如何计算两个给定LatLng点之间的行驶距离?

时间:2014-07-17 17:55:33

标签: google-maps latitude-longitude google-maps-api-2

当给出纬度和经度时,我需要计算两点之间的行驶距离(不是地址)! 我怎么能够?

<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"></script>
<script type="text/javascript">

var geocoder, location1, location2, gDir;

function initialize() {
    geocoder = new GClientGeocoder();
    gDir = new GDirections();
     location1 = {lat: '27.68389267163743', lon: '85.30214309692383', address: 'Sanepa'};


                    location2 = {lat: '27.674581642945725', lon: '85.32673358917236', address: 'Patan'};
                    gDir.load('from: ' + (location1.lat + ", " + location1.lon) + ' to: ' + (location2.lat + ", " + location2.lon));




    GEvent.addListener(gDir, "load", function() {

        var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
        alert("Distance is" + drivingDistanceKilometers); 
    });
}

function showLocation() {





}

</script>

当我在gDir.load()函数中将地址作为参数传递时,它可以工作,但现在我只需要从纬度和经度计算。请帮忙。

1 个答案:

答案 0 :(得分:0)

请不要使用API​​ v2,因为它已经被弃用了很长时间,并且可能随时停止运行。

如果您绝对必须使用它,那么使用loadFromWaypoints方法完成所需的方法是:

gDir.loadFromWaypoints([(new GLatLng(lat,lng)),(new GLatLng(lat,lng))]);

https://developers.google.com/maps/documentation/javascript/v2/reference#GDirections.loadFromWaypoints