gpt4 book ai didi

javascript - Google Maps JS API + JSON - 多个标记未显示

转载 作者:行者123 更新时间:2023-11-28 06:00:31 25 4
gpt4 key购买 nike

所以,我需要的非常简单,我需要在 map 中放置标记,我从使用 PHP 构建的 JSON 中获取数据。我查了所有其他有关谷歌地图标记未显示的问题(确实),但没有一个对我有用。我在代码中找不到缺陷。

JSON 是这样的(但有 58 项长),'id' 不重要:

[
{
"id": "2",
"lat": "-49.217290",
"lon": "-16.416160",
"tit": "Heinz",
"desc": "18 Machines"
},
{
"id": "3",
"lat": "-49.235455",
"lon": "-16.676926",
"tit": "Warehouse",
"desc": "10 Machines"
}
]

我是新来的,如果我做错了什么,抱歉。我的代码如下:

    <div id="map" class="height-400"></div>
<script>
var map;
var myLatLon = {lat: -16.398293, lng: -48.965098};
var markers = [];

$.ajax({
dataType:'json',
url: "contents/map_data.php",
success: function(data){
markers = data;
}
});
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: myLatLon,
zoom: 4,
//disableDefaultUI: true,
});

var i= 0;
$.each(markers, function(i, item) {
if(typeof item == 'object') {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseFloat(item.lat),parseFloat(item.lon)),
map: map,
title: item.titulo,
label: item.desc
});
marker.setMap(map);

google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(item.desc);
infowindow.open(map, marker);
}
})(marker, i));
i=i+1;
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_SECRET_KEY&callback=initMap" async defer></script>

最佳答案

Markers 变量是一个空数组,因为 AJAX 请求尚未返回。您应该将代码移到成功回调中,或者从成功回调中调用它。

尝试这样的事情:

<div id="map" class="height-400"></div>
<script>
var map;
var myLatLon = {lat: -16.398293, lng: -48.965098};
var markers = [];

$.ajax({
dataType:'json',
url: "contents/map_data.php",
success: function(data){
markers = data;
initMap();
}
});
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: myLatLon,
zoom: 4,
//disableDefaultUI: true,
});

var i= 0;
$.each(markers, function(i, item) {
if(typeof item == 'object') {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseFloat(item.lat),parseFloat(item.lon)),
map: map,
title: item.titulo,
label: item.desc
});
marker.setMap(map);

google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(item.desc);
infowindow.open(map, marker);
}
})(marker, i));
i=i+1;
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_SECRET_KEY&callback=initMap" async defer></script>

关于javascript - Google Maps JS API + JSON - 多个标记未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37310950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com