Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating Maps V3 with 'idle' Listener. Opening InfowWindow triggers this and hides the marker

This loads the map, gets new results and removes the old ones:

google.maps.event.addListener(map, 'idle', function() {
    updateMap();
});

That part works great.

My trouble comes when I click on a marker to open it's InfoWindow. Opening an InfoWindow re-centers the map around the marker, which triggers the Listener from above, which then resets the map, hiding the InfoWindow.

Here is how I am creating the markers/InfoWindow:

var infowindow = new google.maps.InfoWindow({});

function makeMarker(LatLong, markerName) { //this is called from a loop 
    var marker = new google.maps.Marker({
        position: LatLong,
        map: map,
        title:markerName,
        content: "html for the infoWindow"
    });

    //Detect marker click
    google.maps.event.addListener(marker, "click", function() {
        infowindow.setContent(this.content);
        infowindow.open(map, marker);
    });
} 

Any insights are greatly appreciated.

like image 991
kamchatka Avatar asked Jan 10 '12 21:01

kamchatka


1 Answers

updateMap might be where the underlying problem is. When you're updating the map you really don't need to be deleting every marker and adding it again; instead you want to remove the ones that you no longer need and add the ones that you do. (Admittedly, the first strategy is much simpler and works well for most use cases.)

Alternatively, there are two approaches I'd explore:

  1. Store a global variable like markerClick and implement something like:

    google.maps.event.addListener(map, 'idle', function() {
      if(!markerClick){
        updateMap();
        markerClick = false;
      }
    });
    
    
    
    google.maps.event.addListener(marker, "click", function() {
      markerClick = true;
      infowindow.setContent(this.content);
      infowindow.open(map, marker);
    });
    

    The one ceveat being that is really a quick hack, and could definitely cause trouble if a marker is clicked that doesn't trigger the idle event (i.e. one in the center or something).

  2. Don't use idle anymore. Events like dragend and zoom_changed might better capture the specific user interactions you're looking for.

like image 73
bamnet Avatar answered Sep 23 '22 15:09

bamnet