簡體   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