Json:
[{"latitude":"42.658673","longitude":"-73.810479","place":"Bethany Reformed Church"}]
Full function:
google.load("visualization", "1", {packages:["map"]});
$(function() {
// when document loads, grab the json
$.getJSON('places.json', function(data) {
// once grabbed, we run this callback
// setup the new map and its variables
var meetings = new google.visualization.DataTable();
meetings.addRows(data.length); // length gives us the number of results in our returned data
meetings.addColumn('number', 'latitude');
meetings.addColumn('number', 'longitude');
meetings.addColumn('string', 'place');
// now we need to build the map data, loop over each result
$.each(data, function(i,v) {
// set the values for both the location and place
alert(i + ":" + v.latitude + ":" + v.longitude + ":" + v.place);
// The alert displays the correct values
meetings.setValue(i, 0, v.latitude);
meetings.setValue(i, 1, v.longitude);
meetings.setValue(i, 2, v.place);
//the code stalls and nothing else gets executed
});
// finally, create the map!
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(meetings, {showTip: true, mapType: 'normal'});
});
});
If I alert() the json values inside the $.each, they are correct, but the code stalls when the json values are in meetings.setValue(). I came to this conclusion because if I put an alert after the meetings.setValues, nothing pops up.
Output of alert:
0:42.658673:-73.810479:Bethany Reformed Church
If I hard code the actual locations in meetings.setValue(), it maps the location correctly.
Like this:
$.each(data, function(i,v) {
// this maps the location correctly
meetings.setValue(i, 0, 42.658673);
meetings.setValue(i, 1, -73.810479);
meetings.setValue(i, 2, 'Bethany Reformed Church');
});
Why does the code seem to stall in the $.each when the json variables are used?
I have been using this as a guide: Using jQuery, JSON and Google’s Visualization Geo API Together
When you hardcode it you’re using numbers:
but your JSON has strings:
So either try changing the JSON to send numbers:
or convert the strings to numbers before you send them to
setValue:The unary
+will convert the string to a number. For a more explicit conversion, use theNumberconstructor (but called withoutnew).