javascript 刷新谷歌地图阻止添加标记的能力
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4268063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Refreshing Google Map is preventing ability to add markers
提问by KennC.
I have problem with after 'refreshing' my Google Map, I am not able to place in marker by myself(Clicking). But before refreshing my map(With the initialize one), I am able to place marker in by clicking. May I know what's wrong with the code?
我在“刷新”我的 Google 地图后遇到问题,我无法自己放置标记(单击)。但是在刷新我的地图(使用初始化地图)之前,我可以通过单击来放置标记。我可以知道代码有什么问题吗?
Below are my codes...
下面是我的代码...
//Initialize the map
function initialize() {
var myLatlng = new google.maps.LatLng(2,110);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
}
// Listen for click for markers
function marker()
{
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
}
// Place markers in by click
function addMarker(location) {
marker = new google.maps.Marker({
position: location,
map: map,
title:"Specified Location",
icon: 'images/greenPoint.png'
});
markersArray.push(marker);
}
function refreshMap()
{
var myLatlng = new google.maps.LatLng(1.1,107);
var myOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
回答by Eric Palakovich Carr
Why are you creating a new google.maps.Map object in the first place? You should do something like this instead:
为什么首先要创建一个新的 google.maps.Map 对象?你应该做这样的事情:
function refreshMap()
{
var myLatlng = new google.maps.LatLng(1.1,107);
var myOptions = {
zoom: 4,
center: myLatlng,
};
map.setOptions(myOptions);
}
回答by Jonathan
Using your markersArrayyou should be able to clear the map using the approach from here: Google Maps API v3: How to remove all markers?
使用您的markersArray您应该能够使用以下方法清除地图:Google Maps API v3:如何删除所有标记?
function clearOverlays() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
markersArray = [];
}
回答by Colin Sullivan
If I understand your problem correctly, you are saying that your map doesn't work after you call the refreshMapfunction. Sounds to me like a scoping issue, where the mapvariable is in a different scope the second time. Try putting this line:
如果我正确理解您的问题,那么您是说在调用该refreshMap函数后您的地图不起作用。对我来说听起来像是一个范围问题,其中map变量第二次处于不同的范围内。尝试放置这一行:
var map = null;
at the very top of the file, to be sure that all of the mapreferences are to the same global mapvariable.
在文件的最顶部,确保所有map引用都指向同一个全局map变量。

