我正在尝试构建一个从服务器提取数据的Web应用程序,并从JSON响应向Google地图添加多个标记。这就是JSON响应的样子:
{"key":[{"Latitude":"60.186518","Longitude":"24.950575"}...]}
我尝试从this post实施代码,但我无法让它发挥作用。
到目前为止,这是我的代码:
function success(position) {
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcontainer';
mapcanvas.style.height = '600px';
document.querySelector('article').appendChild(mapcanvas);
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var options = {
zoom: 15,
center: coords,
panControl: false,
zoomControl: false,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
overviewMapControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapcontainer"), options);
var marker = new google.maps.Marker({
position: coords,
map: map,
title:"You are here!"});
function getLocations() {
$.getJSON("http://myurl.com/jsonresponse", function (json) {
var location;
$.each(json.key, function (i, item) {
addMarker(item.Latitude,item.Longitude);
});
});
}
function addMarker(lat,lng) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map,
});
markersArray.push(marker);
}
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
error('Geo Location is not supported');
}
答案 0 :(得分:1)
请试试这个:
function getLocations() { $.ajax({ url: 'http://myurl.com/jsonresponse', async:false, success: function(data) { $.each(data.key, function(index) { addMarker(data[index].Latitude,data[index].Longitude); }); } }); }
其他明智的方法是在addMarker函数中使用console.log(lat,lng)并在此处复制输出。