我试图找到一种更好的方法来计算谷歌地图上两点之间的距离,但结果并不是我所期望的。
例如,我在这里找到的那两个解决方案:Calculate distance between two points in google maps V3是类似的(它产生了aprox.249.3424456 Km - 但它错了,因为Bacau和布加勒斯特之间的距离 - 罗马尼亚 - 是大约300公里)。
plnkr链接:http://plnkr.co/edit/cv25C6pga0lla7xyBDRO?p=preview
或者:
$( document ).ready(function() {
var myLatLng = new google.maps.LatLng({ lat: 46.5610058, lng: 26.9098054 });
var myLatLng2 = new google.maps.LatLng({ lat: 44.391403, lng: 26.1157184 });
var calc1 = google.maps.geometry.spherical.computeDistanceBetween(myLatLng, myLatLng2)/1000;
console.log('calc1 = ' + calc1);
var start = { lat: 46.5610058, lng: 26.9098054 };
var stop = { lat: 44.391403, lng: 26.1157184 };
var rad = function(x) {
return x * Math.PI / 180;
};
var getDistance = function(p1, p2) {
var R = 6378137; // Earth’s mean radius in meter
var dLat = rad(p2.lat - p1.lat);
var dLong = rad(p2.lng - p1.lng);
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(rad(p1.lat)) * Math.cos(rad(p2.lat)) *
Math.sin(dLong / 2) * Math.sin(dLong / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d; // returns the distance in meter
};
var calc2 = getDistance(start, stop)/1000;
console.log('calc2 = ' + calc2);
document.getElementById("test").innerHTML = 'calc1 = ' + calc1 + '<br/>calc2 = ' + calc2;
});
当我尝试使用谷歌地图web api http://maps.googleapis.com/maps/api/distancematrix/json?origins=46.5610058,26.9098054&destinations=44.391403,26.1157184计算这些距离时,它告诉我距离是299公里(这是一个很好的价值 - 巴克乌和布加勒斯特之间的距离 - 罗马尼亚 - 是aprox.300公里)
我更喜欢在本地计算,而不是每次访问网站时,但为什么当我使用&go;。google.maps.geometry.spherical.computeDistanceBetween&#39;函数或Haversine公式计算错误值?
答案 0 :(得分:1)
解决方案是使用distancematrix api进行本地计算:https://developers.google.com/maps/documentation/javascript/distancematrix(必须从API仪表板启用距离矩阵)
var from = new google.maps.LatLng(46.5610058, 26.9098054);
var fromName = 'Bacau';
var dest = new google.maps.LatLng(44.391403, 26.1157184);
var destName = 'Bucuresti';
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [from, fromName],
destinations: [destName, dest],
travelMode: 'DRIVING'
}, callback);
function callback(response, status) {
if (status == 'OK') {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
console.log(results);
for (var j = 0; j < results.length; j++) {
var element = results[j];
var distance = element.distance.text;
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];
}
}
}
}