Almost year ago I’ve wrote short info about how to change icons in markers placed already on map with Google Maps API. It is cumbersome method, since it requires to delete and create markers. It is problem when with markers are associated some event listeners, since they need to be recreated also.
But then was version 2.75 release of Google Maps API (I think it was around March 2007). Starting from then GMarker
got setImage
method, for changing images on already placed on map markers. But, somehow traffic to my old post is still notable, so I decided to write short example how setImage
can be used.
24 var new_icon = new GIcon() 25 26 new_icon.image = "http://nhw.pl/images/cross.png" 27 new_icon.size = new GSize(16,16) 28 new_icon.iconAnchor = new GPoint(8,9) 29 new_icon.infoWindowAnchor = new GPoint(7,7) 30 31 var opt 32 opt = {} 33 34 opt.icon = new_icon 35 opt.draggable = false 36 opt.clickable = false 37 opt.dragCrossMove = true 38 39 40 function load() { 41 if (GBrowserIsCompatible()) { 42 map = new GMap2(document.getElementById("map")); 43 map.setCenter(new GLatLng(52.2419, 21.01), 4); 44 map.addControl(new GLargeMapControl()) 45 map.addControl(new GMapTypeControl()) 46 47 GEvent.addListener(map, "click", function (marker, point) { 48 if (!marker) { 49 new_marker = new GMarker(point,opt) 50 map.addOverlay( new_marker ) 51 markers.push(new_marker) 52 } 53 } 54 ) 55 } 56 }
First in lines 24-29 I create icon object. Next in lines 31-37 I create options for icon. In this example most important is line 34 when I use icon created in lines 24-29.
In lines 40-56 is function responsible for map creation. It also register one event listener, to create new markers on map. All markers are stored in markers
array.
Now we can use this array to iterate through markers placed on map by user and change icon:
58 function changeIcons() { 59 for (i=0; i< markers.length; i++ ) { 60 markers[i].setImage("http://nhw.pl/images/cancel.png") 61 } 62 }
setImage
is method of marker object (thus is called on elements of array with markers created after click event). As argument it takes URL for new image. Notice, that icon object (and it's properties like draggable
or clickable
does not change). And that is it!
Go to http://nhw.pl/download/setimage.html to see setImage
in action (code above is taken from this page).
When setImage
does not work?
And now a little warning. setImage
is meant to change only marker image, so if You did some fancy shadow (shadow property of GIcon) setImage
does not update shadow property. setImage
does not change printed image also, so if You expect users will print maps from Your application, this method won't work properly. If one of this true for Your application - You need to stick with delete/create method.
And finally - setImage
was made available in API version 2.75, it is not available in stable version of API. As for today (2007.09.18), stable version is based on API in version 2.73.
Leave a Reply