我正在编写一个具有大量位置的应用程序,所有位置都有坐标,我希望应用程序能够按名称搜索位置,或者哪个位置最接近。我知道如何通过半正弦公式确定两个坐标之间的距离。但是,我希望我的应用程序遍历数组中的每个对象(位置),并向该对象添加一个名为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
答案 0 :(得分:0)
将angular.forEach用于对象数组时,函数的第一个参数是对象,第二个是数组索引:
angular.forEach($scope.ASiteLocs, function(location, arrayIndex) {
...
location.distance = d;
})
注意1:您正在更改forEach中的location.Point.coordinates从字符串到数组,因此GetLocation函数只能工作一次,因为原始位置数组已更改。
注意2:在循环中定义一个函数是不好的做法而且很昂贵'
答案 1 :(得分:0)
如果您在代码中使用我的npm包haversine-calculator
,您的代码会更清晰:
const haversineCalculator = require('haversine-calculator')
const start = {
latitude: -23.754842,
longitude: -46.676781
}
const end = {
latitude: -23.549588,
longitude: -46.693210
}
console.log(haversineCalculator(start, end))
console.log(haversineCalculator(start, end, {unit: 'meter'}))
console.log(haversineCalculator(start, end, {unit: 'mile'}))
console.log(haversineCalculator(start, end, {threshold: 1}))
console.log(haversineCalculator(start, end, {threshold: 1, unit: 'meter'}))
console.log(haversineCalculator(start, end, {threshold: 1, unit: 'mile'}))