0

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);
 });
Rick
  • 61
  • 5
  • 12

1 Answers1

0

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;
}
wf9a5m75
  • 6,100
  • 3
  • 25
  • 59
  • I tried this and it did not give me the directions to the marker I selected. It still returned directions to another marker in the array. But I do think marker.getPosition() is what I am missing somewhere in my code. I just need to figure out where, – Rick Nov 29 '12 at 20:13
  • I found this example: http://econym.org.uk/gmap/example_map4c.htm which I beleive passes the marker location through this code `'';` This code uses the google maps api v2. Will something similar work in V3 or is the getPosition() function what I should be looking to? – Rick Nov 30 '12 at 03:24
  • 1
    Finally figured it out. It was similar to your answer, the key is to get marker.getPosition into the function that has the event listener that opens the infowindow. I think as your function code stands it should be enough to help people get through this problem. Thanks – Rick Nov 30 '12 at 03:47