block by mpmckenna8 af23032b41f0ea1212563b523e859228

Topojson on a leaflet map

Full Screen

Using topojson with Leaflet.js and coloring your polygons based on color.

So I saw a nice example of usng geojson right on the Leaflet.js tutorials examples but I wanted to make a little thing to show how to use topojson, even though for this dataset there aren’t too many shared topologies (borders) so it doesn’t make a ton of sense to convert stuff from geojson to topojson to serve it to be converted to geojson again on the client.

But there might be datasets where it actually helps. Especially when you have a lot of shared borders and you want to not color any neighbors the same color. Topojson clientside has a really nice function where it finds each polygon’s neighbors and then when you’re assigning them colors you can make sure the ones next to each other don’t have the same color.

The way topojson is used here is not particularly effective because there are a number of islands of polygons in close proximity to each other and the first polygon in each group will get the same color. So a few small groups of polygons close together will only make use of the first few colors in the color selection array. Maybe in my next post I’ll make it so that it will use actually make use of all the colors using a modulo thing and a counter variable in the parent scope of the style funciton.

But for now I just want to join some data to these polygons so I can make a choropleth map. Look for a block or project with that in the near future.

This example was pretty much just a hacked up version of: http://leafletjs.com/examples/choropleth/

Feel free to let me know if there’s anythong silly in the code or change it yourself and show me.

index.html

style.css