Using Google Maps markers as anchors

3 months ago

Using Google Maps markers as anchors

Do you want to use a marker in Google Maps as an anchor element with a real navigation status bar?

Say we have a very normal marker placed in Amsterdam, that should navigate to the Google Maps platform with directions to Amsterdam:

Hover and check the bottom left corner of your browser. Source code

createMarker() { this.marker = new google.maps.Marker({ map:, title: "Click for directions to Amsterdam.", position: { lat: 52.36994132457453, lng: 4.8998902330155545 } }); };

Traditionally, we could just add a click event listener as such:

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

And this works great, if you press on the marker, you get navigated to the official Google Maps platform with directions to Amsterdam.

But this doesn't tell the user that, the user would most commonly assume that the directions would appear in the map they're clicking inside of.

So to battle this, we can use an actual anchor element, which presents a navigation status bar in the browser. To do this, we must start with turning the map element into an anchor element!

When we turn our map element into an anchor element, we're also turning it into an inline element, which is why we have to override the display property to be a block element!

What's important is that we do not assign it a hyperlink attribute, this will keep it from being an actual hyperlink at all times and we can still safely interact with the map.

Now that the map is an anchor element, we have to add a mouse over event to our marker which sets the hyperlink attribute to our link, and a mouse out event that deletes the attribute, as such:

addMarkerEvents() { this.marker.addListener("mouseover", () => { this.element.setAttribute("href", ""); }); this.marker.addListener("mouseout", () => { this.element.removeAttribute("href"); }); };

With that done, you should now get an actual navigation status when hovering over the marker!

You can find the full source code on Github!