Question

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?

No correct solution

OTHER TIPS

$.each(data['lat_lngs'], function(index, value) {
    addMarker(value[0], value[1]);
})

Explanation: data['lat_lngs'] is an array of arrays. When you iterate over it using $.each, each iteration receives as its value one element of the data['lat_lngs'] array.

And each element is itself an array. (Not a string! No need to split() anything.)

$.each also sets the this value to equal the current iteration’s value. So you could do this as well:

$.each(data['lat_lngs'], function() {
    addMarker(this[0], this[1]);
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top