我有一个复杂的流程,我必须为 map 上的每条折线附加鼠标悬停事件。附加事件的代码很简单:
google.maps.event.addListener(polyline, "mouseover", function() {
console.log('event fired');
});
但是事件附加到少数多段线而不是其他多段线。可能是什么原因?
编辑
以下是在上述代码之前的更多代码,用于定义折线:
this.polyline = new google.maps.Polyline({
path : [fromPosition, toPosition],
strokeColor : '#CCCCCC',
strokeOpacity : 1.0,
strokeWeight : 2
});
var polyline = this.polyline;
编辑 2012 年 4 月 5 日
以下是产生问题的代码,请解释它发生的原因并推荐任何解决方案。谢谢
function Link(from, to) {
this.from = from;
this.to = to;
}
Link.prototype.show = function() {
this.line = new google.maps.Polyline({
path : [this.from, this.to],
strokeColor : "#0000FF",
strokeOpacity : 0.5,
strokeWeight : 6
});
this.line.setMap(map);
google.maps.event.addListener(this.line, 'mouseover', function() {
this.line.setOptions({
strokeOpacity : 1
});
});
google.maps.event.addListener(this.line, 'mouseout', function() {
this.line.setOptions({
strokeOpacity : 0.5
});
});
}
var links = [];
var link2 = new Link(new google.maps.LatLng(-3.5999999999999996, 23.4), new google.maps.LatLng(-4.5, 23.4)), link1 = new Link(new google.maps.LatLng(-3.5999999999999996, 23.4), new google.maps.LatLng(-3.5999999999999996, 18));
links.push(link1);
links.push(link2);
// I've a long list of links, so I'll prefer a loop
for(var i = 0; i < links.length; i++) {
links[i].show();
}
JSFiddle 演示:http://jsfiddle.net/wasimbhalli/9bg6x/
最佳答案
var map;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-3, 23),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('mapcanvas'), mapOptions);
var bounds = [];
var bounds_group_1 = [new google.maps.LatLng(-3.5999999999999996, 23.4), new google.maps.LatLng(-4.5, 23.4)],
bounds_group_2 = [new google.maps.LatLng(-3.5999999999999996, 23.4), new google.maps.LatLng(-3.5999999999999996, 18)];
bounds.push(bounds_group_1);
bounds.push(bounds_group_2);
for (var i = 0; i < bounds.length; i++) {
addPolylineSegment(bounds[i]);
}
}
function addPolylineSegment(bounds) {
// optionally you can put each polyline
// segment into an array to later use...
var polyline;
polyline = new google.maps.Polyline({
path: bounds,
strokeColor: "#0000FF",
strokeOpacity: 0.5,
strokeWeight: 6
});
polyline.setMap(map);
// attach event listener to each segment...
google.maps.event.addListener(polyline, 'mouseover', function(event) {
this.setOptions({
strokeOpacity: 1
});
});
google.maps.event.addListener(polyline, 'mouseout', function(event) {
this.setOptions({
strokeOpacity: 0.5
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
关于javascript - 为什么鼠标悬停事件不为谷歌地图中的折线分派(dispatch)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9895720/