One possible rewrite: "Iterate through an array of coordinates to determine the distance

I've developed a running app that keeps track of the runner's location and saves the coordinates into an array successfully. Now, I'm facing an issue where I need to loop over the array to calculate the total distance traveled.

Here is the code snippet:

        var startPos;
        var num;
        var distance;

        navigator.geolocation.getCurrentPosition(function (position) {
            startPos = position;
        });
        //
        watchID = navigator.geolocation.watchPosition(function (position) {

        pathArr.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
        var latlng = new google.maps.LatLng(lat, lon);

        var num = calculateDistance(startPos.coords.latitude,startPos.coords.longitude,
        position.coords.latitude, position.coords.longitude);
        distance = num;
        },


        function (positionError) {
            $("#error").append("Error: " + positionError.message + "<br />");
        }, {
            enableHighAccuracy: true,
            timeout: 30 * 1000
        });


function calculateDistance(lat1, lon1, lat2, lon2) {
    var R = 6371; // km
    var dLat = (lat2 - lat1).toRad();
    var dLon = (lon2 - lon1).toRad();
    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c;
    return d;
}

Upon testing, I noticed that the calculation only works accurately when walking in a straight line because it always measures from the starting point to the current one. If the runner circles back to the starting point, the total distance will be zero or close to it. To fix this, I attempted the following:

        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
        var latlng = new google.maps.LatLng(lat, lon);

            num += calculateDistance(startPos.coords.latitude, startPos.coords.longitude,
            position.coords.latitude, position.coords.longitude);
            startPos = latlng;
            distance = num;

However, this did not yield the expected results. Any assistance would be greatly appreciated.

Answer №1

To calculate the total distance, you must loop through all geographical coordinates in your array and determine the distance between each consecutive pair of coordinates. Add these distances together to get the total distance traveled.

The key snippet of code looks like this:

If we assume that coordinates is the array holding the geographical coordinates,

for (var i = 0; i < coordinates.length - 1; i++) {
    totalDistance += google.maps.geometry.spherical.computeDistanceBetween(coordinates[i], coordinates[i+1]);
}

For a practical example using the Google Maps API, check out this demo: http://jsfiddle.net/90kbnjqx/2/

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

Error: A TypeError occurred with the startup because it was unable to read the property 'Collection' as it was

Recently, I encountered a series of problems one after another. The first issue was: TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client To resolve this problem, I made changes to my code from: const Discord = require(" ...

Enhance the numerical value displayed in jQuery UI tooltips

I have folders with tooltips displaying text like '0 entries' or '5 entries' and so on. I am looking for a way to dynamically update this tooltip number every time an item is added to the folder. The initial count may not always start a ...

Conceal the message using star symbols

I need help figuring out how to hide a certain type of string input from the user, and then use Angular data binding to display it in another component with part of the data masked with asterisks. I'm not very skilled in JavaScript, so I'm wonder ...

Filter out all elements in an array except for one from a JSON response using Angular 2

After receiving a JSON response from a server via HTTP GET, the data structure looks like this: { searchType: "search_1", overview: [ "Bed", "BedSheets", "BedLinen", .. ...

The save button click handler is not triggering JQuery Validation

I've been attempting for hours to get the validation working, but without success. I have added the name attribute to the input element and included script sources as well. Even after firing the validate method, the contents are still not being valida ...

Can WebDriverJS be compiled without code minimization using Google Closure Compiler?

I am in need of customizing WebDriverJS to suit my specific requirements. However, I am encountering difficulties with debugging the compiled source code. Having descriptive function names and comments would greatly assist me! Therefore, I am curious to kn ...

Tips for displaying the most recent data in Vue following a successful fetch operation

I have the following script to load data from the server after the page loads: <script> export default { data() { return { imageDirectory: "../../images/", fileName: "img", ...

Fetching post value via AJAX in Codeigniter views: A step-by-step guide

Having issues receiving Ajax response as it is coming back null. The HTML layout includes: <form method="post" action="<?php $_SERVER['PHP_SELF'] ?>"> <select class="form-control" class="form-control" id="choose_country"& ...

Removing data from firestore/storage does not follow the expected pathway

I have created an image gallery for users using Firebase Storage and React, allowing them to upload and delete images. However, I am facing an issue where the deletion process is taking longer than expected. Expected flow: User clicks on the trashcan ico ...

When incorporating Typescript into HTML, the text does not appear in bold as expected

Issue with bold functionality in Typescript Hey there, I am currently involved in an Angular project and I came across a problem with a function in a Typescript file that is supposed to bold a specific segment of text formatText() { ......... ...

What is the process for changing and updating the key of an object based on comparisons with other objects?

My task involves working with an array of objects that contain unique IDs as keys. const sampleObj1 = {0011:[{},{}], 0022:[{}, {}], 0033:[{},{}]} const sampleObj2 = [{id:0011, name:'test1'}, {id:0022, name:'test2'}, {id:0033, name:&apos ...

Once the submission is made, the website will automatically refresh

As I delved into working on a web page utilizing JavaScript, I implemented a jQuery function to validate user input data. I ensured that if the data was incorrect, the function would return false (return false;) and the form would not refresh the page. How ...

Attempting to upload information using AngularJS

https://i.sstatic.net/S4ZtU.jpg Hello there! I'm facing a challenge with Angular once again. Despite searching extensively on Google and in this forum, I haven't found a solution to my problem yet. Here's the issue: Currently, I have a loc ...

Retrieve the name of the page instead of the page number using PHP in combination with AJAX

I found a helpful tutorial on using AJAX to load content on a website. However, the tutorial uses generic page names like "page1, page2, page3, etc." and I want to use specific page names like "products, about, etc.". I've been working on the code in ...

Selecting any of the bar chart labels will reveal just a two-day timeframe

My bar chart is behaving strangely - when I click on all labels, it only shows two days instead of updating as expected. I suspect it may be due to a bad implementation involving parsing. Can anyone provide assistance? I have created a minimum example on ...

Loading static assets in Express.js

I am currently utilizing express for developing a web application. However, I am encountering issues with my routes and static files. I have included a reference to static files: app.use(express.static(path.join(__dirname, 'public'))); and conf ...

Storing data with dots in MongoDB

I need help with saving JSON API data to a MongoDB collection. The JSON data I am working with has a structure like this: compatibility: { 2.7.1: { 2.2.6: [ 100, 1, 1 ] }, 2.8.3: { ...

Top method for stacking several divs in a vertical line

In search of the most effective method for organizing numerous dynamically generated divs (all with identical widths) in a vertical stack, two potential solutions have emerged: Utilize float:left... Implement an unordered list and enclose each div within ...

Using webpack to load the css dependency of a requirejs module

Working with webpack and needing to incorporate libraries designed for requirejs has been smooth sailing so far. However, a bump in the road appeared when one of the libraries introduced a css dependency: define(["css!./stylesheet.css"], function(){ &bsol ...

Delete the specified element from the string array

Can someone provide a C function that can remove the N-th element from a char* (treating the char* as an array)? For example: char* tab --> |5|4|5|1|8|3| remove_elt(tab, 3) --> 5|4|5|8|3| ...