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

The Gatsby node encounters an error while trying to create a new page

I am currently working on creating sub-pages for a projects category in Gatsby. The parent page for each project is generating correctly, but the sub-pages are not behaving as expected. Each project has the potential to have zero or multiple sub-pages, an ...

Javascript Array Dilemmas

The current task; Determine whether the first string in the array contains all the letters of the second string. For instance, ['hello', 'Hello'] should result in true as all letters from the second string are found in the first, rega ...

A guide on extracting the text content from an anchor tag by using xPath() with a combination of selenium and Mocha

I have successfully chosen an <a> tag. My goal is to display the text of the anchor tag, but I am facing difficulties. The technologies being used are selenium, mocha, javascript, and phantomJS This is the detailed script: var assert = require(&ap ...

Can the server URL be concealed within the dist folder in Vue.js?

Currently working on a Vue.js project that will need to be distributed once development is complete. But how can I ensure its security? The js files in the "dist" folder contain the server URL, such as http://sample.org:8001/. What if a user changed all t ...

Looking to retrieve a specific data element within Vue.js?

Here's a thought-provoking query for you. Imagine I have some data stored in an element in the form of an array like this: data: { product: socks, variants: [ { variantId: 2234, variantColor: 'Green', varian ...

jQuery performs perfectly in Chrome but encounters issues in IE9/IE8 and other older versions of Internet

I've implemented this lengthy jQuery script to enable dynamic dropdown loading and updating when selections are changed. However, I'm facing issues in Internet Explorer where the script loads the dropdowns initially but doesn't trigger oncha ...

Is it just me or does Img never work, no matter what the "src" is?

I am implementing Google's React example of a "Complex Grid" (located here) to create a Card-like layout. This is how the code appears: return ( <div className={classes.root}> <Paper className={classes.paper} ...

Set options for nested arrays with up to n levels of children

My project involves building a category module using Laravel for the backend and Vue.js for the frontend. I have incorporated the library Laravel Nestable The library has been successful in producing the desired output. [ { "id": 1, "name": "C ...

Displaying iframes in AngularJS using a service

I am currently developing an Angular app and encountering some difficulties with rendering a Soundcloud embed iframe in my HTML. The issue arises when I try to display the tracks stored in the array generated by my getTracks function. Despite successfully ...

Tips for utilizing the select feature within an ng-repeat loop while maintaining the selected value when fetching data from an API

I am currently facing an issue with using select inside ng-repeat. I am attempting to correctly map the value coming from my API to the select as the selected value. However, I seem to be missing something from my end. Can someone please help me identify a ...

Learning how to implement server side rendering in React JS through tutorials

After diving into the world of React js and mastering the basics, I successfully created web pages using this technology. I also honed my skills with node js and express. However, now I am faced with a new challenge: server side rendering. The tutorials av ...

What is the most effective way to transfer information between two pages in React JS?

I am a newcomer to react and currently working on a project that involves two pages/components. I collect user details on one page and need to display that data on another page. However, I am facing difficulties in achieving this. Can someone please provid ...

Is there a way to verify that all images have been successfully loaded following an

Is it possible to determine when all images have finished loading from an appended HTML source in order to trigger another function? $(document).ready(function () { $('a.load-more').click(function (e) { e.preventDefault(); $.ajax({ ...

Chaining inheritance through Object.create

Recently, I decided to experiment with Object.create() instead of using new. How can I achieve multiple inheritance in JavaScript, for example classA -> classA's parent -> classA's parent's parent, and so on? For instance: var test = ...

Tips for retrieving the HTML file of a modified canvas in HTML5

I’m currently working on a project to develop a website that allows users to design their own pages by simply dragging and dropping elements onto the canvas. The goal is for users to be able to save their creations as an HTML file. I’m facing challen ...

Eliminating event listeners in Nuxt/Vue application

In my current project on Nuxtjs 2.13, I have a question regarding the removal of event listeners. Is it necessary and how should I go about doing it? I'm not referring to traditional JavaScript methods like addEventListener and removeEventListener. I ...

What sets apart the concept of asynchrony in C# from that in JavaScript?

When working with Python and JavaScript, a common issue arises due to blocking the event loop. This occurs when code is executed in a single thread and only one synchronous operation can be performed at a time. Interestingly, this problem does not seem t ...

The specific module 'franc' does not have the export named 'default' as requested

Every time I attempt to use the franc package, I encounter the following error message: "The requested module 'franc' does not provide an export named 'default'." Unfortunately, I am unsure of what this means, despite trying to resolve ...

React does not trigger a re-render when dynamically generated buttons are created

I am encountering an issue with displaying social media buttons on my website. I have implemented a tweet button and a Facebook like button to appear on every page, but they only load correctly on the initial page visit. Upon navigating to another page and ...

How do I integrate a button into my grey navigation bar using tailwindcss in REACT?

Is it possible to integrate the - button into the gray bar? I am encountering an issue where my blue button extends beyond the borders of the gray bar in the image provided. export default function App() { ... return ( <div className="text-md fon ...