문제

Using google map, you can actually get the different possible routes between two addresses, also you get the length of every possible route.

enter image description here I'm now working on a website with google map, i want to calculate the shortest path between two different addresses same as google map does. then get the path length back as javascript variable.

도움이 되었습니까?

해결책 2

I found it, it can be calculated using google map api called Distance Matrix it returns a json response containing The recommended path's length and Duration.

{
"destination_addresses" : [ "Témara, Maroc" ],
"origin_addresses" : [ "Rabat, Maroc" ],
"rows" : [
  {
     "elements" : [
        {
           "distance" : {
              "text" : "13,6 km",
              "value" : 13620
           },
           "duration" : {
              "text" : "23 minutes",
              "value" : 1358
           },
           "status" : "OK"
        }
     ]
  }
],
"status" : "OK"
}

This should work fine:

function getDistance()
{
var url="http://maps.googleapis.com/maps/api/distancematrix/json?origins=rabat&destinations=temara&mode=driving&language=fr-FR&sensor=false";
var def = new jQuery.Deferred(); 
$.getJSON(url,function(json)
{
if (json.status=="OK")
{
var distance=json.rows[0].elements[0].distance.text;
}
def.resolve(distance);
});
return def.promise();
}

$.when(getDistance()).then(function(distance){
alert(distance);});

Demo

다른 팁

You can use these function:

google.maps.geometry.spherical.computeDistanceBetween (latLng1, latLng1);

The arguments are two LatLng objects.
Make sure you include:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&v=3&libraries=geometry"></script>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top