0

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?

Brian Logan
  • 812
  • 2
  • 6
  • 20
  • Why would you use .split there anyway? your code isn't making a lot of sense. You're still working with `data` inside the each rather than each entry in data that you are iterating over. – Kevin B Dec 18 '13 at 19:29
  • The problem is that each of the lat_lngs is it's own entity, so for instance, I did alert lat_lngs[0] just to see what I would get, and I got the first entire set of numbers. – Brian Logan Dec 18 '13 at 19:30
  • Right. But, .split is for splitting a string into an array. `data['lat_lngs']` is already an array. – Kevin B Dec 18 '13 at 19:31
  • Ok, so, how would I grab just the first value then, I am still new to jquery, I am much more fluent with PHP :P – Brian Logan Dec 18 '13 at 19:32

1 Answers1

2
$.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]);
})
Nate
  • 18,752
  • 8
  • 48
  • 54
  • That worked! I will have to remember that next time I need to do something like this :) As soon as I can, I will mark it as the answer – Brian Logan Dec 18 '13 at 19:35