Google Direction Service - 从当前位置到指定目的地的路线

时间:2017-03-09 14:23:37

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

这是我的脚本,目前根据用户选择的内容显示汽车或公交路线。

是否有人知道如何调整此脚本以将原点设置为用户当前位置和路由,以设置lat + long目标。

由于我目前无法找到将其整合到我的脚本中的方法 - 任何帮助都将非常感谢!

      function initMap() {
        var directionsDisplay = new google.maps.DirectionsRenderer;
        var directionsService = new google.maps.DirectionsService;
          
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 14,
          center: {lat: *VALUE*, lng: *VALUE*}
        });
        directionsDisplay.setMap(map);
        directionsDisplay.setPanel(document.getElementById('right-panel'));

        calculateAndDisplayRoute(directionsService, directionsDisplay);
        document.getElementById('mode').addEventListener('change', function() {
          calculateAndDisplayRoute(directionsService, directionsDisplay);
        });
      }

      function calculateAndDisplayRoute(directionsService, directionsDisplay) {
        var selectedMode = document.getElementById('mode').value;
        directionsService.route({
          origin: {lat: *VALUE*, lng: *VALUE*},  // Haight.
          destination: {lat: *VALUE*,lng: *VALUE*},  // Ocean Beach.
          // Note that Javascript allows us to access the constant
          // using square brackets and a string value as its
          // "property."
          travelMode: google.maps.TravelMode[selectedMode],
           transitOptions: {
           arrivalTime: new Date(1489242600000),
           routingPreference: 'FEWER_TRANSFERS'
        },
            unitSystem: google.maps.UnitSystem.IMPERIAL,
             provideRouteAlternatives: true
        }, function(response, status) {
            
          if (status == 'OK') {
            directionsDisplay.setDirections(response);
          } else {
            window.alert('Directions request failed due to ' + status);
          }
        });
      }

1 个答案:

答案 0 :(得分:0)

在google Directions API中,您可以阅读可添加的参数。在您的情况下,如果您计划制作多个站点的路线,则需要原点和目的地以及航点。

https://developers.google.com/maps/documentation/directions/intro#Waypoints

在下面的链接中,有一个示例如何选择多个航点。对于该位置,您可以使用地理位置来获取纬度和经度。这些可以在origin参数的calculateAndDisplay函数中实现。

directionsService.route({
          origin: //here you can put lat/long or a name
          destination: //here you can put lat/long or a name
          waypoints: // waypoints expect an Array of locations or lat/long
          optimizeWaypoints: true,
          travelMode: 'DRIVING'
},

https://developers.google.com/maps/documentation/javascript/examples/directions-waypoints