AngularUI: Handling Mouseover Events for Google Maps Markers
The Problem:
It took me a while to figure this out, so I thought the issue deserved its own blog post. I found myself confused when trying to hook up mouseover events with Google Map markers using AngularUI. The documentation was vague on this matter, stating that it is only supported for a single marker and not for multiple markers.
For a single marker, it’s straightforward to specify a directive with an events
property in the HTML:
<ui-gmap-marker events="marker.events"></ui-gmap-marker>
Then in the controller:
$scope.marker = {
events: {
mouseover: function (marker, eventName, args) {
// Callback code here
},
},
}
However, the same approach doesn’t work for multiple markers. I initially thought I could simply add mouseover events to each marker like so:
markers.push({
events: {
mouseover: function (mapModel, eventName, originalEventArgs) {
console.log("I'd really like to show the info window on mouseover.")
},
},
})
My Solution:
To resolve this, add the following to the HTML markers
directive:
events="clickEventsObject"
And in the controller:
$scope.clickEventsObject = {
mouseover: markerMouseOver,
mouseout: markerMouseOut,
}
function markerMouseOver(marker, e) {
// Callback code here
}
function markerMouseOut(marker, e) {
// Callback code here
}
It works! This handler returns a directly-mapped array of the models that belong to the gMarker cluster sent along with the event. If you have any questions, feel free to ask. 😊