10

When I call addDomListener or addDomListenerOnce:

const domNode = document.getElementById('...');
google.maps.event.addDomListener(domNode, "mouseover", () => { ... })

I keep getting the following console warning:

google.maps.event.addDomListener() is deprecated, use the standard addEventListener() method instead: 
https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener
The feature will continue to work and there is no plan to decommission it.

How do I migrate to addEventListener without breaking anything?

Joe - GMapsBook.com
  • 15,787
  • 4
  • 23
  • 68
  • I am not using addDomListener or addDomListenerOnce, but still getting the same Warning many times. How is that even possible? Any ideas on how to deal with this issue? – Fausto R. May 21 '22 at 18:00
  • 1
    I suppose any of the third party libs (infobubble, marker clusterer etc) might still be using them? That’d be the first thing I would check. – Joe - GMapsBook.com May 21 '22 at 19:10
  • 1
    thanks, yes markerclustererplus (now deprecated) is using addDomListener – Fausto R. May 23 '22 at 12:05

1 Answers1

16

Both addDomListener and addDomListenerOnce were deprecated on Apr 7, 2022 but they

…will continue to work and there is no plan to decommission them.

If you want to get rid of the warnings, proceed as follows:

addDomListener alternative

As advised in the official docs, you should migrate to the native DOM's addEventListener.

So instead of:

const domNode = document.querySelector('...');

google.maps.event.addDomListener(domNode, 'mouseover', (evt => {
  // handle mouseover
}));

you'd do:

domNode.addEventListener('mouseover', (evt => {
 // handle mouseover
}));

In both cases, the listener's evt argument keeps implementing the DOM Event interface -- depending on the event type.

addDomListenerOnce alternative

Similar to above but with the addition of the once option. So instead of:

google.maps.event.addDomListenerOnce(domNode, 'click', (evt) => {
  // handle clicks
});

you'd do:

domNode.addEventListener('click',
  (evt) => {
    // handle clicks only once
  },
  { once: true }
);

The return types changed

Note that google's addDomListener[Once] both return a MapsEventListener.

That's not the case for the DOM's addEventListener which returns void.

So if you were previously storing your listeners — usually to remove/detach them later on — you'll need to keep track of them in some other way… Check out How to remove an event listener in javascript? or let the browser's garbage collector detach the listeners for you.


Tip: addEventListener also supports the passive option which can greatly improve performance.

Joe - GMapsBook.com
  • 15,787
  • 4
  • 23
  • 68