I have multiple polylines on a Google Map and add a 'click' event handler for each. All these polylines are added via javascript code. However when I click on any polyline on map, the click event for the last added polyline is fired. This makes it difficult to identify the line clicked.
The code that creates the Polylines is:
$.ajax({
type: "GET",
url: "MapData.html",
success: function (json) {
mapData = JSON.parse(json);
var newroad;
for (var i = 0; i < mapData.length; i++) {
newroad = new google.maps.Polyline({
ID: mapData[i].ID,
path: google.maps.geometry.encoding.decodePath(mapData[i].latLngs),
strokeColor: 'blue',
strokeOpacity: 0.75,
strokeWeight: 3
});
newroad.setMap(map);
google.maps.event.addListener(newroad, 'click', function () {
setSelectedRoad(newroad);
});
}
},
error: function () {
alert('Critical Data Failure');
}
});
The data is correctly fetched from the server and all polylines are displayed in blue as expected. The function that gets called when a polyline is clicked is
function setSelectedRoad(road) {
road.strokeColor = 'black';
road.setOptions({ strokeColor: 'black', strokeOpacity: 1.0 });
selectedRoadID = road.ID;
}
However the "selectedRoadID" always turns out to be the last polyline added and the color for that line changes to black, even if any other polyline is clicked.
The confusing part is that if I draw a fresh polyline on the map and set its click event to the same function, then that works properly. I do get proper ID for the polyline clicked. This works for any number of new lines drawn and works properly for clicking them in any order.
答案 0 :(得分:0)
问题是你在循环中这样做:
newroad = new google.maps.Polyline({ ... });
google.maps.event.addListener(newroad, 'click', function () {
setSelectedRoad(newroad);
});
所以你重新创建newroad
让我们说10次。每次创建它时,都会为同一个变量提供一个新的事件监听器,即您重新覆盖同一个事件监听器10次。不创建10个单独的事件侦听器,每个折线一个。
当您点击折线时,您只能执行最后一个版本的事件监听器。
相反,您需要从循环中分离出事件侦听器。像这样:
$.ajax({
type: "GET",
url: "MapData.html",
success: function (json) {
mapData = JSON.parse(json);
var newroad;
for (var i = 0; i < mapData.length; i++) {
newroad = new google.maps.Polyline({
ID: mapData[i].ID,
path: google.maps.geometry.encoding.decodePath(mapData[i].latLngs),
strokeColor: 'blue',
strokeOpacity: 0.75,
strokeWeight: 3,
map: map
});
bindEvent(newroad);
}
},
error: function () {
alert('Critical Data Failure');
}
});
function bindEvent(newroad) {
newroad.addListener('click', function () {
setSelectedRoad(this);
});
}
这样你就可以调用bindEvent
10次,每次使用newroad
的不同参数。因此,每次为newroad创建10个不同的事件侦听器。
答案 1 :(得分:0)
我发现改变了
newroad.setMap(map);
google.maps.event.addListener(newroad, 'click', function () {
setSelectedRoad(newroad);
});
到
newroad.setMap(map);
google.maps.event.addListener(newroad, 'click', function () {
setSelectedRoad(this);
});
修复了一切。