谷歌地图JS API+JSON-多个标记没有显示
Google Maps JS API + JSON - Multiple markers not showing up
所以,我需要的很简单,我需要在地图中放置标记,我从使用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>
相关文章:
- 隐藏/显示 js 代码不会在 IE8 或更低版本上运行
- 关闭网页时没有显示 Js 的工作时间
- Firebug不再显示JS错误
- 如何在标题标签上显示 JS 变量
- 为什么突出显示.js忽略了语言类
- 在某些情况下显示 JS 警报
- 带有文本显示js功能的图像映射 - 某些部分不显示
- 防止显示.js缩放
- 突出显示 pre 标记中的语法,并突出显示.js
- 更改滚动显示.js视口
- 如何使用 bower 构建依赖关系(例如突出显示.js)
- angularjs:不能显示 JS 'typeof' 的返回值
- 提交后显示 JS/Ajax 消息
- 突出显示.js在文本区域中
- 车把内脚本中的 HTML 在使用 ember 时不显示.js + 剑道 UI
- 使用 jQuery.AJAX 在 Div 中显示 JS 图表
- 在样式模式 (jQuery UI) 窗口中显示 JS 警报
- 突出显示.js在 AngularJS SPA 中不起作用
- Gulp uglify 失败并显示 js 解析错误
- 使用Sharepoint列表值时未显示JS警报