javascript apiキー - Google Maps API v3での道順の距離



常に表示 画像 (3)

正式には文書化されていないようですが、以下の例のように、 DirectionsService.route()メソッドからの応答をresponse.trips[0].routes[0].distance.valueことができますresponse.trips[0].routes[0].distance.value

<!DOCTYPE html>
<html> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
   <title>Google Maps JavaScript API v3 Example: Directions Complex</title> 
   <script type="text/javascript" 
           src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head> 
<body style="font-family: Arial; font-size: 13px; color: red;"> 
   <div id="map" style="width: 400px; height: 300px;"></div> 
   <div id="duration">Duration: </div> 
   <div id="distance">Distance: </div> 

   <script type="text/javascript"> 

   var directionsService = new google.maps.DirectionsService();
   var directionsDisplay = new google.maps.DirectionsRenderer();

   var myOptions = {
     zoom:7,
     mapTypeId: google.maps.MapTypeId.ROADMAP
   }

   var map = new google.maps.Map(document.getElementById("map"), myOptions);
   directionsDisplay.setMap(map);

   var request = {
       origin: 'Chicago', 
       destination: 'New York',
       travelMode: google.maps.DirectionsTravelMode.DRIVING
   };

   directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {

         // Display the distance:
         document.getElementById('distance').innerHTML += 
            response.routes[0].legs[0].distance.value + " meters";

         // Display the duration:
         document.getElementById('duration').innerHTML += 
            response.routes[0].legs[0].duration.value + " seconds";

         directionsDisplay.setDirections(response);
      }
   });
   </script> 
</body> 
</html>

距離と期間を示すスクリーンショット:

Google Maps Directions Demoを使用して、成功した道順から距離を取得する方法を考えてみます。

これは私がこれまでに持っているコードです:

var googleMaps = {
  // HTML Nodes
  fromInput: google_maps_from,
  toInput: google_maps_to,

  // API Objects
  dirService: new google.maps.DirectionsService(),
  dirRenderer: new google.maps.DirectionsRenderer(),
  map: null,

  showDirections: function(dirResult, dirStatus) {
    if (dirStatus != google.maps.DirectionsStatus.OK) 
    {
     //Here we'll handle the errors a bit better :P
      alert('Directions failed: ' + dirStatus);
      return;
    }
    else
    {
     //Get the distance here
     //onGDirectionsLoad();
    }

    // Show directions
    googleMaps.dirRenderer.setMap(googleMaps.map);
    googleMaps.dirRenderer.setPanel(document.getElementById("directions"));
    googleMaps.dirRenderer.setDirections(dirResult);
  },

  getSelectedTravelMode: function() {
    return google.maps.DirectionsTravelMode.DRIVING;
  },

  getSelectedUnitSystem: function() {
    return google.maps.DirectionsUnitSystem.METRIC;
  },

  getDirections: function() {
    var fromStr = googleMaps.fromInput;
    var toStr = googleMaps.toInput;
    var dirRequest = {
      origin: fromStr,
      destination: toStr,
      travelMode: googleMaps.getSelectedTravelMode(),
      unitSystem: googleMaps.getSelectedUnitSystem(),
      provideTripAlternatives: true
    };
    googleMaps.dirService.route(dirRequest, googleMaps.showDirections);
  },

  init: function() {
    googleMaps.map = new google.maps.Map(document.getElementById("map_canvas"), {
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    // Show directions onload
    googleMaps.getDirections();
  }
};

// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', googleMaps.init);

私はv2でこれをうまくやることができました、v3と同等のものをうまく処理するのに苦労しました。


ルートにウェイポイントが1つしかない場合、選択した回答は正しく機能します。 複数のウェイポイントがある場合に全長を取得する方法は次のとおりです。

var distance= 0;
for(i = 0; i < response.routes[0].legs.length; i++){
   distance += parseFloat(response.routes[0].legs[i].distance.value);
       //for each 'leg'(route between two waypoints) we get the distance and add it to the total
}   
console.log(distance);

var arr = ["apples", "oranges", "oranges", "oranges", "bananas", "bananas", "oranges"].sort();
var freq = {};
for (var s in arr) freq[s] = freq[s] ? freq[s] + 1 : 0;
arr.sort(function(a, b) { return freq[a] > freq[b] ? -1 : 1; });
for (var i = arr.length - 1; i > 0; i--) if (arr[i] == arr[i - 1]) arr.splice(i,1);
alert(arr.join(","));




javascript google-maps