I have 2 shape files, one that shows all the counties on an island, the other shows all the villages on the island.
Here is the scenario:
My initial map shows the counties. When you click on a county, the map zooms to that county displaying the villages within.

What is the best way to accomplish this using leaflet?


Your best bet is probably to convert the .shp into a .geojson and use the map.setView() method. QGIS can easily take care of the conversion. Your code might look something like this:

var map = L.map('map');

var counties = L.geoJson('data.geojson', {
    onEachFeature: function (feature, layer) {
        feature.on('click', function(){
            map.setView(feature.getLatLng(), <zoomLevel>);

of course, you have to set zoom levels upfront, or could define them for each feature w/i the geojson. But I can't think of a way to detect optimal zoom on the fly.

By the way, if you're looking for easy ways to load the .geojson file, check out leaflet omnivore.


map.setView(feature.getLatLng(), <zoomLevel>);

would work for points, but not polygons (I think). To zoom to the center of a polygon, try:

map.setView(feature.getBounds().getCenter(), <zoomLevel>) 


just noticed leaflets' map.fitBounds() method. so actually you don't have to specify the optimal zoom level upfront, but can do something like this:

|improve this answer|||||
  • Thanks @James. I want to overlay the county layer on top of the villages layer can I use what you suggested to click on a county and zoom into villages in that county or do I need to merge the 2 layers? – ChrisJ Aug 27 '14 at 16:53
  • You could, by having each county reference one of its containing villages. But presumably each county contains multiple villages, and the map.setView() method is only going to zoom to one point. You zoom to the center of the county, or you could zoom to one of the villages in the county, but you can't have it zoom to every village (or you could, one location after another, but it probably wouldn't be great map interaction). – James Conkling Aug 27 '14 at 21:33
  • You might need some logic to turn on the villages when you zoom in, that is if you want them off when zoomed out. You could use this, with smallish datasets, to only show points within your counties. github.com/mapbox/leaflet-pip – Alex Leith Sep 2 '14 at 2:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.