2017-03-09 36 views
0

这是我的脚本,它根据用户选择的内容显示车辆或公交路线。Google定向服务 - 从当前位置到指定目的地的路线

有人会知道如何修改这个脚本来设置原点作为用户当前的位置和路线从那里设置lat +长的目的地。

由于我目前一直无法找到一种方法来整合这个在我的脚本 - 任何帮助将不胜感激!

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

+0

http://stackoverflow.com/questions/42696379/get-directions-to-predefined-destination-from-current-location-geolocation这个回答我的问题。 –

回答

0

在谷歌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

相关问题