[英]How to make dynamic markers in google maps with jSON?
我正在嘗試創建動態標記以從json文件加載信息。 由於某種原因,json數據永遠不會加載。 當我嘗試加載一個標記時,沒有json數據就可以正常工作。 我看不出錯誤是什么。 在控制台中,它說“ TypeError :(中間值)。錯誤不是函數”。 這是下面的代碼。
html腳本鏈接
<script src="https://maps.googleapis.com/maps/api/js?CLIENT ID HERE
&v=3.21&callback=initMap"
async defer></script>
外部JS
var map;
function initMap() {
var myLatlng = {
lat: -25.363,
lng: 131.044
};
var centerZone = {
lat: 0,
lng: 0
};
map = new google.maps.Map(document.getElementById('map'), {
center: centerZone,
zoom: 3,
minZoom: 3
});
$.getJSON('data/data.json', function(data) {
$.each(data.markers, function(i, value) {
var myLatlng = new google.maps.LatLng(value.lat, value.lon);
alert(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: value.lon
});
});
}.error(function(words) {
alert(words);
}));
var secretMessages = ['This', 'is', 'the', 'secret', 'message'];
/*marker.addListener('click', function() {
map.setZoom(6);
map.setCenter(marker.getPosition());
attachSecretMessage(marker, secretMessages[0]);
});*/
function attachSecretMessage(marker, secretMessage) {
var infowindow = new google.maps.InfoWindow({
content: secretMessage
});
marker.addListener('click', function() {
infowindow.open(marker.get('map'), marker);
});
}
// google.maps.event.addDomListener(window, 'load', initMap);
}
json資料
{
"markers": [
{
"id": "1",
"name": "Mesoamerica",
"lat": "-25.363",
"lon": "131.044",
"zoomLevel": "6"
}
]
}
json數據內部將有更多對象,這只是我想要的一個示例。
您需要等到JSON數據加載后才能對其進行任何處理。 我建議將所有依賴JSON文件的內容放在$ .done()函數中,如下所示:
$.getJSON('data/data.json').done(function(data){
//everything else
});
在等待$ .getJSON函數返回數據時,瀏覽器將繼續執行其他代碼行。 這就是為什么您會收到“不是函數”錯誤的原因; 您正在嘗試在不存在的對象上調用函數,而JS不知道如何處理它。 如果將所有內容都放在$ .done()中,則在成功檢索JSON數據之前,這些行將不會執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.