So for my first real dev post I thought I’ll do a write up on a little project I did a while back. Doing stuff on a map is a big chunk of the functionality for a lot of the applications we build. Handling large numbers of markers and mutating them is mostly part of that deal as well.

For the sake of legibility I’ll split this up in three parts:

Our mapping solution of choice is usually the excellent Leaflet library which is “an open-source JavaScript library for mobile-friendly interactive maps”. Sometimes we’ll also use the Mapbox API but that’s basically an extension on the Leaflet API, so everything I discuss here should work with that as well.

There are lot of great plugins freely available on the Leaflet website, but none of them really fit our needs at the time. So what did I have to do exactly? Well … our applications use thousands of markers at a time which get updated fairly regularly. Imagine a large list of assets (like vehicles) updating and sending us their position in a near-real-time scenario and reflecting those updates on the map.

Our first pass at this worked great. We followed the leaflet guidelines, created markers, updated their positions and this was fine. But I took it upon myself to make the user’s experience of the map a little less clunky. Markers jumping around all the time isn’t my idea of a nice UX. Another point I wanted to improve upon is adding functionality to the marker itself to make it more self-contained, without having to drive it from the outside all the time and bring it more in line with the actual Map API in Leaflet itself. So my to-do list was:

  1. Make the marker move around smoothly
  2. Make the marker functionality more self-contained

First things first …

Setting up a new Leaflet plugin

Before we can do anything in the way of coding we have to set up a new plugin to extend the already existing Marker object. I created a file called ‘leaflet-animated-marker.js’ and put it inside the scripts folder of my web app next to all the other leaflet plugins we use. Here’s the basic skeleton of a Leaflet plugin:

Right now if we were to add a marker to the map and change its position a couple of seconds later the marker would jump to its new position. Have a look at this demo to see what I mean.

Adding some animation with a CSS3 transition

Making it move smoothly turns out to be very easy and straight-forward. In the AnimateMarker object we just have to override the
native _setPos function to achieve this. Our new AnimatedMarker definition now looks like this:

Of course you can achieve the same effect by just using a stylesheet, but for the purposes of this plugin I wanted it to be as self-contained as possible and this gives us the added bonus of being able to change the transition speed on the fly if necessary.

In the next post I’ll discuss making the marker easier to use with some added internal functionality.