Error thrown in JavaScript when calculating the distance

I am currently working on calculating distances between two points, but I keep getting an error that says Uncaught TypeError: a.lat is not a function.

 function MapLocations() {
        
            var i = 0;
            var infoWindow = new google.maps.InfoWindow();
            var myLatLng = {lat: 31.553761202565646, lng: 74.26506623625755}
                var m = new google.maps.Marker({
                    map: map,
                    clickable: true,
                    animation: google.maps.Animation.DROP,
                    title: 'My Home',
                    position: myLatLng,
                   // html: h[i],
                    
                });

                var circle = new google.maps.Circle({
                    map: map,
                    radius: 18.288,    // 10 miles in metres
                    fillColor: '#50D050'
                });

                circle.bindTo('center', m, 'position');
                
           var distanceInMetres = google.maps.geometry.spherical.computeDistanceBetween(myLatLng, pos).toFixed(2);
           //console.log(distanceInMetres);
                //google.maps.event.addListener(m, 'click', function () {
                //    infoWindow.setContent('Hello');
                //    infoWindow.open(map, this);
                //});
                //google.maps.event.addListener(dragable_marker, 'dragend', function (e) {
                //    alert(circle.getBounds().contains(dragable_marker.getPosition()));
                //});

               //alert(distanceInMetres);
                i++;

            
        }

The user's position (pos) is retrieved from the navigator object. Everything works fine until I remove the computeDistance function.

Answer №1

If you're using the

google.maps.geometry.spherical.computeDistanceBetween
method, note that it does not support LatLngLiteral objects currently. Instead, you need to provide google.maps.LatLng objects as parameters.

According to the most recent documentation:

computeDistanceBetween(from:LatLng, to:LatLng, radius?:number)

Return Value: number

This function calculates the distance, in meters, between two LatLng points. You can specify a custom radius if needed, with the default being the Earth's radius.

Answer №2

If you encounter a syntax error, check for any trailing commas in your JavaScript object attributes.

           var m = new google.maps.Marker({
                map: map,
                clickable: true,
                animation: google.maps.Animation.DROP,
                title: 'My Home',
                position: myLatLng,
                                 ??? this is wrong
               // html: h[i],

            });

To fix this issue, remove the comma at the end of the last attribute:

           var m = new google.maps.Marker({
                map: map,
                clickable: true,
                animation: google.maps.Animation.DROP,
                title: 'My Home',
                position: myLatLng

               // html: h[i],

            });

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

Developing a synchronous loop in Node.js using the web-kit module

My goal with my app using node.js and webkit is to scan each proxy listed in a file.txt and determine if the proxy is working. However, I am encountering an issue where my loop does not wait for the "http.get" test on line 11 to complete before moving on ...

Converting HTML widget code to NEXTjs code for integration in an application (CoinMarketCap Price Marquee Ticker)

Having trouble integrating the CoinMarketCap Price Marquee Ticker Widget into my NEXTjs app. I'm outlining my process and hoping for some suggestions from others who may have attempted this. Template Code: To embed the widget in an HTML page, here is ...

Click to switch CodeMirror's theme

http://jsbin.com/EzaKuXE/1/edit I've been attempting to switch the theme from default to cobalt and vice versa, toggling each time the button is clicked. However, I am facing an issue where it only switches to the new theme once and doesn't togg ...

Developing a Node.js and Express REST API for generating tailored routes for custom fields

I'm currently using node.js and express framework to build my REST API server. One of the features I want to implement is similar to the Facebook graph API, where I can pass specific fields in my API routes like: /me?fields=address,birthday,email,do ...

Dealing with GraphQL mutation errors without relying on the Apollo onError() function

When managing access to an API call server-side, I am throwing a 403 Forbidden error. While trying to catch the GraphQL error for a mutation, I experimented with various methods. (Method #1 successfully catches errors for useQuery()) const [m, { error }] ...

Using the Count() function in PHP to update information upon page refresh

I have created a basic cart that displays a div containing purchased items when hovered over. The issue I am facing is that every time I click on the add to cart button, it doesn't immediately update the number of items in the cart. I have to manually ...

Prop validation error: The property "title" must be a string with a value of **, but a number with a value of ** was provided

My Vue js code displays data from a JSON API in a modal. The issue is that the title should be dynamic, but it only works when clicked twice. On the first click, I get an error and the cancel button, which triggers the hidemodal() function, crashes. Can an ...

Having trouble with the Three.js OBJ loader in CodePen?

Currently, I am experiencing a challenge with loading an OBJ file on Three.js. Oddly enough, the functionality seems to be working perfectly fine when I deploy the files on my server as demonstrated here: However, when attempting to run it on Codepen, I e ...

Deleting a file and value in JavaScript

Can you help me figure out how to remove the value of q when the .close class is clicked? Here's my code: $(document).on('click', '.close', function () { $(this).parents('p').remove(); }) $('#Q1DocPath'). ...

Tips for accessing a new variable within an array of objects using JavaScript

How can I retrieve a new variable (section) after every 3 objects are called from an array in JavaScript ES6 Map? I've attempted to do this with an ES6 Map, but I'm not achieving the desired result. Can someone please assist me? Thank you! Below ...

Sleek dialog sliding animation with Svelte

I'm struggling with a svelte component that I have and I'm trying to implement a slide down animation when it closes. The slide up animation is functioning correctly, but for some reason the slide down animation is not working. Does anyone have a ...

Retrieve the innerHTML contents from all span elements

I'm having trouble getting the content of all span tags that are child elements of div#parent. So far, I've only been able to retrieve the content of the first one. Can someone please assist me with this? $( document ).ready(function() { ...

Iframe Interactivity

My goal is to create an interactive iframe that will match the current parent URL (). For example, if I have an iframe pointing to http://www.google.com and click a link within the iframe, it should update the parent URL to , and then load the clicked con ...

Execute Jquery ajax only on the initial invocation

When I am using ajax post in jQuery to build a portion of a page, I am encountering an issue where it only runs once. Below is the code snippet I am working with: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery ...

Using CSS properties as false values within React applications

Can you provide guidance on using conditional styles with conditional operators? What would be the ideal code example? Is it possible to use non-CSS values? margin: isOpen ? '10px' : undefined margin: isOpen ? '10px' : 'initial&a ...

Stable Banner with Automatic Scroll to Sections

I have implemented a script that allows for smooth scrolling to different sections within a webpage when clicking on links in the top navigation menu. In the HTML, I've assigned IDs to each section (section1, section2, section3, etc.) and linked these ...

Mastering React hooks: A guide to effectively updating and rendering elements

Each time I click the delete button, it seems to only remove the last element instead of the specific one based on index. Is there a better way to achieve this without changing from <input defaultValue={name} /> to <input value={name} /> in t ...

What is the best way to notify administrator users when their accounts have exceeded the timeout period?

Working on the website for our high school newspaper, I've encountered a recurring issue on the admin page. Users are getting logged out after creating an article due to a time limit constraint. To address this problem, my goal is to implement an aler ...

Displaying asynchronous promises with function components

Apologies if this post appears duplicated, I am simply searching for examples related to class components. Here is the code snippet I am working with: export const getUniPrice = async () => { const pair = await Uniswap.Fetcher.fetchPairDat ...

Adding npm packages to your Vue.js application

My Vue app is structured like this (auto created by vue init webpack myProject): index.html components/ -main.js -App.vue I am trying to include npm packages, such as https://github.com/ACollectionOfAtoms/atomic-bohr-model. Following the instructions, I ...