'How to address addDomListener() deprecation in google maps

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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1