Digital Geography

21. August 2014

From CSV To Heatmap With Leaflet

There are so many applications out there but they probably share one thing: export your data as a XXX-delimited table. And it’s also very easy to create a comma-separated text file out of it. You also have some lat/lon values in this table? Great! Let’s make a heatmap with leaflet.

The Data

For our heatmap we will need a comma separated table with two columns representing the latitudes and longitudes of our rows/observations/points. So let us take this nice file from the USGS as an example (I know they have GeoJSON 😉 ):

CSV from the USGS with most recent earthquake (M2.5+)

I am not an JS expert but to get this data in my webapp I use the following code in the index.html. I already add all the leaflet js files and initial coding I need as well:
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>CSV to Heatmap</title>
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
    </head>
<body>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>

<script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<script src="http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js"></script>
<div id="map" style="width: 1200px; height: 800px"></div>
<script type="text/javascript"charset="utf-8">

//let's read the csv file. if this is finished we call the function to show it on the map.

$(document).ready(function() {
  $.ajax({
    type: "GET",
    url: "2.5_month.csv",
    dataType: "text",
    success: function(data){displayData(data)}
  });
});

//now the function that is called after the file was loaded

function displayData(Text){
  alert(Text);

//here comes the leaflet standard for the basemap:

  var map = L.map('map').setView([0, 0], 2);
  var OpenStreetMap_BlackAndWhite = L.tileLayer('http://{s}.www.toolserver.org/tiles/bw-mapnik/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, example by <a href="http://www.digital-geography.com">digital-geography.com</a>'
}).addTo(map);
}
</script>
This is our CSV to heatmap! See the alert for the data.
</body>
</html>
As you see, we call a function at the end of the file loading. Of course we can also do something else in the function when the data was loaded succesfully. Especially for leaflet it is good to have a real JS Object. Instead of
alert(Text);
Let’s create this JS Object by replacing this line with:
data = $.csv.toObjects(Text);
Now look in the code inspector: We have a nice Javascript object in our DOM of the page:

Firebug insight: DOM with the data.

Visualizing the Data as Heatmap

So how to get a heatmap out of the CSV file? As you may have noticed I’ve already added a heatmap plugin for leaflet by placing this line in the body of the page:
<script src="http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js"></script>
This works directly on Javascript arrays so what we will do is to create a new array out of the JS object. As the example CSV marks the latitude and longitude as well as the magnitude as strings we also need to parse them into real values:
  data_array= [0,0,0]; //create it before filling 
  for (i = 0; i < data.length; i++) {
    data_array[i] = [parseFloat(data[i].Latitude), parseFloat(data[i].Longitude), parseFloat(data[i].Magnitude)]; // if values are marked as string in the object else:
//  data_array[i] = [data[i].lat,data[i].lon,data[i].val];
};
This new array will serve as the input for our heatmap:
  var heat = L.heatLayer(data_array,{
            radius: 15,
            blur: 20, 
            maxZoom: 6,
        }).addTo(map);
That’s it! I fxxxing love leaflet and its plugins. See the result here: BTW: Does anyone know what is goin on there in Oklahoma (USA)?
  • Ryan Cooper

    Nice lesson.

    As for Oklahoma, I’m no expert, but I’ve heard that the uptick in earthquakes may be a result of fracking in the area.

  • Christoph Gruetzner

    Great post, thanks! The Oklahoma quakes are caused by wastewater injection. All the water used for fracking is pumped back into the boreholes, which results in a change in pressure at depth and quakes. These seismic events are different from tectonic earthquakes on faults (although fault movement may be involved in the process) and also different from fracking quakes. Check this article for some news on this kind of seismicity: http://www.earthmagazine.org/article/human-induced-earthquakes-shake-less

  • Hi Christoph, Hi Ryan,

    thanks for clearing things up. I thought about some old salt mines. But wastewater and fracking explains it.

  • Alex Boschmans

    Perhaps only at this moment in time a problem, but the mapnik tiles don’t seem to be loading anymore from openstreetmap. I only get the heat map.

    • Yeah, I saw this behaviour already on the plugin qgis2leaf. But it looked to me to be a temporal issue

  • Raul Dragnel Jimenez

    Hi I have some questions about the script, how interpret the csv or what is the format that my csv should have for to be recognized by the plugin?

    • Chauhan Ritambhara

      Hi, I have the same issue. the CSV file is no more available on the link. I am trying to use my CSV file from the same folder ( at url: “my_csv_file.csv” ), but it is not recognized.

      If you have found the answer please share.