对于航点内的循环 - 谷歌地图

时间:2014-05-25 21:15:39

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

我正在尝试显示一个带路标的路线。我将所有坐标保存到MySQL varchar属性然后用php将其拉出并将其切成数组,这样两个数组元素结果[0]和fruits [1]代表开始,结果[2]和水果[ 3]代表第一个航路点,即第二个航线点,等等。

我正在尝试显示旅程的路线,如果我不使用航点,它就会完美地工作,也就是说,如果我没有用开始和结束之外的所有点填充路径数组。< / p>

这是我的代码

 <style>
      #map-canvas {
        width: 100%;
            height: 400px;
          }
        </style>

        <script type="text/javascript">
            var fruits = <?php echo json_encode($arr); ?>;

            for (var i = 0; i < fruits.length; i+=2) {
           //text += cars[i]; 
            }

          </script>

     <script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var dbk = new google.maps.LatLng(fruits[0], fruits[1]);
  var mapOptions = {
    zoom: 11,
    center: dbk,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  directionsDisplay.setMap(map);
  calcRoute();
}
 function calcRoute() {

    var waypts = [];

    for (var i = 2; i < fruits.length -2; i+=2) {
      waypts.push(new google.maps.LatLng(fruits[i], fruits[i+1])); 
    };

    var request = {
        origin: new google.maps.LatLng(fruits[0], fruits[1]),
        destination: new google.maps.LatLng(fruits[fruits.length-2],fruits[fruits.length-1] ),
        waypoints: waypts,
        optimizeWaypoints: true,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
        var route = response.routes[0];
        var summaryPanel = document.getElementById("directions_panel");
        summaryPanel.innerHTML = "";
        // For each route, display summary information.
        for (var i = 0; i < route.legs.length; i++) {
          var routeSegment = i + 1;
          summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
          summaryPanel.innerHTML += route.legs[i].start_address + " to ";
          summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
          summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
        }
      } else {
        alert("directions response "+status);
      }
    });
  }

google.maps.event.addDomListener(window, 'load', initialize);

    </script>

1 个答案:

答案 0 :(得分:0)

您需要使用Directions Waypoints作为航点。

var waypts = [];

for (var i = 2; i < fruits.length -2; i+=2) {
  waypts.push({
     location:new google.maps.LatLng(fruits[i], fruits[i+1]),
     stopover:true
  }); 
};

Working example with single LatLng waypoint