Pop Up An InfoWindow When Mouseover A Google Maps Marker

Ivan Luk
Ivan Luk
Feb 28 · 3 min read

In one of my last blogs I wrote about creating a polyline from multiple markers (you can read it here). In the app I display the distances from the created marker as a label. It serves the purpose but it looks a little distracting and, to be frank, a bit unrefined. This is the original look:

It will look a lot better if the distance information is only shown on demand. Well, I also want to see more of that cheeky golf cart icon. Something like this:

Then when I move my mouse pointer over to the cart, I see the yardage information like this:

I can click the “x” to close the window when done reading. Now this is less distracting, isn’t it? This is accomplished by employing infoWindow in Google Maps React and the onMouseover event on the Marker component. If you recall from the original blog, the marker is created by using the derived GPS coordinates from the click on the map. I first have to add the onMouseover event for this marker.

The only thing the associated function needs to do is turn on the infoWindow display. This is accomplished through a flag in the state.

When the function is called, all it does is set the flag to true.

Just like the marker itself, the flag needs to be reset when the user clicks on a different location on the map. I just need to set the display flag back to false in the componentDidUpdate lifecycle event. Make sure this is done because unexpected behavior on the map will surface if the reset isn’t performed.

If, however, you want the info to be displayed on a mouse click instead of a mouseover, all you need is to use the “onclick” event on the Marker. The called function will perform the same task to set the state to turn on the display. You probably want to use one or the other and not both on the Marker. I tried to have both click and mouseover on the same marker but the result was less than desirable.

Nerd For Tech

From Confusion to Clarification

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Ivan Luk

Written by

Ivan Luk

Used to manage software development in financial services. Recently acquired skills include full stack development and DNA extraction/sequencing.

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.