What is the best way to integrate Google Maps into a Vue component?

I found a helpful reference on how to retrieve the formatted address from a dragged marker in Google Maps using JavaScript in this Stack Overflow thread.

Now, I am looking to implement this functionality in a Vue component.

I attempted to do it like this:

https://jsfiddle.net/oscar11/1krtvcfj/2/

I didn't include the code here because it is quite lengthy. You can view it directly on the jsfiddle link provided above.

When I click on the geocode button, I encounter the following error:

Uncaught ReferenceError: marker is not defined

How can I troubleshoot and resolve this error?

Answer №1

new Vue({
  el: '#app',
  template: `
        <div>
            <input id="address" type="textbox" value="London, UK">
            <input type="button" value="Geocode" @click="codeAddress()">
        </div>
    `,
  data() {
    return {
      geocoder: null,
      map: null,
      marker: null,
      infowindow: null
    }
  },
  mounted() {
    this.infowindow = new google.maps.InfoWindow({
      size: new google.maps.Size(150, 50)
    })

    google.maps.event.addDomListener(window, "load", this.initialize)
  },
  methods: {
    initialize() {
      this.geocoder = new google.maps.Geocoder();
      let latlng = new google.maps.LatLng(51.5074, 0.1278)
      let mapOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      this.map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions)
      google.maps.event.addListener(this.map, 'click', () => {
        this.infowindow.close()
      });
    },
    geocodePosition(pos) {
      this.geocoder.geocode({
        latLng: pos
      }, responses => {
        if (responses && responses.length > 0) {
          this.marker.formatted_address = responses[0].formatted_address
        } else {
          this.marker.formatted_address = 'Cannot determine address at this location.'
        }
        this.infowindow.setContent(this.marker.formatted_address + "<br>coordinates: " + this.marker.getPosition().toUrlValue(6))
        this.infowindow.open(this.map, this.marker)
      });
    },
    codeAddress() {
      let address = document.getElementById('address').value;
      this.geocoder.geocode({
        'address': address
      }, (results, status) => {
        if (status == google.maps.GeocoderStatus.OK) {
          this.map.setCenter(results[0].geometry.location);
          if (this.marker) {
            this.marker.setMap(null);
            if (this.infowindow) this.infowindow.close();
          }
          this.marker = new google.maps.Marker({
            map: this.map,
            draggable: true,
            position: results[0].geometry.location
          });
          google.maps.event.addListener(this.marker, 'dragend', () => {
            this.geocodePosition(this.marker.getPosition());
          });
          google.maps.event.addListener(this.marker, 'click', () => {
            if (this.marker.formatted_address) {
              this.infowindow.setContent(this.marker.formatted_address + "<br>coordinates: " + this.marker.getPosition().toUrlValue(6));
            } else {
              this.infowindow.setContent(address + "<br>coordinates: " + this.marker.getPosition().toUrlValue(6));
            }
            this.infowindow.open(this.map, this.marker);
          });
          google.maps.event.trigger(this.marker, 'click');
        } else {
          alert('Geocode was not successful for the following reason: ' + status);
        }
      });
    }
  }
})

Remember to store the global value in the Vue component's data property and access it using this.propertyName in your methods.

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 Vue Select component retrieves the ID value from the selected array

I have been using the Vue Select component and have been working tirelessly all day trying to extract the value id from the selected array. <v-select multiple label="name" :on-change="consoleCallback" :options="option" :value.sync="option.id" :value="i ...

Emails not being sent by Nodemailer

I recently configured my glitch project with a contact form and I'm attempting to set it up so that it sends me an email when someone fills out the form. The issue I'm experiencing is that while the server console logs indicate that the message h ...

Error: Google Plus Cross-Origin Resource Sharing Issue

I recently developed an AngularJS application that utilizes Google's server-side flow for authentication. The issue arises when my AngularJS app is hosted on one server and the Rest API is hosted on another. After successfully logging in, I encounter ...

Can PHP retrieve data when the form submit function is overridden with AJAX?

I have customized the .submit function of a form on this webpage. It is being loaded inside the #mainContent in an "index.php" and I want the Submit button to only replace this #mainContent. My goal is to retrieve data from this form and send it to a .php ...

In MUI v5 React, the scroll bar vanishes from view when the drawer is open

Currently, I am working on developing a responsive drawer in React using mui v5. In the set-up, the minimum width of the drawer is defined as 600px when it expands to full width. However, an issue arises when the screen exceeds 600px - at this point, the d ...

Javascript issue with unresponsive buttons

I've been experimenting with animations on a webpage, particularly with turning a circle into a carousel to display more information. I was inspired by CodingNepal's infinite carousel idea. Everything looks good except the buttons (i tag) are not ...

Using querySelector() to target specific divs by their classes while excluding any other classes

I am attempting to retrieve only the first divs while excluding the second ones: <div class="_5pcr userContentWrapper"> <div class="_5pcr userContentWrapper _4nef"> After researching, I discovered that the querySelector function should be abl ...

Ordering dates by week in AngularJS 1

Currently, I have a list of objects: [{ name: one, date: 2017-09-18 }, { name: two, date: 2017-09-11 }, { name: three, date: 2017-09-13 }] I am looking to organize this list by week. Perhaps like the following structure: { 1week(or , m ...

How to modify the background color in Material Ui's datepicker?

Is there a way to customize the background color of my Material UI datepicker modal? To change the colors, you can use the createMuiTheme function from "@material-ui/core": const materialTheme = createMuiTheme({ overrides: { MuiPickersToolbar: ...

What is the best way to choose a single li element?

I am working on creating a reservation system using HTML, CSS, and JS. I want to customize the color of the border for each list item (li). However, I want only one li to be selected at a time. When I click on a different li, it should remove the selection ...

collapse each <b-collapse> when a button is clicked (initially shown)

I am facing an issue with a series of connected b-buttons and b-collapse, all initially set to be visible (open). My goal is to hide them all when a toggle from my parent.vue component is activated - so upon clicking a button in the parent component, I wa ...

Verifying X-editable input in Laravel (Server-side)

I've successfully integrated x-editable into my webpage (). When I click on a field, it becomes editable inline, allowing me to make changes and submit them to a POST URI. Currently, I am sending three key-value pairs: array:3 [▼ "name" => "n ...

Unable to successfully download zip files using Ajax in the MVC framework

I need to trigger the download of a zip file that contains .pdf files using an ajax call. The issue I'm encountering is that everything seems to be working fine except for the actual downloading of the zip file. public FileResult DownloadZip(string[] ...

Loading/Adding JS script in an asynchronous manner

In my Laravel project, I am implementing templates for different pages based on a main page. Each page requires different JS scripts to function properly, so I created a template to import these scripts: <!-- jQuery 2.1.3 --> <script src="{{ URL: ...

Is it possible to Use Vuejs 2 to Update MathJax dynamically?

Just figured out how to resolve this issue. Simply bind the data using v-html <div id="app"> <h1 v-html="equation"></h1> <button @click='change'>Change</button> </div> var vm ...

What is the reason for v-model altering Vuex state rather than the local data of components?

Embarking on my very first Vue project, everything seemed to be going smoothly. However, curiosity led me to add Vuex just to explore its capabilities and ensure future scalability. Surprisingly, everything remained fine until I activated strict mode. Sudd ...

Creating an Image slideShow with only one Image - making it slide on itself

Apologies for this confusing and vague question. Imagine I only have a single image, and I want to create a slideshow using technologies like Angular, jQuery, JavaScript, or just CSS. What I am aiming for is when the user clicks on my slide button, the i ...

Bringing in States and Functions to a React Component

Is there a way to improve the organization of states and functions within a functional React Component? Here's my current code structure: import React from 'react' //more imports... const Dashboard = () => { const [] = useState() / ...

Protractor performs the afterEach function prior to the expectations being met

I am completely baffled by the behavior of this code. Everything seems to be executing correctly up until the 'expect' statement, at which point it abruptly navigates to a new page and runs the afterEach function. I've tried various solution ...

Ways to stop click propagation in the case of a parent anchor link containing a button among its children

Every time I click on the Link parent, it triggers a click event on the button as well. I want these events to be independent. <Link className="product-item__link" to={`/products/${product.category}/${product.id}`} > <div className ...