我已经编写了在谷歌地图上显示标记的代码。该代码几乎是从 Google API 文档中逐字复制的。但标记并未显示在页面上。
这是我的代码:我做错了什么?
var map;
var central_location = new google.maps.LatLng(42.745334, 12.738430);
function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: central_location,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapCanvas, mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function() {
var infowindow = new google.maps.InfoWindow({
content: '<div>Hello</div>'
});
var marker = new google.maps.Marker({
position: central_location,
map: map,
title: 'This is the title'
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
marker.setMap(map);
});
#map {
width: 500px;
height: 380px;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript" style=""></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
我注意到有类似的问题,唯一与我的问题不同的是我在 jQuery read() 事件中创建我的标记 - 而不是 initialize() 函数。
这就是标记不显示的原因吗?
注意:我不记得在 Google API 文档中读过任何内容,其中指出应在创建 map 时创建标记,因此显然情况并非如此
最佳答案
将标记创建移至initialize
函数。
$(document).ready(function(){})
在加载 DOM 元素时起作用,这并不一定意味着 map 已加载。因此,如果您尝试在文档就绪函数中创建标记,则可能不会创建 map ,一旦 map 准备好 map
变量就有了 map 对象,因此您可以在其上创建标记,您可以在 map 加载后动态添加标记。
var map;
var central_location = new google.maps.LatLng(42.745334, 12.738430);
function initialize() {
console.log('map loaded');
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: central_location,
zoom: 14,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapCanvas, mapOptions);
makePin(42.745334, 12.738430);
}
google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function(){
console.log('document loaded');
})
function makePin(lat, long){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, long),
map: map,
title: 'This is the title'
});
var infowindow = new google.maps.InfoWindow({
content: '<div>Hello</div>'
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
#map {
width: 500px;
height: 380px;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript" style=""></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<button onclick="makePin(42.749334, 12.739430)">Add Pin</button>
<div id="map"></div>
关于javascript - Google 标记未显示在 map 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32692937/