如果您之前沒有在標記上設置zIndex,或者首先初始化它或使用setOption()函數,那麼'this.getZIndex()'將始終返回'undefined'。
如果有超過100個標記,您的腳本也可能無法正常工作。
我已經放在一個非常簡單的地圖下面,包含2個標記,略有重疊。它會在zIndex的設置將其帶到頂端需要最高級別的標誌物之一的懸停,然後返回它回到它以前鼠標移開時:
var map;
var markers = new Array();
var highestZIndex = 0;
function initialize() {
/* SETUP MAP */
var myLatlng = new google.maps.LatLng(52.06768, -1.33758);
var mapOptions = {
center: myLatlng,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
/* ADD 1st MARKER */
var markerOptions = {
position: new google.maps.LatLng(52.06768, -1.32058),
map: map,
zIndex:1
};
marker = createMarker(markerOptions, false);
marker.set("myZIndex", marker.getZIndex());
google.maps.event.addListener(marker, "mouseover", function() {
getHighestZIndex();
this.setOptions({zIndex:highestZIndex+1});
});
google.maps.event.addListener(marker, "mouseout", function() {
this.setOptions({zIndex:this.get("myZIndex")});
});
/* ADD 2nd MARKER */
var markerOptions = {
position: new google.maps.LatLng(52.06768, -1.33758),
map: map,
zIndex:2
};
marker = createMarker(markerOptions, false);
marker.set("myZIndex", marker.getZIndex());
google.maps.event.addListener(marker, "mouseover", function() {
getHighestZIndex();
this.setOptions({zIndex:highestZIndex+1});
});
google.maps.event.addListener(marker, "mouseout", function() {
this.setOptions({zIndex:this.get("myZIndex")});
});
}
function createMarker(markerOptions) {
var marker = new google.maps.Marker(markerOptions);
markers.push(marker);
return marker;
}
function getHighestZIndex() {
// if we haven't previously got the highest zIndex
// save it as no need to do it multiple times
if (highestZIndex==0) {
if (markers.length>0) {
for (var i=0; i<markers.length; i++) {
tempZIndex = markers[i].getZIndex();
if (tempZIndex>highestZIndex) {
highestZIndex = tempZIndex;
}
}
}
}
return highestZIndex;
}