Search code examples
google-maps-api-3driving-directions

Google Maps API V3: pass marker coordinate to google directions service request


Users search my map with the Google places API which adds markers to my map. I have a click event inside each markers infowindow to get directions to that marker. How do I pass the coordinates of the selected marker to my google directions service request?

So far I declared var placeLoc = null; as a global variable. I defined placeLoc=place.geometry.location; inside my create marker function. Then I have:

function calcRoute() {
 var start = myLatLng;
 var end = placeLoc;
 var request = {
    origin: start,
    destination: end,
    travelMode: google.maps.DirectionsTravelMode.BICYCLING
 };
 directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
    }
 });
}

The function renders directions to the wrong marker. I am guessing that it is just giving directions to the first marker in the array returned after the search and not the actual marker I selected. How do I provide the directions request the coordinates of a selected marker?

Below is the code that places the search results into the place variable:

 google.maps.event.addListener(searchBox, 'places_changed', function() {
     var places = searchBox.getPlaces();
     // alert("getPlaces returns "+places.length+" places");

    for (var i = 0; i < gmarkers.length; i++) {
         gmarkers[i].setMap(null);
    }

    gmarkers = [];
    var bounds = new google.maps.LatLngBounds();

    for (var i = 0, place; place = places[i]; i++) {
       var place = places[i];
       createMarker(place);
       bounds.extend(place.geometry.location);
    }
    map.fitBounds(bounds);
    // if (markers.length == 1) map.setZoom(17);
 });

Solution

  • Something like this?

    function createMarker(options) {
      var marker = new google.maps.Marker(options);
    
      google.maps.event.addListener(marker, 'click', function() {
        placeLoc = marker.getPosition();
        calcRoute();
      });
    
      return marker;
    }