Interactive Choropleth Map

This is a case study of creating a colorful interactive choropleth map of US States Population Density with the help of GeoJSON and some custom controls (that will hopefully convince all the remaining major news and government websites that do not use Leaflet yet to start doing so).

Data Source

We’ll be creating a visualization of population density per US state. As the amount of data (state shapes and the density value for each state) is not very big, the most convenient and simple way to store and then display it is GeoJSON.

Adding Some Color

Now we need to color the states according to their population density. Choosing nice colors for a map can be tricky, but there’s a great tool that can help with it — ColorBrewer. Using the values we got from it, we create a function that returns a color based on population density:

Next we define a styling function for our GeoJSON layer so that its fillColor depends on feature.properties.density property, also adjusting the appearance a bit and adding a nice touch with dashed stroke.

Here we get access to the layer that was hovered through e.target, set a thick grey border on the layer as our highlight effect, also bringing it to the front so that the border doesn’t clash with nearby states (but not for IE or Opera, since they have problems doing bringToFront on mouseover).

Next we’ll define what happens on mouseout:

function resetHighlight(e) {
geojson.resetStyle(e.target);
}

The handy geojson.resetStyle method will reset the layer style to its default state (defined by our style function). For this to work, make sure our GeoJSON layer is accessible through the geojson variable by defining it before our listeners and assigning the layer to it later:

var geojson;
// ... our listeners
geojson = L.geoJson(...);

As an additional touch, lets define a click listener that zooms to the state:

function zoomToFeature(e) {
map.fitBounds(e.target.getBounds());
}

Now we’ll use the onEachFeature option to add the listeners on our state layers: