Mark Needham

Thoughts on Software Development

Archive for the ‘leafletjs’ tag

Leaflet: Mapping Strava runs/polylines on Open Street Map

without comments

I’m a big Strava user and spent a bit of time last weekend playing around with their API to work out how to map all my runs.

2017 04 29 15 56 06

Strava API and polylines

This is a two step process:

  1. Call the /athlete/activities/ endpoint to get a list of all my activities
  2. For each of those activities call /activities/[activityId] endpoint to get more detailed information for each activity

That second API returns a ‘polyline’ property which the documentation describes as follows:

Activity and segment API requests may include summary polylines of their respective routes. The values are string encodings of the latitude and longitude points using the Google encoded polyline algorithm format.

If we navigate to that page we get the following explanation:

Polyline encoding is a lossy compression algorithm that allows you to store a series of coordinates as a single string.

I tried out a couple of my polylines using the interactive polyline encoder utility which worked well once I realised that I needed to escape backslashes (“\”) in the polyline before pasting it into the tool.

Now that I’d figured out how to map one run it was time to automate the process.

Leaflet and OpenStreetMap

I’ve previously had a good experience using Leaflet so I was keen to use that and luckily came across a Stack Overflow answer showing how to do what I wanted.

I created a HTML file and manually pasted in a couple of my runs (not forgetting to escape those backslashes!) to check that they worked:


    <title>Mapping my runs</title>
    <script src=""></script>
    <script type="text/javascript" src=""></script>
    <link rel="stylesheet" href="" />
    <div id="map" style="width: 100%; height: 100%"></div>
    var map ='map').setView([55.609818, 13.003286], 13);
        'http://{s}{z}/{x}/{y}.png', {
            maxZoom: 18,
    var encodedRoutes = [
      "{zkrIm`inANPD?BDXGPKLATHNRBRFtAR~AFjAHl@D|ALtATj@HHJBL?`@EZ?NQ\\Y^MZURGJKR]RMXYh@QdAWf@[~@aAFGb@?j@YJKBU@m@FKZ[NSPKTCRJD?`@Wf@Wb@g@HCp@Qh@]z@SRMRE^EHJZnDHbBGPHb@NfBTxBN|DVbCBdA^lBFl@Lz@HbBDl@Lr@Bb@ApCAp@Ez@g@bEMl@g@`B_AvAq@l@    QF]Rs@Nq@CmAVKCK?_@Nw@h@UJIHOZa@xA]~@UfASn@U`@_@~@[d@Sn@s@rAs@dAGN?NVhAB\\Ox@@b@S|A?Tl@jBZpAt@vBJhATfGJn@b@fARp@H^Hx@ARGNSTIFWHe@AGBOTAP@^\\zBMpACjEWlEIrCKl@i@nAk@}@}@yBOWSg@kAgBUk@Mu@[mC?QLIEUAuAS_E?uCKyCA{BH{DDgF`AaEr@uAb@oA~@{AE}AKw@    g@qAU[_@w@[gAYm@]qAEa@FOXg@JGJ@j@o@bAy@NW?Qe@oCCc@SaBEOIIEQGaAe@kC_@{De@cE?KD[H[P]NcAJ_@DGd@Gh@UHI@Ua@}Bg@yBa@uDSo@i@UIICQUkCi@sCKe@]aAa@oBG{@G[CMOIKMQe@IIM@KB]Tg@Nw@^QL]NMPMn@@\\Lb@P~@XT",
    for (let encoded of encodedRoutes) {
      var coordinates = L.Polyline.fromEncoded(encoded).getLatLngs();
              color: 'blue',
              weight: 2,
              opacity: .7,
              lineJoin: 'round'

We can spin up a Python web server over that HTML file to see how it renders:

$ python -m http.server
Serving HTTP on port 8000 ( ...

And below we can see both runs plotted on the map.

2017 04 29 15 53 28

Automating Strava API to Open Street Map

The final step is to automate the whole thing so that I can see all of my runs.

I wrote the following script to call the Strava API and save the polyline for every run to a CSV file:

import requests
import os
import sys
import csv
token = os.environ["TOKEN"]
headers = {'Authorization': "Bearer {0}".format(token)}
with open("runs.csv", "w") as runs_file:
    writer = csv.writer(runs_file, delimiter=",")
    writer.writerow(["id", "polyline"])
    page = 1
    while True:
        r = requests.get("{0}".format(page), headers = headers)
        response = r.json()
        if len(response) == 0:
            for activity in response:
                r = requests.get("{0}?include_all_efforts=true".format(activity["id"]), headers = headers)
                polyline = r.json()["map"]["polyline"]
                writer.writerow([activity["id"], polyline])
            page += 1

I then wrote a simple script using Flask to parse the CSV files and send a JSON representation of my runs to a slightly modified version of the HTML page that I described above:

from flask import Flask
from flask import render_template
import csv
import json
app = Flask(__name__)
def my_runs():
    runs = []
    with open("runs.csv", "r") as runs_file:
        reader = csv.DictReader(runs_file)
        for row in reader:
    return render_template("leaflet.html", runs = json.dumps(runs))
if __name__ == "__main__": = 5001)

I changed the following line in the HTML file:

var encodedRoutes = {{ runs|safe }};

Now we can launch our Flask web server:

$ python 
 * Running on (Press CTRL+C to quit)

And if we navigate to we can see all my runs that went near Westminster:

2017 04 29 16 32 00

The full code for all the files I’ve described in this post are available on github. If you give it a try you’ll need to provide your Strava Token in the ‘TOKEN’ environment variable before running

Hope this was helpful and if you have any questions ask me in the comments.

Written by Mark Needham

April 29th, 2017 at 3:36 pm

Posted in Javascript

Tagged with , ,

Leaflet JS: Resizing a map to keep a circle diameter inside it

with 2 comments

I’ve been working on creating a UI to make searching for the football stadiums that I wrote about last week a bit easier and I thought I’d give Leaflet JS a try.

Leaflet is a Javascript library which was recommended to me by Jason Neylon) and can be used as a wrapper around Open Street Map.

I started by creating a simple form where you could fill in a lat/long and distance and it would centre the map on that lat/long and show you a list of the stadiums within that diameter next to the map.

Having done that I wanted to draw the diameter onto the map and then show the location of the stadiums which fitted inside the circle.

I had the following code to centre the map and draw a circle:

  var distance = 10;
  var latLong=[51.505, -0.11398315429687499];
  var map ='map').setView(latLong,11);
  var layer = L.tileLayer('http://{s}{z}/{x}/{y}.png', { maxZoom: 18 });
  var currentDiameter =, distance * 1000);
  var currentPositionMarker = L.marker([latLong[0], latLong[1]]);

which creates this map:


I wanted to be able to change the diameter of the circle from the form and have it pick up more stadiums which I did with the following code:

  $("#inputDistance").change(function() {	
    currentDiameter =, $("#inputDistance").val() * 1000);

I updated the diameter to be 16km and the map looked like this:

Map diameter

It just about fits inside the map but setting it to anything higher means that the area of the diameter falls outside of the visible map which is annoying.

I wanted to be able to resize the map when the circle changed in size and after a bit of browsing of the Leaflet code I came across a function called ‘fitBounds’ which lets us achieve this. I changed the code like so:

  $("#inputDistance").change(function() {	
    currentDiameter =, $("#inputDistance").val() * 1000);

Now if I change the distance the map resizes too:

Map diameter fixed

Much better!

The full code to do this reads like so:

$(document).ready(function() {		
  var distance = 10;
  var latLong=[51.505, -0.11398315429687499];
  var map ='map').setView(latLong,11);
  var layer = L.tileLayer('http://{s}{z}/{x}/{y}.png', { maxZoom: 18 });
  var currentDiameter =, distance * 1000);
  var currentPositionMarker = L.marker([latLong[0], latLong[1]]);
  $("#inputDistance").change(function() {	
    currentDiameter =, $("#inputDistance").val() * 1000);

The code for this is all on github although I’ve refactored it a bit now so it doesn’t look exactly like this. I tried to put it on jsfiddle as well but it didn’t seem to work very well so screenshots it is!

Written by Mark Needham

June 30th, 2013 at 10:23 pm

Posted in Javascript

Tagged with ,