Leaflet Zip Code Map Part 2

Leaflet Zip Code Map Part 1

In this part of the tutorial we’ll be focusing on what you need to do to get a front end set up to serve up the map and consume the wonderful zip code data.

In case you missed it, here’s what we’re going for:

leaflet js zipcode map


The html required on the page is almost as basic as it gets since most stuff is loaded in dynamically.

The main pieces are:

The map div <div class="control" id="map-loader"></div>

The Coloring function dropdown if needed

And your script includes of course:

I’m using Numeral.js for number formatting on the popup, d3 for the handy quantize function that assigns data to color buckets, and Underscore.js for filtering/mapping/aggregating the data received.


Most of the CSS is just for the age histogram in the rollover popup.


Saving the best and most for last, here’s the javascript. Thanks to stamen.com for a black and white tile set, it’s much nicer than struggling to tell what colors mean what when you overlay colored data on top.

The basic flow is:

  • Initialize the map with a center point retrieved from another API endpoint
  • Fetch the zipcode data for the current viewport
  • Calculate some statistics about the demographic data received that will be used to determine the color for each zip code.
  • Set up all the bindings for zoom/scroll/hover events and handle appropriately.

Closing thoughts

At some point I would like to group the zip codes together by fewer and fewer digits and show bigger and bigger areas as you zoom out. This would allow the map to show the whole country instead of having to cap the max zoom because there’s so much data to show. This should be possible starting back with the original shape data file by finding the distinct lat/long points in each zip code group. This would probably take awhile to compute but once you got it into the database all the steps down the line would be much faster showing less boundary data.

Thanks for reading! Hopefully this has saved you a bunch of time making an awesome looking map and please leave a comment if it has.

Liked this post?

Sign up and be the first to see new posts!

No spam, no nonsense, no guarantees, no rights reserved, probably.


comments powered by Disqus