我使用Google地图Api构建了一个网络应用,并且遇到了折线点击事件的问题。 我试图在地图上添加一些标记,然后将它们连接在一起。我希望如果我点击折线,我可以获得该折线的起点和终点的标记。但是,我单击不同的折线时,只有一个结果返回相同的结果。这是我的源代码:
var locations = [
{ title: "Site 1", lat: 16.044137, lng: 108.206511 },
{ title: "Site 2", lat: 16.067161, lng: 108.186259 },
{ title: "Site 3", lat: 16.063472, lng: 108.215248 },
{ title: "Site 4", lat: 16.041847, lng: 108.193539 },
{ title: "Site 5", lat: 16.054186, lng: 108.172890 },
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: new google.maps.LatLng(16.067161, 108.186259),
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var infowindow = new google.maps.InfoWindow();
var polyLineClicked = function (polyline, fromIndex, toIndex) {
google.maps.event.addListener(polyline, 'click', function (e) {
infowindow.setContent = fromIndex + " to " + toIndex;
infowindow.setPosition = event.latLng;
infowindow.open(map);
});
}
for (var i = 0; i < locations.length; i++) {
var position = new google.maps.LatLng(locations[i].lat, locations[i].lng);
var marker = new google.maps.Marker({
position: position,
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i].title);
infowindow.open(map, marker);
}
})(marker, i));
if (i <= locations.length - 2) {
var nextPosition = new google.maps.LatLng(locations[i + 1].lat, locations[i + 1].lng);
var polyline = new google.maps.Polyline({
path: [position, nextPosition],
strokeColor: 'black',
strokeOpacity: 1,
strokeWeight: 7,
map: map,
fromPositionIndex: i,
toPositionIndex: i+1
});
var fromIndex = locations[i].title;
var toIndex = locations[i + 1].title;
polyLineClicked(polyline, fromIndex, toIndex);
}
}
答案 0 :(得分:1)
在您的polyLineClicked函数中,您将重新分配setContent和setPosition,而不是调用infoWindow class methods。
var polyLineClicked = function(polyline, fromIndex, toIndex) {
google.maps.event.addListener(polyline, 'click', function(e) {
// call the methods instead of reassigning
infowindow.setContent(fromIndex + " to " + toIndex);
infowindow.setPosition(e.latLng);
infowindow.open(map);
});
};