如何向地图添加新标记?我设法显示了地图function startGoogleMaps(),但我的函数(onclick())不起作用。
function startGoogleMaps(){
var map = new google.maps.Map(document.getElementById('canvasMap'), {
zoom: 5,
center: initCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
document.getElementById("testButton").onclick = function(){
var marker = new google.maps.Marker({
position: (37, -97),
map: map,
title:"Hello World!"});
}发布于 2012-10-23 05:58:38
尝试在绑定单击事件的同一作用域中定义map对象:
var map = null;
function startGoogleMaps(){
map = new google.maps.Map(document.getElementById('canvasMap'), {
zoom: 5,
center: initCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
document.getElementById("testButton").onclick = function(){
var marker = new google.maps.Marker({
position: (37, -97),
map: map,
title:"Hello World!"});
}另请注意,您需要将您的位置作为google.maps.LatLng的实例进行传递
...
position: google.maps.LatLng(37, -97),
...发布于 2012-10-23 05:58:40
请记住,Javascript使用函数作用域。您需要全局声明map,如下所示:
var map;
function startGoogleMaps(){
map = new google.maps.Map(document.getElementById('canvasMap'), {
zoom: 5,
center: initCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
document.getElementById("testButton").onclick = function(){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(37, -97),
map: map,
title:"Hello World!"});
}此外,标记本身可能不在地图的范围内,因此您可以使用map.fitBounds正确显示它:
document.getElementById("testButton").onclick = function(){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(37, -97),
map: map,
title:"Hello World!"});
var latlngbounds = new google.maps.LatLngBounds();
latlngbounds.extend(new google.maps.LatLng(37, -97));
map.fitBounds(latlngbounds);
}https://stackoverflow.com/questions/13020439
复制相似问题