[GIS] Alert Box on Marker Google Maps API

google-maps-apijavascript

I have a marker called chicagoMarker and each time the user zooms in closer I would like to alert them if they are getting closer to chicago. I am not sure if I have a problem with my event listener in this instance.

if (score==0) {
    chicagoMarker.setMap(map)
    google.maps.event.addListener(chicagoMarker,'bounds_changed',function(){
        zoom = map.getZoom();
        if (bounds.contains(chicagoMarker)){
            window.alert("Good Job!");
            }
        })

}

Best Answer

Not sure about your code... You create a variable zoom, but then don't use it. You refer to a variable bounds, but I don't see that being created anywhere. You have an event listener set up on the Marker for 'bounds_changed', but the Marker class hasn't got that as an event you can listen for. See the list of events available under 'Events' here: https://developers.google.com/maps/documentation/javascript/reference#Marker

Instead set the event listener on the Map object, for the same event. And I've changed it to see if the Marker's position is inside the Bounds:

if (score == 0) {
    chicagoMarker.setMap(map);

    map.addListener('bounds_changed', function() {
        var bounds = map.getBounds();
        if (bounds.contains(chicagoMarker.getPosition())) {
            window.alert("Good Job!");
        }
    });
}