Google Maps API V3 - Adding Multiple Events to a Single Map

I have the following code that works fine:

google.maps.event.addListener(map, 'dragend', function() {
    bounds = map.getBounds();
    var ne = bounds.getNorthEast(); // LatLng of the north-east corner
    var sw = bounds.getSouthWest(); // LatLng of the south-west corder
    $.when( removeMarkers() ).then( setMarkers(city, state, ne, sw) );
});

What I want is when either one of two events occur, this code is ran. The two events I want are 'dragend' and 'zoom_changed'. I have tried the 'idle' event and it slows down the map and I get things happening that I don't like. It just makes for a bad user experience. However, 'dragend' and 'zoom_changed' events both work good seperatly, I just haven't found a way to combine them. Basically I want the code to run anytime someone pans the map or zooms in or out.

I have tried this code and I get an error that says 'bounds is null' and it points to the second instance of 'bounds' right below the 'zoom_changed' event line:

google.maps.event.addListener(map, 'dragend', function() {
    bounds = map.getBounds();
    var ne = bounds.getNorthEast(); // LatLng of the north-east corner
    var sw = bounds.getSouthWest(); // LatLng of the south-west corder
    $.when( removeMarkers() ).then( setMarkers(city, state, ne, sw) );
});
google.maps.event.addListener(map, 'zoom_changed', function() {
    bounds = map.getBounds();
    var ne = bounds.getNorthEast(); // LatLng of the north-east corner
    var sw = bounds.getSouthWest(); // LatLng of the south-west corder
    $.when( removeMarkers() ).then( setMarkers(city, state, ne, sw) );
 });

1 answer

  • answered 2017-08-16 19:31 Michael Geary

    If you want to run exactly the same code in response to more than one event, put it in a named function and use that function as the event listener for both events.

    Also, why are you using $.when().then() with your removeMarkers() function? Is this an asynchronous function? That would be rather unusual. Any typical implementation of a function that removes some markers would be ordinary synchronous code.

    So you could write the code like this:

    function updateMarkers() {
        bounds = map.getBounds();
        var ne = bounds.getNorthEast();
        var sw = bounds.getSouthWest();
        removeMarkers();
        setMarkers( city, state, ne, sw );
    }
    
    google.maps.event.addListener( map, 'dragend', updateMarkers );
    google.maps.event.addListener( map, 'zoom_changed', upateMarkers );
    

    Having said all this, I have no idea what would be causing the error you ran into. You'll need to post a runnable test case that demonstrates the problem, either in a snippet here or in a fiddle.