Incorporating click functionality into the infoWindow for Google Maps in Vue

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?

Answer №1

Here are three suggestions for you:

  1. Take a look at the Google API Docs to see if there is a Callback you can pass, or if clicking on content triggers any listeners.
  2. If you just want to make it work, you can add an event listener to the document and check if the click event target matches your element with the specified id. You can do something like this:
 document.addEventListener("click", (event) => {
  if (event.target.id && event.target.id === standplaats.slug) {
    console.log('I\'ve been clicked');
  }
});
  1. You could also try putting a Vue Component as content and adding a @click directive there. I'm not entirely certain if this approach will work, but it's worth considering!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The information seems to not be getting transferred to the req.body variables from the HTML form

Within my server-side settings using knex and express, I have defined the following function: // POST: Create new users app.post('/add-user', (req, res) => { const {firstName, lastName, emailAdd, gender, dob, password} = req.body; cons ...

Replacing data in a Node server

I am currently working on a server that temporarily stores files in its memory before uploading them to the database. Below is the code snippet I'm using: uploadImage(file, uid, res) { var fs = require('fs'); mongoose.connect(config ...

Submitting several individual files through distinct Dropzones within a single form

I have implemented a form that allows users to add multiple rows, each containing name and avatar fields. My goal is to utilize Dropzone.js in order to create individual droppable areas for each avatar field. Every time a new row is added, a new Dropzone ...

When dealing with ReactJS, utilize the onChange event for handling updates to nested

I am currently learning ReactJS and struggling with a simple logic problem (I'm not very good at JS). I have a form that includes fields for name, email, and message. @ContactUsNew = React.createClass getInitialState: -> message: @props.mess ...

Ways to display a collection of random images with a click of a button?

I've created a simple php webpage that is supposed to display random images from my images folder when a button is clicked. However, I'm facing an issue where no images are showing up and I can't seem to pinpoint the problem in my code. ...

Validation of HTML forms through JavaScript

I'm working on form validation and struggling with implementing preg_match check from a variable. Currently, I can validate empty fields successfully, but that's not sufficient. Any suggestions on how to proceed? var pattern = /([a-zA-Z0-9]|[a-z ...

Execution of the PHP code within the div element with the id 'upload' is not working properly when trying to use xhr.open("POST", $id("upload").action, true)

Within my .js file, I came across the following line: xhr.open("POST", $id("upload").action, true); xhr.setRequestHeader("X_FILENAME", file.name); xhr.send(file); In the index.php file, there is a form structured like this: <form id="upload" action=" ...

Incorporate a SharpSpring form within a custom React component

Trying to integrate a Sharpspring form script into my React component (page.jsx). The form needs to be placed outside the <head></head> element and inside the <div> where I want to display it. The original HTML code for embedding the for ...

jQuery uploads elements only when the page is initially loaded for the first time

The issue seems to be related to the $(document).ready(function() {}); code block or potential misuse of callbacks. My goal is to execute getTotalMarketCap(), getAllOtherValues(), and getMarketShare() in sequence for an accurate market share calculation. ...

Troubleshooting Angular 5: Interceptor Fails to Intercept Requests

I have a valid JWT token stored in local storage and an interceptor that I borrowed from a tutorial. However, the interceptor is not intercepting requests and adding headers as expected. Here's where I am making a request: https://github.com/Marred/ ...

Different divs exhibit similar id and class while each being distinct from one another

Whenever I click on a number in this link, it is supposed to show its own id or class, but it always shows the same one. When I check childrenImg in the console, all the ids and classes are different. Additionally, I am trying to replace the image with ano ...

Why does NPM keep flagging dependencies as unmet even though they are clearly installed and met?

Currently, I am in the process of setting up angular2 with typescript and node. However, I keep receiving warnings about unmet peer dependencies even though they seem to be available: tyler@tyler-Blade-Stealth:~/projects/mockups$ npm install -g @angular/c ...

Why am I unable to retrieve data using jQuery and PHP?

I'm working with a PHP form that involves checkboxes: <form action="" method="post" id="CheckBoxForm"> foreach ( $results as $result ) : <input type="checkbox" class="chk" id="check_list[]" value="'.($result->meta_value).&a ...

JavaScript is incapable of locating image files

I am encountering Resource Not Found errors for the image files I am attempting to load into var manifest. Despite following the tutorial code closely, I can't seem to identify what is causing this issue... (function () { "use strict"; WinJS.Bin ...

Is there a way to conceal the toggle division following a postback in ASP.NET?

Here is the script code I am working with: <script type="text/javascript> $(document).ready(function () { var $content = $(".contentPersonalDetail").hide(); $(".togglePersonalDetail").on("click", function (e) { $(this ...

Sending a C# variable to an HTML file

I’m struggling to understand how I can use jQuery to access a variable from C# named sqlReq. My main objective is to be able to input my own SQL data into a PieChart. However, I’m unsure about how to call and define C# SQL requests in HTML or jQuery. ...

What steps can be taken to properly display dateTime values in a data table when working with JavaScript (VueJS) and PHP (Laravel)?

I am facing an issue where I am unable to save user inputted date-time values from a modal into a data table. Despite receiving a success message, the dateTime values are not being added to the table. My payload only displays the state and approval fields ...

Creating visually appealing transition effects like sliding in an autocomplete feature can enhance the user experience and

I have successfully implemented autocomplete functionality, but now I am looking to add a transition effect (slide down) to the suggested menu. After researching online, I found a helpful tutorial on this topic: Based on the information I gathered, I tri ...

What steps can I take to trigger a 404 error instead of a cast error?

My route is defined as /mysafe/idofthemodel. When the idofthemodel is not found, it throws a cast error Cast to ObjectId failed for value "something" (type string) at path "_id" for model "modelname". Instead of this error, I ...

Mastering the art of efficiently handling jQuery AJAX in WordPress plugins

Struggling to implement ajax autosave on the settings page of my plugin, I created this code: <?php function cfgeo_settings_javascript() { ?> <script type="text/javascript" > (function($){ $(document).ready(function(){ ...