簡體   English   中英

具有多個停靠點/航點的 Google Maps Route API

[英]Google Maps Route API with multiple stops/waypoints

我正在嘗試使用 Google Maps API 在多個站點之間繪制源和目的地之間的路線。 我將傳遞源、目的地和所有停靠點的緯度和日志值。我嘗試使用基本代碼段,但代碼(如下)在每個停靠點之間繪制了一條路線。

[![<script type="text/javascript">
    var markers = [
            {
                "timestamp": 'Alibaug',
                "latitude": '18.641400',
                "longitude": '72.872200',
                "description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
            },
            {
                "timestamp": 'Mumbai',
                "latitude": '18.964700',
                "longitude": '72.825800',
                "description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
            }
        ,
            {
                "timestamp": 'Pune',
                "latitude": '18.523600',
                "longitude": '73.847800',
                "description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
            }
    \];
    window.onload = function () {
        var mapOptions = {
            center: new google.maps.LatLng(markers\[0\].latitude, markers\[0\].longitude),
            zoom: 10,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
        var infoWindow = new google.maps.InfoWindow();
        var lat_lng = new Array();
        var latlngbounds = new google.maps.LatLngBounds();
        for (i = 0; i < markers.length; i++) {
            var data = markers\[i\]
            var myLatlng = new google.maps.LatLng(data.latitude, data.longitude);
            lat_lng.push(myLatlng);
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: data.timestamp
            });
            // console.log(i)

            latlngbounds.extend(marker.position);
            (function (marker, data) {
                google.maps.event.addListener(marker, "click", function (e) {
                    infoWindow.setContent(data.timestamp);
                    infoWindow.open(map, marker);
                });
            })(marker, data);
        }
        map.setCenter(latlngbounds.getCenter());
        map.fitBounds(latlngbounds);

        //***********ROUTING****************//

        //Initialize the Path Array
        var path = new google.maps.MVCArray();

        //Initialize the Direction Service
        var service = new google.maps.DirectionsService();

        //Set the Path Stroke Color
        var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });


        //Loop and Draw Path Route between the Points on MAP
        for (var i = 0; i < lat_lng.length; i++) {
            if ((i + 1) < lat_lng.length) {
                var src = lat_lng\[i\];
                var des = lat_lng\[i + 1\];
                path.push(src);
                poly.setPath(path);
                service.route({
                    origin: src,
                    destination: des,
                    travelMode: google.maps.DirectionsTravelMode.WALKING
                }, function (result, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        for (var i = 0, len = result.routes\[0\].overview_path.length; i < len; i++) {
                            path.push(result.routes\[0\].overview_path\[i\]);
                        }
                    }
                });
            }
        }
    }
</script>][1]][1]

在此處輸入圖片說明

在上圖中,繪制了一條額外的路線。

小提琴演示問題更多點

您的代碼中有拼寫錯誤/錯誤。 刪除這一行:

path.push(src);

從這個循環:

    //Loop and Draw Path Route between the Points on MAP
    for (var i = 0; i < lat_lng.length; i++) {
        if ((i + 1) < lat_lng.length) {
            var src = lat_lng[i];
            var des = lat_lng[i + 1];
            // path.push(src); <============================================ here
            poly.setPath(path);
            service.route({
                origin: src,
                destination: des,
                travelMode: google.maps.DirectionsTravelMode.WALKING
            }, function (result, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                        path.push(result.routes[0].overview_path[i]);
                    }
                }
            });
        }
    }

第二個問題來自方向服務的異步特性。 不能保證服務響應的順序與發送請求的順序相同。 解決這個問題的最簡單方法是為每個結果創建一個單獨的折線:

 function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {

      //Initialize the Path Array
      var path = new google.maps.MVCArray();
      //Set the Path Stroke Color
      var poly = new google.maps.Polyline({
        map: map,
        strokeColor: '#4986E7'
      });
      poly.setPath(path);
      for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
        path.push(result.routes[0].overview_path[i]);
      }
    }
  });

概念證明小提琴

結果地圖的屏幕截圖

代碼片段:

 var markers = [{ "timestamp": 'Alibaug', "latitude": '18.641400', "longitude": '72.872200', "description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.' }, { "timestamp": 'Mumbai', "latitude": '18.964700', "longitude": '72.825800', "description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.' }, { "timestamp": 'Pune', "latitude": '18.523600', "longitude": '73.847800', "description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.' }, { "timestamp": 'Bhopal', "latitude": '23.2599', "longitude": '73.857800', "description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.' }, { "timestamp": 'Bhopal', "latitude": '26.9124', "longitude": '75.7873', "description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.' } ]; window.onload = function() { var mapOptions = { center: new google.maps.LatLng(markers[0].latitude, markers[0].longitude), zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions); var infoWindow = new google.maps.InfoWindow(); var lat_lng = new Array(); var latlngbounds = new google.maps.LatLngBounds(); for (i = 0; i < markers.length; i++) { var data = markers[i] var myLatlng = new google.maps.LatLng(data.latitude, data.longitude); lat_lng.push(myLatlng); var marker = new google.maps.Marker({ position: myLatlng, map: map, title: data.timestamp }); // console.log(i) latlngbounds.extend(marker.position); (function(marker, data) { google.maps.event.addListener(marker, "click", function(e) { infoWindow.setContent(data.timestamp); infoWindow.open(map, marker); }); })(marker, data); } map.setCenter(latlngbounds.getCenter()); map.fitBounds(latlngbounds); //***********ROUTING****************// //Initialize the Direction Service var service = new google.maps.DirectionsService(); //Loop and Draw Path Route between the Points on MAP for (var i = 0; i < lat_lng.length; i++) { if ((i + 1) < lat_lng.length) { var src = lat_lng[i]; var des = lat_lng[i + 1]; // path.push(src); service.route({ origin: src, destination: des, travelMode: google.maps.DirectionsTravelMode.WALKING }, function(result, status) { if (status == google.maps.DirectionsStatus.OK) { //Initialize the Path Array var path = new google.maps.MVCArray(); //Set the Path Stroke Color var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' }); poly.setPath(path); for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) { path.push(result.routes[0].overview_path[i]); } } }); } } }
 /* Always set the map height explicitly to define the size of the div * element that contains the map. */ #dvMap { height: 100%; } /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
 <div id="dvMap"></div> <!-- Replace the value of the key parameter with your own API key. --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"> </script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM