user2454340
user2454340

Reputation: 1220

dynamic route with Google directions API

Initially I have two points on map. One of them being origin and other being destination.

The origin is dragable while destination is fixed.

When drawing the map for first time after page load, I have some default value for origin, while destination point gets value from database.Initial Loading works fine. I am able to draw route between origin and destination.

I draw directions on map using this below function

function calcRoute() {
  var request = {
      origin:myLatLng1,
      destination:myLatLng,
      optimizeWaypoints: true,
      travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
}

Now I have a event listener whenever my origin marker is draged, it gets the new latlong of the new position of orign marker, then I call the same function above to get new route.

function togglePos(){
    myLatLng1 = new google.maps.LatLng(marker1.getPosition());
    calcRoute();
}

This is where I am facing problem, I am not able to redraw new route between the new marked origin and the same old destination. This is my initialize function if any1 needs it.

function initialize() {
    var mapOptions = {
        zoom: 13,
        center: myLatLng
    };
    map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);

    directionsDisplay.setMap(map);

    var image = 'myimage.png';

    marker = new google.maps.Marker({
          position: myLatLng,
          map: map,
          icon: image,
    });
    marker1 = new google.maps.Marker({
          position: myLatLng1,
          map: map,
          draggable: true
    });
    google.maps.event.addListener(marker1, 'dragend', togglePos);

    calcRoute();
}

I am not getting any javascript error. I am building something like this.
https://developers.google.com/maps/documentation/javascript/examples/directions-simple

But instead of selecting it from drop down box, I am calling the function when marker is moved.

Fiddle link: http://jsfiddle.net/FvqAL/4/ But i have no idea why its not working on fiddle :|

Upvotes: 0

Views: 4238

Answers (1)

user2454340
user2454340

Reputation: 1220

I made some changes in calc route, now whenever it is called, it get marker1 position and draw route through it.

function calcRoute() {
  var request = {
      origin:marker1.getPosition(),
      destination:myLatLng,
      optimizeWaypoints: true,
      travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
}

Here is final fiddle if you want to check it out. Thanks for helping :)

Upvotes: 1

Related Questions