Events: listening to your users [Feb. 13, 2012, 10:22 p.m.]
---This section shows how to detect and respond to your users moving and zooming the map---
In programming-speak, an event is generated whenever the user moves the mouse, clicks, types a key, or does other actions, such as moving and zooming a map. Event listeners detect and respond to these events. A good example is how Leaflet.js will open a popup window when you click on a marker.
Suppose we want a map which changes when the user zooms out. We need to create an event listener, so that our code will respond when the user changes the zoom. Use the reference at http://leaflet.cloudmade.com/reference.html#map-events to research the event type which we should look for. Under EVENT_TYPES, the map object has an event called zoomend.
We connect the Leaflet map's zoomend event by adding something like this after your map is created. It will pop up "you zoomed the map!" every time you change the zoom.
map.on( "zoomend", function( e ) {
alert( " you zoomed the map! " )
});
http://jsfiddle.net/8QHFe/8/
To make this event listener useful, we need to have it act on the map. You probably want to know what the new zoom level is, so we will need to call map.getZoom() to see that. Change the function to this:
map.on( "zoomend", function( e ) {
alert( map.getZoom() )
});
Run this, and you'll see that zooming in adds to this zoom level, and zooming out subtracts. There are only integer zoom levels. I've decided that if your zoom level becomes 3 or lower, I will remove the marker from the map.
map.on( "zoomend", function( e ) {
zoom = map.getZoom( );
if ( zoom <= 3 ) {
map.removeLayer( marker );
}
});
Cool, but not all that useful. This was a better example from earlier:
marker.on('mouseover', function(e){
marker.openPopup();
});
This makes it so that you don't have to click a marker for its popup to appear - you can just move the mouse over it and trigger the mouseover event.
You can research other events, such as moveend , to redraw parts of your map and load more information when the user moves to a new area. Many websites use this event so that the page's sidebar will only show information about places which are visible on your map ( Yelp.com is a great example of this for restaurant search ). You could also use this to keep users from moving the map too much and losing the site which you've mapped.