In my Vue project, I decided to implement the Google Maps API directly instead of using a library like vue2-google-maps. A colleague advised me against using the library due to performance issues when dealing with a large number of markers.
So, I came up with a method to render the Google Map on the page using Vue:
methods: {
async generateMap() {
const google = await gmapsInit();
this.map = new google.maps.Map(this.$el, {
zoom: 7,
center: new google.maps.LatLng(52.100886023504415, 5.6446197918489)
});
this.standplaatsen.forEach(standplaats => {
const position = {
lat: standplaats.location.latitude,
lng: standplaats.location.longitude
};
const marker = new google.maps.Marker({
position: position,
title: standplaats.name,
map: this.map,
});
marker.addListener("click", () => {
const infoWindow = new google.maps.InfoWindow({
content:
`<div>` +
`<h4>${standplaats.name}</h4>` +
`${standplaats.location.street}<br/>` +
`${standplaats.location.zipcode} ${standplaats.location.location}<br/>` +
`<hr/>` +
`<a>${standplaats.posts} opdrachten beschikbaar</a>` +
`</div>`
});
infoWindow.open(this.map, marker);
});
});
},
}
I want to trigger a Vue emit
event when the hyperlink (
<a>${standplaats.posts} opdrachten beschikbaar</a>
) is clicked within the infoWindow. Since this HTML is rendered through the Google API, I can't simply include an @click
event.
My proposed solution was to assign a unique ID to the hyperlink element and then add an eventListener immediately after it, like so:
marker.addListener("click", () => {
const infoWindow = new google.maps.InfoWindow({
content:
`<div>` +
`<h4>${standplaats.name}</h4>` +
`${standplaats.location.street}<br/>` +
`${standplaats.location.zipcode} ${standplaats.location.location}<br/>` +
`<hr/>` +
`<a id="${standplaats.slug}">${standplaats.posts} opdrachten beschikbaar</a>` +
`</div>`
});
infoWindow.open(this.map, marker);
document.getElementById(`${standplaats.slug}`).addEventListener("click", () => {
console.log('I\'ve been clicked');
});
});
This approach didn't work smoothly as there was a delay in rendering the element by the Google API. I resorted to wrapping the eventListener in a one-second timeout, but I feel that this workaround is not ideal...
Any suggestions on how to improve this setup?