How to add CSS-Class to a GoogleMaps marker?
The DOMNode that contains the image used for the marker isn't available via the API.
Furthermore, by default the markers will not be single DOMNodes, they will be drawn via canvas.
But the Marker-Image may be accessible via CSS when you use a unique icon-URL for each Marker.
Sample(using jQuery):
<style type="text/css">
img[src^='http://www.google.com/mapfiles/marker.png?i=']{
opacity: 0.5
}
</style>
<script type="text/javascript">
function initialize() {
var index=0;
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(52.5498783, 13.425209099999961),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
marker=new google.maps.Marker({position:map.getCenter(),
map:map,optimized:false,
icon:'http://www.google.com/mapfiles/marker.png?i='+(index++)});
google.maps.event.addListener(marker,'mouseover',function(){
$('img[src="'+this.icon+'"]').stop().animate({opacity:1});
});
google.maps.event.addListener(marker,'mouseout',function(){
$('img[src="'+this.icon+'"]').stop().animate({opacity:.5});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
How ist works:
The sample uses a single image as Marker-Icon (http://www.google.com/mapfiles/marker.png)
via CSS we apply a opacity. You may notice that there is a i-parameter inside the URL. This parameter will be used to make the img-src unique.
I use a variable which will be incremented to get a unique img-src:
var index=0;
//a few lines later:
icon:'http://www.google.com/mapfiles/marker.png?i='+(index++)
Now you'll be able to select the <img/>
-element used for the marker, e.g. onmouseover/onmouseout via a attribute-selector.
When you wan't to use vanilla javascript you may use document.querySelector
to access the image.
Note: you must set the optimized
-option of the marker to false
(this will force the API to render the marker as a single element)
Demo: http://jsfiddle.net/doktormolle/nBsh4/
There is a trick that can work if you for example want to change the cursor for the marker Add this:
google.maps.event.addListener(YOURMARKER,'mouseover',function(){$(".gm-style div").addClass("markerClass")});
google.maps.event.addListener(YOURMARKER,'mouseout',function(){$(".gm-style div").removeClass("markerClass")});
and
#YOUR-CANVAS .gm-style div {cursor: default !important;}
#YOUR-CANVAS .gm-style div.markerClass{cursor:pointer !important}
works like a charm