What is the best method for activating a function with @click within an infowindow on Google Maps in Vue.js?

Here's the current code snippet:

addpolygon: function(e) {
      var vm = this;
      var point = {
        lat: parseFloat(e.latLng.lat()),
        lng: parseFloat(e.latLng.lng())
      };
      vm.coord.push(point);
      vm.replot();
      vm.marker = new google.maps.Marker({
        position: point,
        map: vm.map,
        icon: "/fred.png"
      });
      vm.infowindow = new google.maps.InfoWindow({
        content:"<a class=\"btn btn-danger\" @click.native=\"removePoint("+vm.markerid+)\">Remove</a>",
        maxWidth: 300
      });
      vm.bindInfoWindow(vm.marker, vm.map, vm.infowindow);
      vm.markers[vm.markerid] = {
        marker: vm.marker,
        point: point
      };
      vm.markerid++;
    },

When I click on Remove, I want to trigger another function called removePoint.

I have defined it like this:

removePoint: function(id) {
      alert("adsf")
    },

However, I'm unable to make it work with the above code. Nothing happens when I click on the remove button. Can you help me find a solution?

Answer №1

Revamped Solution

In order to integrate a global method from InfoWindow, implement a basic click handler function.

`onclick="removePoint(${vm.markerId})"`

To access your vm within the global method, create a closure via code.


const vm = this
window.removePoint = function(id) {
    vm.removePoint(id)
}

If dealing with multiple instances, further enhancements may be required in extending this strategy.

Prior Method

There exist 2 pivotal issues at play here.

To start with, rectify the syntax error related to quotes.

vm.markerid + ")\">Remove</a>"

A more efficient alternative is leveraging template strings to evade quote complications.

vm.infowindow = new google.maps.InfoWindow({ content:`
<a class="btn btn-danger" @click.native="removePoint(${vm.markerid})">Remove</a>`, maxWidth: 300 });

Secondly, any function embedded within a vue template operates under the component's scope. Assume a this. object precedes it. Therefore, calling removePoint essentially invokes this.removePoint.

Define the function inside the instance itself.


vm.removePoint = function(id) {
   console.log(`removing point ${id}...`)
}

Alternatively, ensure that the component options explicitly define removePoint within the methods section.

You also have the option of globally defining removePoint (on the window object) and invoking

$window.removePoint(" + vm.markerId + ")"
within the template if utilizing a plugin like https://www.npmjs.com/package/window-plugin.

@click.native=\"$window.removePoint(" + vm.markerid ...


function removePoint(id) {
   console.log(`removing point ${id}...`)
}

Answer №2

StevenSpungin's solution worked perfectly. Many thanks! Just keeping it simple.

When setting up the marker content,

markerContent += `<button onclick='editVehicle(${vehicle.id});'>EDIT</button>`;

And in any component where it is created,

 created() {
    let that = this;
    window.editAppointment = function(vehicleId) {
        console.log("vehicleId", vehicleId);
    }
}

Answer №3

When setting up your mounted method, remember to map the window method to the vue method:

mounted(){
    this.initMap();
    window.linkToKey = this.linkToKey;    // Linking vue method to window method
},

Additionally, in the html for your infoWindow:

const contentString =`<img onClick="linkToKey('${video.key}')" src="images/${video.key}.png">`;
const infowindow = new google.maps.InfoWindow({
    content: contentString,
});

You can define your vue method as follows:

methods: {
    linkToKey(key) {
        console.log('key', key);            
        this.$router.push(`/video/${key}`);
    },

This way, the window method is connected to your vue method and you can expect everything to function properly when clicking on items in the InfoWindow.

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

Having trouble changing the chosen selection in the material UI dropdown menu

I've encountered an issue with my material ui code for a select dropdown. It seems that the selected option is not updating properly within the dropdown. <FormControl variant="outlined" className={classes.formControl}> <InputLabel ref={ ...

Angular2 bootstrapping of multiple components

My query pertains to the following issue raised on Stack Overflow: Error when bootstrapping multiple angular2 modules In my index.html, I have included the code snippet below: <app-header>Loading header...</app-header> <app-root>L ...

Update the Laravel public directory

I need to update the public folder to public_html, but encountering issues with commands and functions still referencing the old public directory. While using Laravel+Vue for a single page application, my usual practice of renaming the public folder to pu ...

Prevent refreshing Google Maps when changing routes in AngularJS

Utilizing a Google map as the background for my website adds a unique visual element to the data displayed on different routes. However, I have encountered an issue where the map reloads with every route change, resulting in an unsightly flash of white tha ...

Challenges surrounding jQuery's .before

Currently, I am in the process of creating a simple carousel consisting of 4 divs. The carousel is utilizing 2 jQuery functions to position a div at either the first or last slot. The transitions being used are only alpha transitions as there is no need fo ...

The process of obtaining and sending a token from an HTML page while submitting a form request to a Laravel 5 application involves a few key steps

My application consists of the client side being written in HTML and Angularjs, while the server-side is using Laravel 5. Every time I submit my form, I send the models using $http to a route in my Laravel 5 app, but I continuously encounter the error: pr ...

Exploring ways to customize the input color of Material UI TextField when it is disabled [Version: 5.0.8]

I am having trouble changing the border color and text color when an input is disabled. I have tried multiple variations, as seen below: const textFieldStyle = { '& label': { color: darkMode?'#1976d2':'', } ...

Using AngularJS to fetch images from RSS feed description

I'm currently learning AngularJS by creating a simple RSS feed. I have successfully made a JSON request and fetched all the data including title, link, description, and images from the RSS feed I parsed. The code snippet for extracting images looks li ...

Visualize data retrieved from a third-party website through scraping in a chart

After attempting to extract data from a website's data.asp file (formatted in json) and display it as a chart on my site using Google Chart API or FusionCharts, I'm facing issues. Although I can retrieve the json data, it doesn't render as a ...

Increasing the size of a div container based on the position of the cursor on the

I recently stumbled upon a fantastic website where two images slide left and right based on mouse movement. When the cursor is on the right, the right part of the image expands, and when it's on the left, the left part expands. You can check out the ...

Unable to render the JSON data that was retrieved from a jQuery AJAX request

I am having trouble displaying JSON data that is returned from an AJAX call. Can someone please assist me? I am new to this. $.ajaxSetup({ cache: false, timeout: 5000 }); //String.prototype.toJSON; var the_object = {}; function concatObject(obj) { ...

Are you searching for the origin of a dynamic dropdown widget or database?

Currently, I am browsing through and I have a query regarding accessing all available classes/options for the courses in a semester. There is a class locator on the top left of the page with a dynamic drop-down menu. Can anyone suggest how I can access ...

Neglect to notify about the input text's value

Having trouble retrieving the text from a simple <input id="editfileFormTitleinput" type="text>. Despite my efforts, I am unable to alert the content within the input field. This is the code snippet I've attempted: $('#editfileFormTitleinp ...

Building a TypeScript Rest API with efficient routing, controllers, and classes for seamless management

I have been working on transitioning a Node project to TypeScript using Express and CoreModel. In my original setup, the structure looked like this: to manage users accountRouter <- accountController <- User (Class) <- CoreModel (parent Class o ...

The localhost on port 3000 seems to be malfunctioning on Windows when trying to develop a ReactJS app using Create React App

For the past few days, I have been encountering a few issues that I have been trying to resolve without success. I attempted to stop localhost:3000 with netstat -ano | findstr :3000 taskkill /PID myPIDhere /F Despite my efforts, I still see- TCP 0. ...

Tips for updating a column with just one button in AngularJS

On my list page, there is an Unapproved button. I am new to angular and struggling to figure out how to retrieve the post's id and update the corresponding column in the database to mark it as approved. Can someone provide guidance on how to accomplis ...

Oh no! It seems like the build script is missing in the NPM

https://i.stack.imgur.com/el7zM.jpg npm ERR! missing script: build; I find it strange, what could be causing this issue? Any suggestions? I have included the fullstack error with the package.json. Please also review the build.sh code below. Fullstack err ...

Exploring the power of jQuery's deferred method and utilizing the ajax beforeSend

Using the deferred object in $.ajax allows for: Replacing the success-callback with the deferred-method done() Replacing the error-callback with the deferred-method fail() And replacing the complete-callback with always() When using: var jqxhr = $.ajax ...

Retrieve a specific value from a JavaScript object

Utilizing the npm package app-store-scraper, I am extracting the app IDs of 1000 apps from the App Store. My objective is to retrieve the "id" field from each JavaScript object and save it in a .csv file. How can I accomplish this task? Below is the code ...

Using a locally hosted HTML page to update a JSON file stored on my computer

In my current project, I need to reorganize data stored in an array named unknown. Each item in this array needs to be moved either to a new array called good or another one called bad. let data = { "bad":[], "unknown": ["b", "a", "d", "g", "o", ...