jQuery解析数据并获取经纬度和经纬度,然后插入Google Maps`
我正在使用jQuery从以下URL获取JSON:
I am using jQuery to get JSON from the following URL:
http://api.chartbeat.com/live/geo/v3/?apikey=fakekeytoshowtheurl&host=example.com
这是我得到的JSON的示例:
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]]
我正在尝试使用jQuery并获取每个lat_lngs并运行一个函数.
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]);
})
});
这是行不通的,我收到一条错误消息,说对象[object array]没有方法'split',并且无论我尝试了什么,我都无法工作.我只想从列出的每个lat_lngs中获取前两个数字,然后运行功能addMarker(lat,long).
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).
有人有想法吗?
$.each(data['lat_lngs'], function(index, value) {
addMarker(value[0], value[1]);
})
说明:data['lat_lngs']
是一个数组数组.当您使用$.each
对其进行迭代时,每次迭代都会将data['lat_lngs']
数组的一个元素作为其value
接收.
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.
每个元素本身就是一个数组. (不是字符串!不需要split()
任何东西.)
And each element is itself an array. (Not a string! No need to split()
anything.)
$.each
还将this
的值设置为等于当前迭代的值.因此,您也可以这样做:
$.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]);
})