【发布时间】:2014-05-31 22:25:02
【问题描述】:
我对这段代码感到很恼火。正如您可能猜到的那样,我对编码比较陌生。我将不胜感激您对它为什么不起作用的任何见解。
我正在尝试更改鼠标悬停/移出时的标记图标。我正在尝试在 for 循环中创建和添加侦听器。在循环中,从位置数组创建标记并将其推送到另一个数组,为 mouseover 事件添加一个侦听器以更改图标,并为 mouseout 事件添加另一个侦听器以使标记图标无效。下面的代码显示了地图,添加了标记,并且似乎在监听 mouseover 和 mouseout 事件(光标悬停在标记上时会发生变化),但图标不会在这些事件中发生变化。
function initialize(){
//Marker locations
var NYC = new google.maps.LatLng(40.721505, -74.004783);
var LA = new google.maps.LatLng(34.049519, -118.238698);
var Chicago = new google.maps.LatLng(41.877461, -87.624352);
var Seattle = new google.maps.LatLng(47.606747, -122.330349);
var Miami = new google.maps.LatLng(25.788661, -80.226617);
var Boston = new google.maps.LatLng(42.357913, -71.059217);
var Houston = new google.maps.LatLng(29.758182, -95.364213);
var KansasCity = new google.maps.LatLng(39.097781,-94.588079);
var locations = new Array(NYC, LA, Chicago, Seattle, Miami, Boston, Houston, KansasCity);
//Array to store markers
var markers = new Array ();
//Icon
var gif = 'http://demers-ambulances.com/assets/img/news/mapPinOver2.gif';
//Map options
var mapOptions = {
center: KansasCity,
zoom: 5,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.TOP_LEFT
},
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
position: google.maps.ControlPosition.TOP_RIGHT,
},
};
//Create map
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//Create markers and add listener to change marker icon on mouseover/out
for (i = 0; i<locations.length; i++){
var marker = new google.maps.Marker({
position: locations[i],
draggable: true,
map: map,
});
markers.push(marker);
google.maps.event.addListener(markers[i], 'mouseover', function() {
markers[i].setIcon(gif);
});
google.maps.event.addListener(markers[i], 'mouseout', function() {
markers[i].setIcon(null);
});
};
};
google.maps.event.addDomListener(window, 'load', initialize);
感谢您的帮助:)
【问题讨论】:
-
@AntoJurković 这个问题和这个不一样。不是重复的。
标签: javascript google-maps google-maps-api-3 mouseover mouseout