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

The custom confirmation popup is experiencing technical issues

Currently, I am utilizing a plugin to modify the appearance of the confirm popup. Although I have successfully customized the confirm popup, I am encountering an issue where upon clicking the delete icon, the custom confirm popup appears momentarily before ...

Utilizing PHP to fetch data from a separate webpage

This is a question that has sparked my curiosity. I am not facing any particular issue that requires an immediate solution nor do I possess the knowledge on how to achieve it. I have been contemplating whether it is feasible to utilize PHP for fetching co ...

Guide to sending a response to an AJAX post request in Express with Node.js: Answered

For a project focused on practicing Node.js and jQuery Ajax, I'm working on a simple task. Essentially, I have an ajax post request that sends data to a Node.js server and waits for a response. On the server-side, there's code that processes this ...

Mongoose encountered an error when attempting to cast the value "......" as an ObjectId in the "author" path. The error was caused by a BSONError

I'm currently facing an issue with Mongoose in my NextJS project. Specifically, I am encountering a problem when trying to save a document where one of the fields references an ObjectId. The error message I receive is as follows: Cast to ObjectId fail ...

Toggle button visibility on ng-repeat item click

Hello everyone, I'm encountering an issue with displaying and hiding buttons in ng-repeat. <div class="row" ng-repeat="item in items"> <button type="button" ng-click="add()">+</button> <button type="button" ng-click="remo ...

Creating a way for a Node and React application to share classes

I am in the process of developing a Node and React application, both implemented using TypeScript. The directory structure of my project is illustrated below: https://i.sstatic.net/914A1.png My query: Given that I am utilizing the same programming langu ...

Navigating without the need for a mouse click

Is there a way to automatically redirect without user interaction? I need the redirection to happen without clicking on anything <script> setInterval(function(){ window.location.replace("http://your.next.page/"); }, 5000); // Redirec ...

How to show multiline error messages in Materials-UI TextField

Currently, I am attempting to insert an error message into a textfield (utilizing materials UI) and I would like the error text to appear on multiple lines. Within my render method, I have the following: <TextField floatingLabelText={'Input Fi ...

Generating fresh Mongodb Records versus Appending to a Document's Collection

A device that records temperature data every second feeds into a real-time chart using Meteor.js to display the average temperature over the past 5 seconds. Should each temperature reading be saved as a separate MongoDB document, or should new readings be ...

Undo a CSS transition when clicked

There is a div named learn-more which expands to fill the whole page when a CSS class is added like this: .learn-more{ padding:10px; font-size: 20px; text-align: center; margin-top:20px; font-family: klight; -webkit-transition:2s; ...

Unable to reference the namespace 'ThemeDefinition' as a valid type within Vuetify

Looking to develop a unique theme for Vuetify v3.0.0-alpha.10 and I'm working with my vuetify.ts plugin file. import "@mdi/font/css/materialdesignicons.css"; import "vuetify/lib/styles/main.sass"; import { createVuetify, ThemeDefinition } from "v ...

Load subtitles into your video in real-time

Let's discuss the scenario: The server is receiving a stream of SRT file. This stream is then converted into VTT format by the server, which is further buffered and sent to the client through an io.socket connection. Below is the server-side code: s ...

What is the process for retrieving the value of `submit.preloader_id = "div#some-id";` within the `beforesend` function of an ajax call?

In my JavaScript code, I have the following written: var formSubmit = { preloaderId: "", send:function (formId) { var url = $(formId).attr("action"); $.ajax({ type: "POST", url: url, data: $(formId).serialize(), dataTy ...

Error: Unable to locate attribute 'indexOf' within null object in vuejs when using consecutive v-for directives

I've been struggling with this issue for hours. I'm using vuejs' v-for to render items in <select> element's <options>, but I keep getting a type error. I've tried changing the :key values, but it still won't rende ...

javascript download multiple PDF files on Internet Explorer

I am facing an issue with downloading multiple PDF files In my list, I have various a elements with links to different PDF files. I created a loop to go through each a element and generate an iframe using the value of the href as the source. This solutio ...

Utilize the Discord SDK to broadcast a message to every channel within a server whenever a command is utilized

In the process of development, I have crafted a new command: ! sir snd all -hello Essentially, this particular command instructs to dispatch the message specified after " - " to every channel located on the server where the command is initiated. Here&apo ...

jquery allows you to toggle the visibility of content

There are two divs with a button positioned above them. Initially, only one div, the catalogusOrderBox, is visible. When the button named manualButton is clicked, it should display the manualOrderBox div while hiding the catalogusOrderBox div. The text on ...

Ways to retrieve Data obtained in response using superagent

I am currently working on hitting an API and extracting the data received in response. To achieve this, I am utilizing superagent to retrieve the data from the API. I have inspected my network tab, however, I am encountering an issue where I want to extra ...

SignalR 2.2 application encountering communication issues with client message reception

I am facing an issue in my application where clients are not receiving messages from the Hub when a user signs in. Here is my Hub class: public class GameHub : Hub { public async Task UserLoggedIn(string userName) { aw ...

Having difficulty pinpointing and deleting an added element using jQuery or JavaScript

My current task involves: Fetching input from a form field and adding the data to a div called option-badges Each badge in the div has a X button for removing the item if necessary The issue at hand: I am facing difficulty in removing the newly appended ...