Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
29
rated 0 times [  35] [ 6]  / answers: 1 / hits: 20873  / 14 Years ago, wed, july 7, 2010, 12:00:00

I have a map and I'd like to change the marker image, when zoom is greater then 5.

I know how to detect zoom change, but I don't see how to change the image.


More From » jquery

 Answers
61

That should be quite easy. I gave a look to your code, and it looks like you are not keeping a reference to your markers. This is the first thing that you should do.



Therefore create a markers array:



var markers = [];


And within your setMarkers() function, push each new marker into this array:



markers.push(marker);


Now you will be able to iterate over your markers with a for loop: for (i = 0; i < markers.length; i++).



Ideally, we should also store the two icons of each marker in the marker object itself. JavaScript objects can be augmented with custom properties very easily. To do so, you may want to change your setMarkers() function as follows:



function setMarkers(map, map_bounds, locations, iconLevel1, iconLevel2) {
for (var i = 0; i < locations.length; i++) {
var loc = locations[i];
var myLatLng = new google.maps.LatLng(loc[1], loc[2]);

var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: iconLevel1, // iconLevel1 by default
title: loc[0],
zIndex: loc[3]
});

// Add custom properties to the marker object
marker.iconLevel1 = iconLevel1;
marker.iconLevel2 = iconLevel2;

// Add the new marker to the markers array
markers.push(marker);

map_bounds.extend(myLatLng);
}
}


Finally, it seems that you are already handling the zoom_changed event correct. First of all, I suggest checking if the zoomLevel has changed between 1 and 2, in order not to iterate through the markers array if there is no need. If there is a change, simply call the setIcon() method for each marker, and pass the custom property iconLevel1 or iconLevel2 depending on the zoomLevel:



var zoomLevel = 1;

google.maps.event.addListener(map, 'zoom_changed', function() {
var i, prevZoomLevel;

prevZoomLevel = zoomLevel;

map.getZoom() < 5 ? zoomLevel = 1 : zoomLevel = 2;

if (prevZoomLevel !== zoomLevel) {
for (i = 0; i < markers.length; i++) {
if (zoomLevel === 2) {
markers[i].setIcon(markers[i].iconLevel2);
}
else {
markers[i].setIcon(markers[i].iconLevel1);
}
}
}
});


The above should work, but you may want to refactor your for loop as follows, using the subscript notation instead of the dot notation to access the properties of the markers:



for (i = 0; i < markers.length; i++) {
markers[i].setIcon(markers[i]['iconLevel' + zoomLevel]);
}

[#96313] Sunday, July 4, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
laytonlamontm

Total Points: 745
Total Questions: 130
Total Answers: 130

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
;