Google Maps AdvancedMarker hover listener function not working

2k Views Asked by At

I have created a function that places an array of pins on a map. I have already added a click function to all markers that re-centers the map on the new location and zooms to the appropriate. This part works without issue.

The mouseover event listener above it will not work & I can't figure out why. Is there something I'm overlooking?

function setMarker(loc,pos){
    pos = { lat: pos['lat'], lng: pos['lng'] }; 
    let marker = new AdvancedMarkerElement({
        map: map,
        position: pos,
        title: loc
    });

    google.maps.event.addListener(marker, 'mouseover', function() {
        console.log('Marker has been moused over.');
    });

    google.maps.event.addListener(marker, 'click', function() {
        map.panTo({ lat: jp[loc]['lat'], lng: jp[loc]['lng']} );
        animZoom(jp[loc]['zoom']);
        $location = loc;
    });
}
2

There are 2 best solutions below

2
henken On BEST ANSWER

I figured it out. After setting the marker, create an event listener targeting the marker.content object like so:

marker.content.addEventListener('mouseenter', function(){
    console.log('mouse enter');
});

marker.content.addEventListener('mouseleave', function(){
    console.log('mouse leave');
});

If you're wanting to add custom CSS for animation (e.g. hover effects, transitions, etc.), you can target the marker class itself without having to do it all manually via JavaScript:

.GMAMP-maps-pin-view { transition: all 0.25s linear; }
.GMAMP-maps-pin-view:hover { transform: scale(1.5); }
1
pratv On

Apparently you have to make the marker clickable by adding a Google Maps event listener like this (it can be empty):

marker.addListener("click", () => {});

This will make the marker interactable and all other mouse events will work. The answer by @henken didn't work for me until I did this.


Btw I'm using a React component as the marker, and event handlers as props work too now:

const content = document.createElement("div");
const root = createRoot(content);
root.render(<Marker />);

const marker = new google.maps.marker.AdvancedMarkerElement({
  position,
  content,
  map,
});

marker.addListener("click", () => {});
const Marker = () => {
  return (
    <div onMouseEnter={() => console.log("It works!")}>
      ...
    </div>
  )
}