Errors with Undefined Variables in Vue Google Maps

Currently, I am in the process of learning how to calculate the distance between two points using Google Maps and Vue.js. While trying to test some initial code, I keep encountering errors such as: TypeError: Cannot read property 'LatLng' of undefined

I am facing difficulty in understanding why Vue is not recognizing 'Google' or 'Geometry' for what seems like a straightforward task. I have made sure to reference 'Geometry' in Main.js, but so far no success. Although I believe that I am referencing Google correctly based on my readings, being a beginner, anything is possible.

<template>
  <div>
     <button class='btn-primary' @click='filt'>Filter</button>
  </div>
</template>


<script>
import * as VueGoogleMaps from 'vue2-google-maps';
export default {
  name: "Distance",
    data: () => {
        return {
          placeholder: "enter location",
            center: {lat: 34.503441, lng: -82.650131},
      targetLoc: { lat: 11.31, lng: 123.89 },
      
        } //ends return
    }, //end data
    methods: {
           filt () {
   
       this.center =  new VueGoogleMaps.gmapApi.maps.LatLng(-36.874694, 174.735292) 
        this.targetLoc = new VueGoogleMaps.gmapApi.maps.LatLng(-36.858317, 174.782284) 
        let distance = VueGoogleMaps.gmapApi.maps.geometry.spherical.computeDistanceBetween(this.center, this.targetLoc) 
      console.log(distance)
      
    },

    },
}
</script>

Main.js snippet:

libraries: 'places,drawing,geometry',

The snippet above leads to a console error: Error in v-on handler: "TypeError: Cannot read property 'LatLng' of undefined" I would greatly appreciate any assistance with this issue.

Answer №1

I have adjusted your configuration as follows:

<template>
  <div>
    <div><button class='btn-primary' @click='filt'>Filter</button></div>
  </div>
</template>


<script>
import * as VueGoogleMaps from 'vue2-google-maps';
export default {
  name: "Distance",
    data: () => {
        return {
          placeholder: "enter location",
          center: {lat: 34.503441, lng: -82.650131},
          targetLoc: { lat: 11.31, lng: 123.89 },
        }
    },
    computed: {
       google: VueGoogleMaps.gmapApi
    },
    methods: {
       filt () {
          this.$gmapApiPromiseLazy().then(() => {
             this.center = new this.google.maps.LatLng(-36.874694, 174.735292) 
             this.targetLoc = new this.google.gmapApi.maps.LatLng(-36.858317, 174.782284) 
             let distance = new this.google.maps.geometry.spherical.computeDistanceBetween(this.center, this.targetLoc) 
             console.log(distance)
          });
       },
    },
}
</script>

this.$gmapApiPromiseLazy().then(()
ensures that the gmap object is ready for use and
computed: { google: VueGoogleMaps.gmapApi },
improves code readability

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

Accordion Tuning - The Pro and Cons

Here is a functional accordion that I've implemented, you can view it here This is the JavaScript code I am using: $(document).ready(function ($) { $('#accordion').find('.accordion-toggle').click(function () { //Expa ...

Refresh only a portion of a page using PHP and JavaScript

I have a webpage set up with multiple sections in separate divs. Currently, the essential divs required are <div id="main">...</div> & <div id="sidebar">...</div> Each div contains PHP code like: <?php include("page.php") ...

CSS popup experiencing issues due to Iframe integration

As someone who is relatively new to web development and completely self-taught, I've encountered a challenge with an iframe on my page. I have a CSS and JavaScript popup that is triggered by jQuery. The desired behavior is that when a link is clicked, ...

If the v-model is an array, the Vuejs radio buttons will be automatically checked

Is it possible to have a checked radio button in v-for when using an array as the v-model? Here is my data structure: data() { return { persons: { name: [], surname: [], sex: [], } } } ...

Executing successive setState() calls within a React method: Achieving "synchronous" behavior

During a recent issue in my React application, I encountered a scenario where I needed to make multiple setState() calls within one method and ensure that certain code executed AFTER the states were set. The following code snippet showcases a Dialog box ut ...

Retrieving user input in a JavaScript/React app

I'm currently developing a search feature for my website using Algolia. When the user types in their search term, the results are updated to show relevant matches as they go. Here is an example below of what I am working on: https://codesandbox.io/s ...

What is the method for changing the Uint8Array object into a string?

I am encountering a similar issue as the one discussed in this post. I have read the solution provided, but I am having trouble grasping how to implement it. Are there any alternative suggestions? Here is my code snippet: var eccrypto = require("eccrypto ...

The v-img component is unable to find the resource within the assets directory

Having some trouble getting a static image to display properly using the v-img Vuetify component. The image is located at src/assets/images/logo.png. <v-img src="@/assets/images/rima_logo.png"></v-img> When attempting to load t ...

Output the information retrieved from the Axios call

How can I display data fetched from axios in a table? In my controller: public function index() { return User::latest(); } Inside user.vue: export default { data() { return { users: {}, } }, methods: { loadUsers() { a ...

Angular: Maximizing Input and Output

I'm having trouble with the function displaying within the input field. My goal is to simply allow the user to enter a name and have it displayed back to them. HTML: <div ng-app = "mainApp" ng-controller = "studentController"> <tr> < ...

Is there a problem triggering a link click with another click in jquery?

I'm currently facing a situation where I have implemented a simple tab menu from a resource found here. <ul class="tabs"> <li><a href="#tab1">tab1</a></li> <li><a id="myprofile" href="#tab2">tab2</a>< ...

Is it possible for you to enter "1.00" instead of just 1 when using the input type as number?

I am using Polymer paper-input and I would like to ensure that my input with type "number" always displays 2 decimal points, even when it is a whole number. Instead of just displaying as "1", I want it to be shown as "1.00" at all times. I have tried sett ...

Exclude specific fields when updating a document in Firebase using the update()

Currently, I am storing a class in Firebase by using the update() function. Is there a way to stop specific fields (identified by name) of the object from being saved to the Firebase database? It's similar to how we use the transient keyword in Java ...

Deprecated as it may be, I am still determined to add an array of routes to my Vue router

In my Main.js file, I am currently fetching routes from the database using an API call. However, I've run into an issue with Vue router version 4 deprecating the addRoutes functionality. Now, I can only add one route at a time which is not ideal for m ...

Tips for handling npm dependency issues

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6715020604134a1306004a0612130804080a170b021302275249524957">[email protected]</a> has requested a peer version of react@^15.0.0, but it is not currently installed on ...

The Iframe contains its own scroll feature within the body

I am facing an issue with displaying an Iframe inside a modal. The challenge is that the content within the Iframe varies in height, making it difficult to set a fixed height for the Iframe itself. When I try setting the height to 100%, the result is a 150 ...

Creating a sleek animated analog clock using CSS and jQuery

I am facing a small issue with my CSS3/jQuery analog clock. Currently, the movement of the clock hands is a bit abrupt. I would like the animation to be smooth. I attempted using transition: all .1s, but it gets messy when the clock hands reach the top po ...

Invalid character entered into HTML5 number input field

How can I validate a number field on my own when element.value returns nothing in Chrome if the content is alphabetical? Setting 'novalidate' on the form does not prevent this issue. As a result, I am unable to distinguish between an empty entry ...

What is the method to transform a string that represents an array of objects into an actual array of objects in javascript?

My data consists of an array of objects in the form of a string like this "[{'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}, {'key1': 'val1', 'key2': 'val2 ...

What is the best way to incorporate currency formatting into a table using sumtr and datatables?

I have a table where I am utilizing sumtr for the table footer, and displaying all the information within datatables. My requirement is to show all the values as currency. However, I am unable to modify the values after sumtr because it won't be able ...