What is the best way to trigger a function in Vue.js when a click event occurs on Google Maps?

In my Nuxt.js app in SPA mode, I am utilizing the Google Maps API and I'm aiming to trigger a function in Vue.js methods from the gmap click event.

When attempting this.createInfoWindow(), it became apparent that this does not refer to the VueComponent, but instead to the Window.

Within my component, I initialize Google Maps and set up the click event in the vue mounted:

async mounted() {
  // Map initialization
  const google = await gmapsInit()
  this.map = new google.maps.Map(
    document.getElementById('g-map'),
    this.mapOptions
  )
  // Add click event
  google.maps.event.addListener(this.map, 'click', e => {
    // Function call not functioning
    this.createInfoWindow(e.latLng)
  })
}

Furthermore, in the vue methods, I have defined the function:

methods: {
  async createInfoWindow(latLng) {
    const google = await gmapsInit()
    const infoWindow = new google.maps.InfoWindow({
      content: 'InfoWindow',
      position: latLng
    })
    infoWindow.open(this.map)
  }
}

Though everything appears to be in order, the function call this.createInfoWindow(e.latLng) is not working as expected. How can I successfully invoke the function createInfoWindow from the click event?

Answer №1

According to your explanation, the usage of this does not pertain to the Vue instance within the click handler. You can resolve this by implementing a closure.

// Include click event
const that = this
google.maps.event.addListener(this.map, 'click', e => {
  // Calling the function is ineffective
  that.createInfoWindow(e.latLng)
})

Answer №2

In the listener function, "this" is not directly accessed, causing a lack of awareness of the existence of "this.createInfoWindow". Utilizing a closure allows for capturing and storing "this" to be used within the scope of the child function (in this case, the listener function), which is why Steve's solution proves effective.

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

socket.io establishes several sockets for each connection

At times, when the server is experiencing some load, connecting to the page may result in multiple sockets being created. If there is significant lag, the connection may never be established while additional sockets are generated every second indefinitely. ...

SCORM: moving between SCOs by clicking a button in the presentation

Currently, I am developing a website that allows users to create presentations. One of the website's features is the ability to export presentations in SCORM format (either 1.2 or 2004). This is my first time working with SCORM and I am currently impl ...

Accessing a local JSON data file via an AJAX call

function fetchColor() { var promise = $.Deferred(); $.ajax ({ url: 'ajax/color/Red.json', dataType: 'json', type: 'get', success: function(data){ promise.resolve(data); ...

jQuery is failing to properly render dynamic content data identifiers

Need help with a dynamic HTML div <a data-id="17" onclick="getcustomer();"> <div class="note note-success"> <h4 class="block">A</h4> <p>Email : <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Exploring the possibilities of jQuery with Accordion functionality and creating dynamic multiple menus

Incorporating the Wayfinder and Accordion menus, I have set up a two-level menu structure for the left column. The structure looks like this: <ul class="accordion">: Menu 1 Sub-menu 1.1 Sub-menu 1.2 Sub-menu 1.3 Menu 2 Sub-menu 2 ...

CanvasJS showcasing a variety of pie charts

I need to generate multiple pie charts for a website, but I'm struggling with the idea of dynamically rendering them based on the required quantity. I know that I will have to create a maximum of 28 pie charts at once. My initial approach involves man ...

Tips for displaying a JSON array on a web browser using a React component

My goal is to display a list of JSON data obtained from an API on the browser. I have successfully fetched the data from the REST API in the backend and now need to render it on the browser. Here is what I have learned and attempted: import React from &ap ...

Error: The element 'scrollable' is not recognized in Angular2

I recently updated my angular2 project to the final release after previously using angular2 RC5 for development. However, I encountered an error message stating "scrollable is not a known element." If I change <scrollable><!--- angular code -- ...

Using the Angular translate filter within a ternary operator

I am currently working on translating my project into a different language. To do this, I have implemented the Angular Translate library and uploaded an external JSON file containing all the translations. Here is an example of how it looks: { "hello_wor ...

Challenges with Hangman in JavaScript

As a beginner in JavaScript, I recently developed a simple hangman-like game. However, I encountered some challenges that I need help with. One issue is related to my lettersGuessed array. Currently, the array displays every time a key is pressed and repea ...

Ways to make a function inside a Node.js script get called by JavaScript in HTML?

At the moment, I am integrating Node.JS with various systems as the backend. My goal is to trigger a function in the Node.JS script from my webpage and retrieve specific values. This illustration outlines my objective: JS --> triggers function --> ...

Changing Array Object into a different Array Object (with Angular)

I am dealing with an array Object [ { product: "Product A", inStock: 3, onHold: 1, soldOut: 2 }, { product: "Product B", inStock: 2, onHold: 0, soldOut: 1 }] I am struggling to convert it into the new array format below. Any assista ...

When using jQuery, the function $(this).serialize() will not include input fields that have

Is there a way to serialize and send an entire form using jQuery post, even if only some items have been changed? I want all form fields to be included in the serialization. Here's my HTML: <form name ="XXX" class="user_goal_form"> <input ...

Adjust the height of Revolution Slider on mobile devices using initialization

To see an example of the Revolution Slider, please check out the top hero section on this page. If you are looking for the initialization code, you can find it in this javascript file: function dz_rev_slider_5(){ if(dzQuery("#rev_slider_11_1" ...

I am struggling to showcase the values of character names stored within an array

I am currently developing a Library Express App and utilizing fake data to easily showcase the values on the screen. const PopularBooks = [ { id: 1, title: "Harry Potter", characters: [ { id: 1, name: "Har ...

Guide on Generating SAS Token for Azure Table Storage in a jQuery Application

I am currently working on a jQuery web application that requires read-only access to an Azure Table Storage, fetching one record at a time by passing in the PartitionKey and RowKey. To simplify my code, I have integrated the Azure Storage JavaScript Client ...

The invocation of `prisma.profile.findUnique()` is invalid due to inconsistent column data. An invalid character 'u' was found at index 0, resulting in a malformed ObjectID

The project I'm working on is built using Next.js with Prisma and MongoDB integration. Below is the content of my Prisma schema file: generator client { provider = "prisma-client-js" } datasource db { provider = "mongodb" url = env("DATABA ...

Please submit the form to log in with your credentials

Here is the HTML code snippet for a form where users can enter their username and password to log in: <form Name ="form1" Method ="POST" ACTION = "userlogin.php" id="form1"> <div id="main_body" class="full-width"> <label>User ...

Link Array with Google Charts

I've been struggling for a long time to connect this array to a Google chart with no success. I would really appreciate some assistance in identifying what mistake I've made. I have created a jsfiddle where the array appears to be correct, and wh ...

React failing to display basic component

As a newcomer to React, I have a question regarding rendering a basic React component. Here is my setup in index.html: <!DOCTYPE html> <html lang="en> <head> <title>React</title> </head> <body> < ...