Closed cspence001 closed 2 years ago
Hm, I don't see why not. Happy to take a look at your code if you want to pop it into a codepen/stackblitz
I couldn't get the code to run properly in stackblitz. I've sent a code invite for the project in glitch.
Okay, so you'd like the map to zoom into the feature when you click on it? Sure, you can do that. leaflet-choropleth extends L.GeoJSON
, so you can do anything with it that you can do with leaflet's GeoJSON
object (which itself extends FeatureGroup
etc.). For example:
choropleth.on('popupopen', function (popupEvent) {
const bounds = popupEvent.layer.getBounds()
map.fitBounds(bounds)
})
Here's a demo. Hope that helps. Will close the issue for now but feel free to re-open if I've misunderstood.
Thanks Tim, I'm sure this should work. I've implemented the event handler similarly in my code however am still getting an error that the map.fitBounds() is not a function. This more than likely has something to do with calling the handler on an overlay layer that exists within my createMap function rather than to the map itself. I will troubleshoot. Thanks for your help.
Without diving too deeply into your code, my guess is that the problem is that the variable referencing the map instance isn't accessible from wherever you're running this code, perhaps because you create the map in a function and assign it to a local variable inside that function. It's technically called not being in "scope".
An alternative might be to assign it to a variable that was declared above that function, or have the function return the map instance, so you can assign it when you call that function.
That was it. I had deeply nested variables, and multiple selector references for different choropleth type selections. I figured out a global reference:
map.on('popupopen', function (e) {
map.setView(e.target._popup._latlng); // popup location
map.fitBounds(e.target._popup._source._bounds); // selected choropleth bounds
});
Is there a way this works using fitBounds() and getBounds() onEachFeature layer? I've tried using a function similiar to this -https://leafletjs.com/examples/choropleth/example.html so that I can zoom to county or state level on 'click'. But seems to not be able to read choropleth layer properties the same as geojson.