Leaflet Day 3 - The Trail


In 1902 the only way from the port of Valdez to the Fortymile gold fields was a nearly 400 mile trail through the Alaska wilderness. The Valdez-Eagle trail plays a key role in novels two and three.

Adding the Trail to a Leaflet Map

To add the trail to our map, we will convert it from a shapefile to GeoJSON. There is more than one way to do this—you could use ogr2ogr, but we chose to use QGIS, since it would not only convert it, but transform the coordinate system at the same time.

Converting to GeoJSON

With the shapefile loaded in QGIS, we can can right-click on the layer and choose Export -> Save Features As…

Converting to GeoJSON

We chose the proper coordinate system (EPSG:4326 WGS 84) for use with Leaflet and QGIS does the conversion while saving to GeoJSON. This makes our trail ready to use in Leaflet.

Adding the File

The GeoJSON file needs to be added to our HTML file as a script, but first we need to modify it by adding a variable name:

var trail = {
"type": "FeatureCollection",
"name": "valdez_eagle_trail",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::3857" } },
"features": [

Adding var trail = to the beginning of the file will allow us to refer to it in Leaflet.

Next we add the script

Now we can add it to the map:

  var trail = L.geoJSON(trail)

This adds it to the map. You’ll notice we changed the center point and zoomed out a bit. You can still see our original earthquake marker.

Styling the Trail

We can change the look of the trail by adding options to the L.geoJSON statement:

  var thetrail = L.geoJSON(trail, {
      color: '#800000',
      weight: 3,
      dashArray: '12 8 12',

This turns the trail dark red, increases the width to 3 pixels, and creates a dashed line.

Adding a Tooltip

Adding a tooltip that is displayed when the mouse is hovered over the trail is easy:

  thetrail.bindTooltip('The Valdez-Eagle Trail')


The result of our changes looks like this:

That’s it. You can try the live map here and copy the source if you like.