我在删除Google地图上的标记时遇到问题。每次用户创建航点时都会创建这些标记。它们与航点具有相同的位置。这些标记还有一个InfoBox,其中包含一个按钮,用于删除正确的航点和标记。
每次创建航点时,我都会将标记推送到一个阵列,将信息框推送到另一个阵列。
如果我只有一个航点,这是有效的。标记和航点被删除。但是,一旦我有2个或更多,它就不再起作用了。一旦我尝试删除标记停留在地图上的其中一个航路点,即使我调用.setMap(null)和/或.setPosition(null)。每次我删除一个标记我也会从它们相应的数组中删除它的航点和信息框。奇怪的是,当我调用一个重绘路径的函数时,航路点不再存在(按计划),但标记仍然存在。
以下是代码:
var markers = {
waypoints:{
p:[],
i:[],
m:[]
}
};
var saveWaypoints = function(){
removeWaypoints();
var points = directionsRenderer.getDirections().routes[0].legs[0].via_waypoints;
for(var i=0;i<points.length;i++){
var marker = new google.maps.Marker({
map:map,
position:points[i],
icon: 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png',
id: i
});
var infobox = new InfoBox({
id: i,
position: points[i],
disableAutoPan: true,
boxStyle: {
background: "white",
opacity: 1,
width: "289px",
border: 0,
padding: 0
},
zIndex: 1E4,
isHidden: false,
pane: "floatPane",
enableEventPropagation: false,
content: 'Pozicija: ' + points[i]
});
infobox.open(map,marker);
infobox.hide();
google.maps.event.addListener(infobox,'closeclick',function(){
markers.waypoints.m[this.id_].setMap(null);
markers.waypoints.m[this.id_].setPosition(null);
markers.waypoints.m.splice(this.id_,1);
markers.waypoints.p.splice(this.id_,1);
markers.waypoints.i.splice(this.id_,1);
drawPath();
});
google.maps.event.addListener(marker,'mouseover',function(){
markers.waypoints.i[this.id].show();
});
google.maps.event.addListener(marker,'mouseout',function(){
if(markers.waypoints.i[this.id] !== undefined){
if(!markers.waypoints.i[this.id].keepOpen()){
markers.waypoints.i[this.id].hide();
}
}
});
google.maps.event.addListener(marker,'click',function(){
if(waypointDialog !== null){
waypointDialog.doNotClose(false);
waypointDialog.hide();
}
console.log(this.id);
waypointDialog = markers.waypoints.i[this.id];
waypointDialog.doNotClose(true);
});
markers.waypoints.m.push(marker);
markers.waypoints.i.push(infobox);
markers.waypoints.p.push({
location: points[i],
stopover: false
});
};
};
var removeWaypoints = function(){
if(markers.waypoints !== (null||undefined)){
markers.waypoints.p = [];
markers.waypoints.m = [];
markers.waypoints.i = [];
}
};
答案 0 :(得分:0)
我认为它是因为每次循环时,它都会创建一个标记,这就是为什么你无法访问前一个标记的原因,在你的代码中,我认为只有最后创建的标记可以访问,才能访问你应该放置的所有标记声明后在数组内部。试试这段代码
var markers=[]; //initialize it on global
//and on creating marker, inside for loop add this code.
markers.push(marker);
//and to clear the markers in map try the code below
for(var i=0; i< markers.length; i++)
{
markers[i].setMap(null);
}