javascript - 具有多个停靠点/航点的 Google Maps Route API

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

我正在尝试使用 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]

enter image description here

在上图中,绘制了一条额外的路线。

fiddle demonstrating issue with more points

最佳答案

您的代码中有错字/错误。删除这一行:

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]);
      }
    }
  });

proof of concept fiddle

screenshot of resulting map

代码片段:

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>

关于javascript - 具有多个停靠点/航点的 Google Maps Route API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60056946/

相关文章:

使用包含时,带有 margin-left 的 jQuery 可拖动元素不会向左移动

javascript - 谷歌地图手绘

javascript - SugarCRM 新库存安装样式和脚本未正确链接

javascript - 我应该使用 canvas 来制作带有 js 的简单图像动画吗?

Jquery 和输入文件

javascript - 如何使用 jQuery 而不是 RJS 来处理复杂的表单

javascript - 倒数计数器,用户可以在其中输入结束日期

javascript - 如何动态设置div大小?

java - 谷歌的距离矩阵API也考虑 "Elevation"吗?

javascript - 在谷歌地图中将数据分箱到六边形网格中