0
votes

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

1 Answers

0
votes

It doesn't look like this is easily accomplishable in mobile web, so I just created a third marker that moves according to the user's position.