繁体   English   中英

使用Google Maps API之间的距离

[英]Distance between several latlng with Google maps API

如果我在数据库中存储了几个latlng点,并且想将这些点与实际latlng位置进行比较(给出每个latlng点与实际latlng之间的距离),那么使用Google Maps API怎么可能? 还是使用我的数据库会更容易?

计算球面上两点之间的距离需要使用Haversine公式 ,这需要对三角学有充分的了解。

比较简单的方法是利用Google Maps API ,该APIgoogle.maps.geometry.spherical命名空间中具有便捷的功能computeDistanceBetween

这是一些使用computeDistanceBetween示例代码:

var home = ['London', new google.maps.LatLng(51.5, -0.1167)];

var pts = [
        ['Prague', new google.maps.LatLng(50.08, 14.43)],
        ['Paris', new google.maps.LatLng(48.856614, 2.3522219000000177)],
        ['Berlin', new google.maps.LatLng(52.5200065999, 13.404953999999975)]
];

// provide a shortcut for the distance function
var dist = google.maps.geometry.spherical.computeDistanceBetween;

pts.forEach(function(pt){
    var d = dist(home[1], pt[1])/1000;
    // d is now the distance (in km) between the home coordinate and the point
});

参见此处的工作示例: http : //jsfiddle.net/aJTK2/5/

如果您打算将数据库用于此类工作,则可能需要考虑使用PostGIS。 安装PostGIS后:

CREATE EXTENSION postgis;

SELECT ST_Distance( 
    ST_GeographyFromText('POINT(115.764286 -31.746416)'), 
    ST_GeographyFromText('POINT(151.036606 -33.906896)')
);

生产:

   st_distance    
------------------
 3295294.42439749
(1 row)

与Google Maps的输出(大约3700公里(步行,而不是乌鸦飞))相比

所以这似乎是正确的,距离明智的。

请注意,这是球体距离,即在地球表面上的距离,而不是通过它的点对点距离。

请注意PostGIS与Google Maps中的坐标顺序。

要了解有关PostGIS的更多信息:

暂无
暂无

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

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