Categories
JavaScript Answers

How to open URL by clicking on marker with Google Maps API with JavaScript?

Spread the love

Sometimes, we want to open URL by clicking on marker with Google Maps API with JavaScript.

In this article, we’ll look at how to open URL by clicking on marker with Google Maps API with JavaScript.

How to open URL by clicking on marker with Google Maps API with JavaScript?

To open URL by clicking on marker with Google Maps API with JavaScript, we add listeners to each marker.

For instance, we write

google.maps.event.addListener(
  marker,
  "click",
  ((marker, i) => {
    return () => {
      window.location.href = marker.url;
    };
  })(marker, i)
);

to call addEventListener to add a click listener to the marker.

We use the function returned by the outer function as the listener.

And we go to the url of the marker when we click on it.

Conclusion

To open URL by clicking on marker with Google Maps API with JavaScript, we add listeners to each marker.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *