The error message "a.lat is not a function" is indicating a problem with the

As I was working on a code to extract data from a CSV file using a split function as the separator, and then calculate the distance between two sets of input coordinates, I encountered an error message stating "a.lat is not a function." Despite searching online for solutions to this specific error, I have been unable to find a resolution. Can anyone offer assistance in resolving this issue?

Here is an example of the coordinates I am working with:

-6.168454914420734, 106.7574467
-6.16897225004169, 106.7570443

Below is the code snippet that I am currently using:

<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry"></script>

<script>
function calcDistance(p1, p2){
  return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}

function encodeLatLngPolygon(array) {

var polyOptions = {
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
  }
  poly = new google.maps.Polyline(polyOptions);

var path = poly.getPath();

for(var i=0;i<array.length;i++) {
    var xyz = new google.maps.LatLng(parseFloat(array[i][0]).toFixed(2), parseFloat(array[i][1]).toFixed(2));
    path.push(xyz);            

}

var code = google.maps.geometry.encoding.encodePath(path)

return code;
}

function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;

                var byline = allText.split('\n');

                for(var e=0;e<4;e++){
                var coor=byline[e].split(',');
                alert(calcDistance(coor[0],coor[1]));

                }



            }
        }
    }
    rawFile.send(null);
}

function initialize() {
  var mapProp = {
    center:new google.maps.LatLng(51.508742,-0.120850),
    zoom:5,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  };
  var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);

  readTextFile("DaerahG.csv");


}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<title>kenny</title>
</head>

<body>
<div id="googleMap" style="width:1000px;height:700px; float:left;"></div>

</body>

</html>

Answer №1

When using the calcDistance function, ensure that you are passing in google.maps.LatLng objects instead of plain numbers or strings. The

google.maps.geometry.spherical.computeDistanceBetween
method requires two google.maps.LatLng objects with a .lat() method for accurate distance calculations.

function calcDistance(p1, p2){
  return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}

for(var e=0;e<4;e++){
  var coor=byline[e].split(',');
  alert(calcDistance(coor[0],coor[1]));
}

Snippet Code:

function calcDistance(p1, p2) {
  return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}

var allText = "-6.168454914420734, 106.7574467\n-6.16897225004169, 106.7570443";
var byline = allText.split('\n');
var path = [];
for (var e = 0; e < byline.length; e++) {
  var coor = byline[e].split(',');
  path.push(new google.maps.LatLng(coor[0], coor[1]));
  if (path.length > 1)
    alert(calcDistance(path[0], path[1]));
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

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

Form submission issue with dynamically added input fields within a modal

I'm facing a problem where dynamically added input fields in a modal are not being included when the form is submitted. The scenario involves a modal with a form, where input fields are added dynamically upon clicking an "Add" button. Each input fiel ...

Iterate through every item in Google Docs and duplicate them onto a fresh page

I am currently developing a script that allows teachers to easily create translations of documents stored on Google Drive. The script is expected to go through the body elements of the document, translate the text, and paste it onto a new page appended to ...

What is the process for creating a tab logo?

Is there a way to create a personalized logo to appear next to the website title on the tab? Whenever I see a logo displayed beside the website title in my browser tabs, I can't help but wonder how it's done. ...

Using jQuery to filter or duplicate options in a select box - a step-by-step guide!

I am struggling with filtering options in two select boxes. One contains projects and the other contains people: <select id="project"> <option data-person_ids="[75,76,77]">None</option> <option data-person_ids="[77]">Project A& ...

When res.write is called before res.send, an error occurs

I'm struggling to figure out why I am getting an error with the following code. app.get("/", (req, res) => { res.write("Hello"); res.send(" World!"); }) // Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers afte ...

What is the technique for arranging the display of a component in React?

Is there a way to dynamically render a component in my react-app at a specific date and time, like 6.00PM on October 27, 2022? I want to release a form for signing up starting from that exact moment. The timestamp information will be stored in my database ...

Use Javascript to conceal a div element if there are no links present

I am working on a website using ModX CMS and I am attempting to hide or remove a div element when it does not contain any anchor tags. How can I achieve this? I have already attempted the following code without success: jQuery(function($) { if ($(".pages ...

Executing a query in MongoDB to retrieve data from multiple collections simultaneously

Currently, I have two separate collections for different types of products. My goal is to retrieve all documents from both collections that belong to a specific user. I am aware that I could achieve this by running 2 queries for each collection, merging t ...

I'm curious about the distinction between React's one-way data binding and Angular's two-way data binding. Can someone please clarify the key differences

My understanding of these concepts is a bit hazy. If I were to develop the same ToDo application using AngularJS and ReactJS, what exactly distinguishes React ToDo's use of one-way data binding from AngularJS's two-way data binding? From what I ...

Tips for adding and verifying arrays within forms using Angular2

Within my JavaScript model, this.profile, there exists a property named emails. This property is an array composed of objects with the properties {email, isDefault, status}. Following this, I proceed to define it as shown below: this.profileForm = this ...

I keep getting an error message that says "The JSX element type does not have any construct or call signatures."

I am currently developing an application that takes user input through buttons and creates an array. However, when I attempt to display the array, I encounter a JSX element type error. import { Delete } from "lucide-react" export function Passwo ...

Retrieve events from database within angular-calendar

My challenge lies in loading events from the database onto my calendar view using angular-calendar. I have created an API that returns resources, but I am struggling to bind them onto CalendarEvents. Here is the part where I am attempting to do so: https:/ ...

Sorting Tables - My goal is to ensure that when sorting parent rows, the child rows are also correctly moved along with them

Can I sort parent rows and move child rows along with them using JavaScript? Here is an example of my table structure: <table> <tr class="parent"> <th id="apple">Apple</th> <th id="orange">Orange</th> ...

The console log displays an unhelpful response even after attaching a then function to it in the chain

While I am attempting to implement a promise in my JavaScript file, I have encountered a peculiar issue. Upon logging the returned value within the function, this is what I see: const id = getAccounts() .then(res => res.find(acc => acc.type === ACC ...

Exploring the concept of variable scope with modules in Node.js

I have been searching for information on creating modules and came across some great tips, but not much is available regarding variable scope within module usage. Initially, my program was all in one document var mongodb = require('mongodb'); ...

Ways to retrieve the value of a concealed element without any activation signal

In my project, I've created a slider that dynamically shows different forms one by one. Each form contains a hidden element with a specific value that I need to retrieve (using its class) every time a new form is displayed. This way, I can use that el ...

Return to the initial stage of a multistep process in its simplest form following a setTimeout delay

I recently customized the stepsForm.js by Copdrops and made some modifications. Although everything works well, I'm struggling to navigate back to the initial step (first question) after submitting the form due to my limited knowledge of JavaScript. ...

The header.ejs file is unable to render the image

As I work on my website, I had the brilliant idea of using a JavaScript HTTP header (via express) to avoid having to recreate a header and footer on every single file. And guess what? I successfully implemented it! But now I'm facing an issue with ins ...

URL for image preview on Amazon S3

Is there a way to retrieve preview images from my Amazon S3 image storage instead of always fetching the full-sized 5MB images? If necessary, I would then be able to request the normal image. ...

Vue JS encountering issues in rendering method's returned data on DOM

HTML Template <div class="item" v-for="n, index in teamRoster"> <span> {{ getFantasyScore(n.personId) }} </span> </div> Function getFantasyScore(playerId) { if(playerId) { axios.get(config.NBLAPI + config.API.PLAYE ...