我正在尝试构建一个 Web 应用程序,该应用程序从服务器中提取数据并从 JSON 响应中向谷歌地图添加多个标记。这是 JSON 响应的样子:
{"key":[{"Latitude":"60.186518","Longitude":"24.950575"}...]}
我试图实现这篇文章中的代码,但我无法让它工作。
到目前为止,这是我的代码:
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');
}