0

I'm trying to build a heatmap using leaflet.js and leaflet.heat from data I have in JSON format. So far, I've been able to fetch and parse my JSON file using jQuery's getJSON, but I'm stuck at the part where I loop through the file and return the arrays leaflet.heat needs to build the heatmap layer on top of leaflet.

According to leaflet.heat's documentation, all I need to pass to the library is an array constructed like so:

[latitude, longitude, intensity]

My JSON looks like this:

[{"Lat":"39.51","Long":"-76.164","Intensity":"0.0017980221756068300"},
{"Lat":"39.463","Long":"-76.12","Intensity":"0.0332634102487264000"}, 
...more data...]

Here is my code:

$.getJSON( 'data.json',
    function(data){
        var heat = L.heatLayer(data, {radius: 25}).addTo(map);
    });
});

When I run this, I get the following error:

TypeError: null is not an object (evaluating 't.lat')

I assume this is resulting from passing a JSON object when the library requires an array without keys. I've looked at this similar SO question, but when I log the output to the console with this code,

var arr = $.map(data, function(el) { return el });
console.log(arr);

...it's still output as an object with keys. Not sure what I'm doing wrong.

2 Answers2

1

I think should do the trick:

var arr = data.map(function(el) {
  return [+el.Lat, +el.Long, +el.Intensity];
});

map gives you each element of the array one at a time and lets you transform it.

Each element looks like {"Lat":"39.51","Long":"-76.164","Intensity":"0.0017980221756068300"}, and you want to transform it to something like [39.51, -76.164, 0.0017980221756068300]. You can use .Lat, .Long, and .Intensity to get each of those values, and the preceding + converts the values from strings to numbers.

user94559
  • 59,196
  • 6
  • 103
  • 103
  • probably need to coerce to numbers from strings also – charlietfl Aug 08 '17 at 14:05
  • 1
    Be aware that `$.map()` will place all the values in a single array with this code: https://jsfiddle.net/h1pf4dwf/. If you want a 2d array, you need to double wrap the output, eg. `[[+el.Lat... ]]`: https://jsfiddle.net/h1pf4dwf/1/. Alternatively you could use the native `map()` function and avoid the problem completely: https://jsfiddle.net/h1pf4dwf/2/ – Rory McCrossan Aug 08 '17 at 14:16
  • Wow, what's wrong with `$.map`? I'm at a loss as to how that behavior would help. – user94559 Aug 08 '17 at 14:47
  • @Jonasw I don't see how `Object.values` would help, since we need to emit the values in the right order. – user94559 Aug 08 '17 at 14:47
  • Edited to use the native `map`. – user94559 Aug 08 '17 at 14:48
  • @smarx good point. Would probably work, but i admit that its buggy. – Jonas Wilms Aug 08 '17 at 14:48
-1

You actually don't need to parse it manually. Modern browsers supports JSON deserialization:

var json_string = file.read("filename");
var json_to_array = JSON.parse( json_string );
Jay Nguyen
  • 342
  • 1
  • 2
  • 18