简体   繁体   English

for循环中的距离计算不起作用

[英]distance calculation in for loop dosen't work

Im now currently developing test geolocation app. 我现在正在开发测试地理位置应用。

I found some codes which are helpful for distance between two points (with latitude longitude coords.) and now im trying is, do loop that formula in for loop to get distance not only two points but many. 我发现了一些对两点之间的距离(使用纬度经度坐标)有帮助的代码,现在我正在尝试的是,在for循环中执行该公式,以获取不仅两点之间的距离,而且可以得到许多点。

lets say I got one reference point, point X, and many other points, and Id like to get each distance between X and A, X and B and so on. 可以说我得到了一个参考点,X点和许多其他点,Id很想得到X与A之间,X与B之间的每个距离,依此类推。

each longitude and latitude of the other points are set in associative-dimensional array like this, 这样,其他点的每个经度和纬度都设置在关联维数组中,

    var response = (

    {

    id = 2;

    latitude = "50";

    longitude = "0";

    username = AAA;

    },

    {

    id = 5;

    latitude = "51";

    longitude = "-1";

    username = BBB;

    },

    {

    id = 6;

    latitude = "52";

    longitude = "-3";

    username = CCC;

    }

    )


    //and pointX data is
    var lat1 = "50";
    var lon1 = "0";

what im trying is; 我在想什么

    for(var i = 0; i < response.length; i++){

        var lat2 = response[i].latitude;
        var lon2 = response[i].longitude;

    //distance in kilometer
    function distance(lat1, lon1, lat2, lon2,response) {
        var radlat1 = Math.PI * lat1/180;
        var radlat2 = Math.PI * lat2/180;
        var radlon1 = Math.PI * lon1/180;
        var radlon2 = Math.PI * lon2/180;
        var theta = lon1-lon2;
        var radtheta = Math.PI * theta/180;
        var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
        dist = Math.acos(dist);
        dist = dist * 180/Math.PI;
        dist = dist * 60 * 1.1515;
        dist = dist * 1.609344;
        return response[i].distanceKm = dist;
    }

but when i run this and output, for example, response[1].distanceKm is Undefined. 但是当我运行它并输出时,例如,response [1] .distanceKm是未定义的。 smthng seems to go wrong. smthng似乎出了错。 but i have no idea... any suggestion? 但我不知道...有什么建议吗?

thank you in advance. 先感谢您。

Your response code declaration is not declared as an array. 您的response代码声明未声明为数组。 It used ( and ) , not [ and ] like an array would use. 它使用() ,而不是像数组那样使用的[] Thus, there is no response[1] (eg it's undefined). 因此,没有response[1] (例如,未定义)。

Arrays are declared using [ and ] like this: 数组使用[]声明如下:

var response = [ /* comma separate data elements here */ ];

As jfriend00 said, response[1] is undefined. 正如jfriend00所说, response[1]是未定义的。 Also you've incorrect object literal definition: 另外,您有不正确的对象文字定义:

{  id = 5;
   latitude = "51";
   longitude = "-1";
   username = BBB;
 },

should be: 应该:

{  id : 5,
   latitude : "51",
   longitude : "-1",
   username : BBB
 },

etc. 等等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM