Sarah Sarah - 1 year ago 51
Javascript Question

Loop through JSON keys to add Google Maps data

I found a lot of similar questions to this but none were useful for my particular problem. Basically, I have an AJAX call that fetches a dictionary of users along with their latitude and longitude.

$(function() {
$.getJSON($SCRIPT_ROOT + '/_userInfo',
function(data) {
var userinfo = $("#userinfo").text(data.userinfo);
});
})


This returns something like the following JSON:

{
"userinfo": {
"bob": [
40.089158,
-88.239035,
"at home",
null,
],
"sarah": [
40.486545,
-89.00478,
"at work",
null,
],
"michael": [
40.089018,
-88.239361,
"in class",
null,
]
}
}


I don't know what the key names will be, so I'm not sure how to place the markers. To simply plot the points, I just need the first value (latitude) and the second value (longitude). I tried something like this, but it doesn't work:

var data = [
for (var i = 0; i < data.userinfo.length; i++){
new google.maps.LatLng(data.userinfo[i].[0], data.userinfo[i].[1]),
}
];

map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);

heatmap = new google.maps.visualization.HeatmapLayer({
data: data,
radius: 20
});


It doesn't recognize
userinfo
as a valid variable name. I'm not familiar with the syntax of AJAX, what am I doing wrong in either my AJAX call or the for loop for my map data?

Answer Source

Aside from the syntax issue with the for inside an array definition, the issue is because userinfo is an object so you cannot loop through it as you can with an array.

Instead, you can use Object.keys to get the property names, then loop through those like this:

$(function() {
  $.getJSON($SCRIPT_ROOT + '/_userInfo', function(data) {
    var locations = [];
    Object.keys(data.userinfo).forEach(function(key) {
      var user = data.userinfo[key];
      locations.push(new google.maps.LatLng(user[0], user[1])) 
    });

    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    var heatmap = new google.maps.visualization.HeatmapLayer({
      data: locations,
      radius: 20
    });
    heatmap.setMap(map);
  });
})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download