Google Maps Javascript API v3路由迭代

时间:2016-10-11 21:47:28

标签: javascript json google-maps google-maps-api-3

我正在努力使用Google Maps JavaScript API。我试图自己解析DirectionsResult以显示一些数据,然后将它们传递给数据库。

然而,迭代循环

for (i = 0; i < response.routes.length; i++)
{ var route = response.routes[i];` 

似乎没有赶上路线[i]提供的所有数据。我正在尝试显示路由摘要但是如果使用i定义索引,则无法获得除路由[1]摘要之外的任何摘要。如果我使用数字定义routeIndex,它就可以正常工作。

这是我的代码段:

&#13;
&#13;
<script src="http://maps.google.com/maps/api/js&libraries=geometry" type="text/javascript"></script>
    <script type="text/javascript">
    
    var map = null;
    var boxpolys = null;
    var directions = null;
    var routeBoxer = null;
    var distance = null; // km
    
    function initialize() {
      // Default the map view to Finland.
      var mapOptions = {
        center: new google.maps.LatLng(65.25, 25.35),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false,
        streetViewControl: false,
        zoomControl: false,
        zoom: 5
      };
      
      map = new google.maps.Map(document.getElementById("map"), mapOptions);
      
      directionService = new google.maps.DirectionsService();
      directionsRenderer = new google.maps.DirectionsRenderer({ 
      	map: map
      });      
    }
    
    function route() {
      
      var request = {
        origin: "Sastamala+Finland",
        destination: "Tampere+Finland",
        travelMode: google.maps.DirectionsTravelMode.DRIVING,
        provideRouteAlternatives: true
      }
      
      // Make the directions request
      directionService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) { 
        	directionsRenderer.setDirections(response);
        	parseJson(response);
        	console.log(response);
                       
        } else {
          alert("Directions query failed: " + status);
        }
      });
    }
	
		// Parse JSON

		function parseJson(response) {
    	for (i = 0; i < response.routes.length; i++) {
       	 	var route = response.routes[i];
       	 		// Route atribuutit
       	 // Push alternative routes to results div	
		document.getElementById("results").innerHTML = "";
		document.getElementById("results").innerHTML += route.summary; 
		console.log(route.summary);                   	
       	 	for (j = 0; j < route.legs.length; j++) {
            	var leg = route.legs[j];
            	// Leg atribuutit
            			for (k = 0; k < leg.steps.length; k++) {
               	 		var step = leg.steps[k];
               	// Steps atribuutit
               	 	
            }
        }        
    }		

}   // End of JSON parse
  </script>
&#13;
html, body {
        height: 100%;
        margin: 0;
        padding: 0;
    }
    #map {
      height: 90%;
      width: 70%;
      float: left;
    }
    #results {
      height: 90%;
      width: 30%;
      float: right;
    }

    #controls {
    	position: absolute;
    	top: 50px;
      font-family: sans-serif;
      font-size: 11pt;
    }
&#13;
<body onload="initialize();">
  	<div id="controls"></div>
    <input type="submit" onclick="route()"/>
    <div id="map"></div>
    <div id="results"></div>
  </body>
&#13;
&#13;
&#13;

我知道DirectionsResult.routes.summary不再被记录,但DirectionsRenderer可以提供与#34相同的功能;建议路线&#34;所以应该可以制作。

UPDATE1 :我通过取消所有不必要的东西来更新我的代码。代码返回2个路由的数组,我可以从控制台看到,但是当我试图显示每个路由的摘要时,它总是只显示路由[1] .summary,这是&#34; Sastamalantie / Reitti 249 ja Porintie / Reitti 11&#34;路线[0]。总结是&#34; Reitti 12&#34;并且不显示。两种情况都输出相同的东西: 1. document.getElementById("results").innerHTML += route.summary; 2. console.log(route.summary);

UPDATE2 :提供的答案解决了我的问题,但我遇到了有关同一迭代循环的另一个问题。

      // Make the directions request
  directionService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) { 
        directionsRenderer.setDirections(response);
        parseJson(response);
        console.log(response);
        google.maps.event.addListener(directionsRenderer, 'routeindex_changed', function() { 
        console.log(this.getRouteIndex());
    });

    } else {
      alert("Directions query failed: " + status);
    }
  });
}

    // Parse JSON

    function parseJson(response) {
    var resultsHTML = "";
    for (i = 0; i < response.routes.length; i++) {
        var route = response.routes[i];
            // Route atribuutit
            route.overview_path;
            var pathPolyline = route.overview_polyline;
            var routeName = route.summary;  
                resultsHTML += "<p onclick='directionsRenderer.setRouteIndex(i)'>" + (i+1) + ": " + routeName + " ";    
                console.log(routeName);  // setRouteIndex(i) returns always 3.                  
        for (j = 0; j < route.legs.length; j++) {
            var leg = route.legs[j];
                var routeDistance = leg.distance.text;
                var routeDuration = leg.duration.text;
                    resultsHTML += routeDistance + " " + routeDuration + "</p>";
            // Leg atribuutit
                    for (k = 0; k < leg.steps.length; k++) {
                    var step = leg.steps[k];
            // Steps atribuutit     
        }
    }        
}
    // Push alternative routes to results div
    document.getElementById("results").innerHTML = resultsHTML;

我现在正在显示route.summary,就像它应该一样但在resultsHTML += "<p onclick='directionsRenderer.setRouteIndex(i)'>" + (i+1) + ": " + routeName + " ";行中,当点击每个<p>时,setRouteIndex(i)返回到控制台值3并绘制地图路线[ 3],它应该为每个<p>标签定义一个相应的routeIndex。然而,i + 1显示每条路线的正确routeIndex编号,例如。 1:路线,2:路线。

1 个答案:

答案 0 :(得分:0)

您正在覆盖&#34;结果&#34;中第一条路线的输出。 DIV:

var map = null;
var boxpolys = null;
var directions = null;
var routeBoxer = null;
var distance = null; // km

function initialize() {
  // Default the map view to Finland.
  var mapOptions = {
    center: new google.maps.LatLng(65.25, 25.35),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: false,
    streetViewControl: false,
    zoomControl: false,
    zoom: 5
  };

  map = new google.maps.Map(document.getElementById("map"), mapOptions);

  directionService = new google.maps.DirectionsService();
  directionsRenderer = new google.maps.DirectionsRenderer({
    map: map
  });
}
google.maps.event.addDomListener(window, 'load', initialize);

function route() {
  var request = {
    origin: "Sastamala+Finland",
    destination: "Tampere+Finland",
    travelMode: google.maps.DirectionsTravelMode.DRIVING,
    provideRouteAlternatives: true
  }

  // Make the directions request
  directionService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsRenderer.setDirections(response);
      parseJson(response);
      console.log(response);

    } else {
      alert("Directions query failed: " + status);
    }
  });
}

// Parse JSON
function parseJson(response) {
    document.getElementById("results").innerHTML = "";
    for (i = 0; i < response.routes.length; i++) {
      var route = response.routes[i];
      // Route atribuutit
      // Push alternative routes to results div	
      document.getElementById("results").innerHTML += i + ":" + route.summary + "<br>";
      console.log(route.summary);
      for (j = 0; j < route.legs.length; j++) {
        var leg = route.legs[j];
        // Leg atribuutit
        for (k = 0; k < leg.steps.length; k++) {
          var step = leg.steps[k];
          // Steps atribuutit
        }
      }
    }
  } // End of JSON parse

删除第一行(或将其移出循环外)。

代码段

&#13;
&#13;
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#map {
  height: 90%;
  width: 70%;
  float: left;
}
#results {
  height: 90%;
  width: 30%;
  float: right;
}
#controls {
  position: absolute;
  top: 50px;
  font-family: sans-serif;
  font-size: 11pt;
}
&#13;
<script src="https://maps.google.com/maps/api/js?libraries=geometry" type="text/javascript"></script>
<div id="controls"></div>
<input type="submit" onclick="route()" />
<div id="map"></div>
<div id="results"></div>
&#13;
SELECT a.acnum, a.title, a.famname, a.givename, count(au.panum)
FROM ACADEMIC a 
JOIN AUTHOR au ON a.acnum = au.acnum 
GROUP BY a.ACNUM, a.title, a.famname, a.givename 
HAVING COUNT(au.panum) < 20;
&#13;
&#13;
&#13;