Creating An Interactive Map With Leaflet and OpenStreetMap

I’ve known for a while that the interactive map of the world showing some of my bloodstain pattern analysis software customers was kind of slow. I also knew that I was using a very outdated version of Google’s API for displaying the data. Yesterday I decided to take a look at it to see what I needed to do to fix it up.

Old Google Map

Old Google Map

My first stop was the Google page about moving to v3 of the API. Apparently I needed to get a new API key by signing up for something with my Google Account. Google has added usage limits and now tracks absolutely everything (yes, they probably did before, but now it’s more explicit). I also needed to consider whether or not I can use the maps on a commercial site.

I don’t like hurdles, and I like simplicity, so I decided to look around for alternatives. I remembered looking at OpenStreetMap (OSM) several years ago when I originally built my map and deciding it wasn’t quite good enough. I decided to check it out again to see how they were doing. My how things change!

OpenStreetMap

OpenStreetMap

Because I’m a good lazy developer (by that I mean I avoid writing things when they already exist, are well-coded, and maintainable), my first thought was to grab a WordPress plugin and to use it for my map. I tried out the OSM – OpenStreetMap plugin. While it sort-of worked for what I was trying to do, it was not as customizable as I’d like, it seemed too heavy for one map on one site, and it tied me to WordPress (which my other site hasn’t moved to yet).

My next thought was to look for a JavaScript library with a nice API to integrate and handle most of the heavy lifting. Poking around the OSM site, I ran across OpenLayers. It looked pretty powerful, and has a ton of stuff in its API. I downloaded it (10M?) and took a look but I really just wanted something simpler. Then I found Leaflet. Exactly what I needed. Small, simple, great documentation, and some really straightforward examples.

Leaflet

Leaflet

Even though I had to brush up on some JavaScript, jQuery, and JSON concepts—things I rarely use— I ended up researching possibilities and replacing my Google Map with an OpenStreetMap/Leaflet version in just a couple of hours. It’s now much faster and simpler to customize.

New OpenStreetMap/Leaflet Map

New OpenStreetMap/Leaflet Map

In this article, I’ll step through an example that shows how to:

  • set up a simple map using the Leaflet JavaScript library
  • load marker locations from a JSON file
  • change the marker icon
  • have the markers show some data when clicked

Continue reading