Data, Maps, Usability, and Performance

Leaflet and Zoom into Country via GeoJSON

Last updated on June 27, 2013 in Development

Leafletjs zoom geoJSON

I was really impressed with Leaflet and UTFgrid but I wondered how hard would it be to allow the end user to highlight countries on mouse hover and zoom into a specific country on mouse click. I did that in my D3 World Map Example by leveraging GeoJSON but Leaflet.js creates a world map using image tiles. Of course, you could load the GeoJSON code as a layer in Leaflet and then use that data to identify countries on mouse over and zoom into the bounds of that country area on click. It’s actually really simple and here is how to do it.

First we draw a setup a simple Leaflet world map with CloudMade tiles. You can load inline GeoJSON with the L.GeoJSON constructor but Leaflet cannot load data from external files. I actually like that, as I prefer to keep the mapping library small. I wrote a simple Ajax function and used that to load the countries GeoJSON file into a Leaflet layer and used the onEachFeature function to attach an event on each layer. layer.getBounds() gives me the bounding box of each country and map.fitBounds(layer.getBounds()); zooms the map to the polyline. The final step is to attach a click event on the map so it will zoom back out to original geo coordinates and zoom level.

Since GeoJSON layer gets translated to SVG paths on the map, I just used path and path:hover CSS attributes to give each country a little visual effect on mouseover. Here is our final map, Leaflet map with zoom to country on click.


Interactive Choropleth Map

Tags: , , , ,

Facebook Twitter Hacker News Reddit More...