显示方向的每个步骤地理编码

时间:2010-03-22 21:20:14

标签: javascript google-maps geocoding map-directions

Google Maps API 可以构建从源到目标的路线。在以下Google的示例中,每个步骤都发布到HTML代码中:http://code.google.com/apis/maps/documentation/examples/directions-simple.html

我想获得这个方向的每一步的地理编码,并将它们存储在一个数组中。我相信这是可能的,但我不知道如何处理。

非常感谢您的回答。 此致

1 个答案:

答案 0 :(得分:3)

是的,您可以非常轻松地从GDirections获取各个步骤。

首先,您必须确保在调用getSteps: true方法时传递GDirections.load()选项。然后,您可以简单地遍历GDirections.getRoute(i).getStep(j),如下例所示:

<!DOCTYPE html>
<html> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
   <title>Google Maps Simple Directions Demo</title> 
   <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false" 
              type="text/javascript"></script>
</head> 
<body onunload="GUnload()">
   <div id="map" style="width: 550px; height: 400px"></div> 

   <script type="text/javascript"> 
      var map = new GMap2(document.getElementById("map"));
      var directions = new GDirections(map);

      directions.load('from: London, UK to: Glasgow, UK', { getSteps: true });

      GEvent.addListener(directions, "load", function() {
         if (directions.getNumRoutes() > 0) {
            for (var i = 0; i < directions.getRoute(0).getNumSteps(); i++) {
               directions.getRoute(0).getStep(i).getLatLng().lat();
               directions.getRoute(0).getStep(i).getLatLng().lng();
               directions.getRoute(0).getStep(i).getDescriptionHtml();
               directions.getRoute(0).getStep(i).getPolylineIndex();
               directions.getRoute(0).getStep(i).getDistance().meters;
               directions.getRoute(0).getStep(i).getDuration().seconds;
            }
         }
      });
   </script> 
</body> 
</html>

进一步阅读和参考: