map
Using OpenStreetMaps with d3.js

Oct 2014

This post focuses on Open street maps and d3.js and how to combine these 2 bits of technology to create some pro looking maps with a high degree of configurability.


Inspired by Mike Bostock's Vector Tiles example we're going to use OpenStreetMap data to plot the glorious island of Jersey. Starting with his original code, changing the translate property on the zoom object, to use jersey coordinates, centres the map over Jersey:

.translate(projection([-2.1043, 49.1836])

chart

As you can see though, only roads are drawn so it makes the island look a bit weird as there is no land/sea border. There are 6 types of vector tiles available from OpenStreetMap:

  • vectiles-highroad - roads (and paths, railways etc.)
  • vectiles-skeletron - road names
  • vectiles-buildings - polygons representing buildings
  • vectiles-pois - points of interest
  • vectiles-land-usages - polygons representing usages such as parks, schools, cemetries, golf course etc. etc.
  • vectiles-water-areas

Changing the url to request vectiles-water-areas, rather than vectiles-highroad produces a map with the distinctive outline around Jersey.

chart

We can tidy it up considerably with a few CSS rules. The first rules set the ocean colour to a light grey and other selected water features to a light blue.

	
.tile .ocean {
	fill: #ededed;
}
.tile .lake,
.tile .reservoir,
.tile .riverbank,
.tile .water,
.tile .basin,
.tile .dam {
	fill: #deebf7;
}

And modifying the existing path rule to nullify the stroke means that we won't get lines drawn along the edges of the tiles, or around the features.

 .tile path {
	fill: none;
	stroke: none;
	stroke-linejoin: round;
	stroke-linecap: round;
}
chart

We're at the point where we can draw the roads or the water, but we want both! Fortunately this is simple to do and just requires us to add a second SVG layer and load it up with the OpenStreetMap data that we require. While we're at it, let's add a third layer for buildings. With all these extra layers we need to be a bit more specific with the CSS classes that we assign to the layers, and give them all different names, otherwise we'll encounter funny behaviour. For the finished working example check out my block.

chart
Please enable JavaScript to view the comments powered by Disqus.