I am using jQuery to get JSON from the following URL:
http://api.chartbeat.com/live/geo/v3/?apikey=fakekeytoshowtheurl&host=example.com
Here is an example of the JSON I get:
"lat_lngs": [[25, -80, 9], [26, -80, 6], [27, -80, 1], [29, -98, 2], [29, -95, 7], [30, -97, 3], [33, -117, 6], [33, -112, 25], [33, -111, 33], [34, -112, 1], [34, -111, 1], [36, -109, 1], [38, -97, 2], [40, -73, 1], [42, -78, 2]]
I am trying to use jQuery and get each of the lat_lngs and run a function.
Here is the code I currently have that is not working.
function addMarker(latitude, longitude) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
map: map
});
}
$.get('http://api.chartbeat.com/live/geo/v3/?apikey=fakekeytoshowtheurl&host=example.com', function(data) {
$.each(data['lat_lngs'], function() {
var latlng = data['lat_lngs'].split(',');
addMarker(latlng[0], latlng[1]);
})
});
This is not working, I get an error saying Object [object array] has no method 'split', and no matter what I have tried, I can't get anything to work. I just want to grab the first two numbers from every lat_lngs that is listed, and run the function addMarker(lat, long).
Anyone have ideas?
Explanation:
data['lat_lngs']
is an array of arrays. When you iterate over it using$.each
, each iteration receives as itsvalue
one element of thedata['lat_lngs']
array.And each element is itself an array. (Not a string! No need to
split()
anything.)$.each
also sets thethis
value to equal the current iteration’s value. So you could do this as well: