Google Maps Pan between markers

2.5k views Asked by At

I have multiple markers on a map that I want the ability to pan between. The idea being that if you click Marker 1 it will pan to Marker 1 being centered, and then if you click Marker 2 it will pan from Marker 1 to Marker 2. I've got the pan to work fine initially, but it won't pan from one marker to another without the user moving the map first.

The current code I'm using is:

google.maps.event.addListener(marker, 'click', function() {
    map.panTo(marker.getPosition());
});

I'm thinking there might be something I'm unaware of when it comes to using multiple marker event listeners in a row (maybe? I'm not sure).

Here's the functioning example as I'm encountering it now:
http://kolosk.us/pan/

Hopefully that's clear, let me know if you can help. Thanks!

1

There are 1 answers

0
geocodezip On BEST ANSWER

There is only one marker variable in your code, left at the last marker created by the loop. The usual solution is to use function closure, associates a unique copy of the marker variable with each event listener.

  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        //icon: image,
        //shape: shape,
        title: beach[0],
        zIndex: beach[3]
    });

    google.maps.event.addListener(marker, 'click', (function(marker) {
      return function() {
        map.panTo(marker.getPosition());
      }
    })(marker));
  }

working example