【发布时间】:2014-10-07 03:51:54
【问题描述】:
我正在编写一个应用程序,该应用程序将按名称或与用户的距离对位置进行排序。除了距离之外,一切都按原样进行。从理论上讲,我应该能够通过地理位置获取用户的坐标,并且我已经有了每个位置的坐标。我不应该能够使用这些坐标运行半正弦公式并通过object.distance = d 将距离附加到每个位置吗?这是我的代码,也是我项目的一部分。
Plunker:http://plnkr.co/edit/nRQc7Ym0lsaK6jQwd626?p=preview
代码:
var app = angular.module('app', []);
app.controller('firstCtrl', function($scope) {
$scope.ASiteLocs = [{
"name": "IL5077 BRUSSELS",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-90.58543899999999,38.955472,0"
}
}, {
"name": "IL5076 KAMPSVILLE",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-90.661923,39.29403,0"
}
}, {
"name": "IL5146 CARROLLTON",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-90.39965700000001,39.309142,0"
}
}, {
"name": "IL5153 GREENFIELD",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-90.208747,39.364077,0"
}
}];
$scope.SSiteLocs = [More Locations...];
$scope.SiteLocs = $scope.SSiteLocs.concat($scope.ASiteLocs);
repoSortOrder = "site.name";
navigator.geolocation.getCurrentPosition(GetLocation);
function GetLocation(location) {
Lat = location.coords.latitude;
Lon = location.coords.longitude;
}
angular.forEach($scope.SSiteLocs, function(object) {
object.carrier = 'Sprint';
getCoordDistance();
object.distance = $scope.d
});
angular.forEach($scope.ASiteLocs, function(object) {
object.carrier = 'AT&T';
getCoordDistance();
object.distance = $scope.d
});
angular.forEach($scope.SiteLocs, function(location) {
var clength = location.Point.coordinates.length;
if (location.Point.coordinates.substring(clength - 2, clength) === ",0") {
location.Point.coordinates = location.Point.coordinates.substring(0, clength - 2).split(",");
Lat = location.Point.coordinates[0];
Lon = location.Point.coordinates[1];
Com = ",";
location.Point.coordinates = Lon.concat(Com, Lat);
}
});
function getCoordDistance() {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
var lat2 = Lat;
var lon2 = Lon;
var lat1 = 45;//Test Lat
var lon1 = -50;//Test 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));
$scope.d = R * c;
}
});
在上面的代码中,当我在 getCoordDistance() 中使用整数作为纬度/经度时,例如 lat1 = 5,lat2 = 10,lon1 = 0,lon2 = 0 它可以工作并添加到每个位置的距离。但是当我尝试使用我的位置时它失败了。有任何想法吗?
提前感谢您的帮助。
【问题讨论】:
标签: javascript angularjs geolocation coordinates haversine