23 May 2015


One of the best way to visualize the data about a city is to render it on a map. This way allows viewers connecting their spatial experience with the data and creating stronger engagement.

Sample Code

The first step is to initialize a leaflet map object. This map object will provide a complete interactive map and some important functions that help us mapping data to the map. The setView function takes 2 arguments, the first is the postion(latitute, longitutde) and the second is zoom scale.

<div id="map"></div>
var map = L.map('map').setView([25.046374, 121.517896], 13);

Then setup tileLayer for the map. Different tileLayers vary style and detail. Here are different map providers and their demo.

            'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; ' + mapLink + ' Contributors',
            maxZoom: 18,

Create a svg layer on the map and assign it as svg. This way allows the appended svg elements moving with the map.

var svg = d3.select("#map").select('svg');

Now we can load the data and start our regular d3 visualization processes. One key step is using the latitude and longitude of the data as coordinates for rendering elements on the screen. The function we used here is map.latLngToLayerPoint(LatLngObject). LatLngObject is create by L.LatLng(latitude value, longitude value). We can assign the return value of latLngToLayerPoint to transform or x, y position. And be sure to update d3 elements’ position if map is dragged.

projectPosition(); //initialize elements position
map.on("viewreset", projectPosition); //listening to map event 

function projectPosition() {
	function(d) { 
		return "translate("+ 
			map.latLngToLayerPoint(d.LatLng).x +","+ 
			map.latLngToLayerPoint(d.LatLng).y +")";


The Taipei MRT data I used here is from longitude and latitude of Taipei MRT stations.

Source code


blog comments powered by Disqus