简体   繁体   中英

Google Maps API: Combining Directions Service with watchPosition Geolocation

I'm trying to display a map using Google's directions service with an origin, destination, and the blue directions line connecting the two. However, I am trying to use watchPosition for the origin lat/lng.

So far everything displays correctly, except the green origin marker doesn't move as watchPosition updates with new lat/lng coordinates. Is what I'm trying to do possible? Or would I just have to create a third marker that follows the user's coordinates?

Here is what I have in my script:

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

    function initialize() {
      directionsDisplay = new google.maps.DirectionsRenderer();
      var mapOptions = {
        zoom:7,
        center: new google.maps.LatLng(38.5815719, -121.4943996)
      }
      map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
      directionsDisplay.setMap(map);
      calcRoute();
}

function handleNoGeolocation(errorFlag) {
  if (errorFlag) {
    var content = 'Error: The Geolocation service failed.';
} else {
    var content = 'Error: Your browser doesn\'t support geolocation.';
}

  var options = {
    map: map,
    position: new google.maps.LatLng(<%= @order.origin_lat %>, <%= @order.origin_lng %>),
    content: content
  };

  var infowindow = new google.maps.InfoWindow(options);
  map.setCenter(options.position);
}



function calcRoute() {
    if(navigator.geolocation) {
        navigator.geolocation.watchPosition(function(position) {
            var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            var request = {
                  origin: pos,
                  destination: new google.maps.LatLng(<%= @order.user.latitude %>, <%= @order.user.longitude %>),
                  travelMode: google.maps.TravelMode.DRIVING
              };
            directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                  directionsDisplay.setDirections(response);
                }
            });
        },

        function() {
        handleNoGeolocation(true);
        });
    } else {
    // Browser doesn't support Geolocation
        handleNoGeolocation(false);
    }

}

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

看起来这在移动网络中不容易实现,因此我刚刚创建了第三个标记,该标记根据用户的位置移动。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM