【发布时间】:2014-08-08 17:07:08
【问题描述】:
我正在编写一个具有大量位置的应用程序,所有位置都带有坐标,我希望该应用程序能够按名称或最近的位置搜索位置。我知道如何通过半正弦公式确定两个坐标之间的距离。但是,我希望我的应用程序遍历数组中的每个对象(位置)并向该对象添加一个名为 distance 的新元素,distance 应该是从我的位置到该位置的距离。我有以下代码,我认为应该可以工作,但事实并非如此。有人有什么想法吗?
function GetLocation(location) {
myLat = location.coords.latitude;
myLon = location.coords.longitude;
angular.forEach($scope.ASiteLocs, function(object, location) {
location.Point.coordinates = location.Point.coordinates.substring(0, clength - 2).split(",");
Lat = location.Point.coordinates[0];
Lon = location.Point.coordinates[1];
function getCoordDistance() {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
var lat2 = myLat;
var lon2 = myLon;
var lat1 = Lat;
var lon1 = Lon;
var R = 3959; // Radius in miles
//has a problem with the .toRad() method below.
var x1 = lat2 - lat1;
var dLat = x1.toRad();
var x2 = lon2 - lon1;
var dLon = x2.toRad();
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
}
object.distance = d;
});
}
这是地点的样子(只是其中的几个):
"name": "502 Nelson St, Greenville, MS 38701",
"visibility": "0",
"description": "502 Nelson St, Greenville, MS 38701",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-91.05636,33.415485,0"
}
}, {
"name": "242 Blackhawk Trace, Galena, IL 61036",
"visibility": "0",
"description": "242 Blackhawk Trace, Galena, IL 61036",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-90.319778,42.390862,0"
}
}, {
"name": "3747 Ocean Dr, Vero Beach, FL 32963",
"visibility": "0",
"description": "3747 Ocean Dr, Vero Beach, FL 32963",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-80.358248,27.659094,0"
}
}
这是我的工作的一部分,如果这样更容易阅读的话。
http://plnkr.co/edit/nRQc7Ym0lsaK6jQwd626?p=preview
【问题讨论】:
-
你的函数是从哪里得到 $scope 的?
-
它被引入应用程序的另一部分。 @msarchet
-
你在哪里调用
getCoordDistance你定义了函数但从不调用它 -
不是在
forEach()中调用的吗? @msarchet
标签: javascript arrays angularjs coordinates haversine