Exceedingly High Outputs from the Haversine Formula

I am currently utilizing the Haversine formula in order to compute the distance between two specific points on the earth's surface. Below is the code snippet I am using:

    var app = angular.module('app', []);
app.controller('firstCtrl', function($scope, $timeout) {
  var myLat, myLon, locLat, locLon;
  navigator.geolocation.watchPosition(GetLocation)

  $scope.ASiteLocs = [{
    "name": "IL5077 BRUSSELS",
    "styleUrl": "#waypoint",
    "Point": {
      "coordinates": "-90.58543899999999,38.955472,0"
    }
  }, {
    "name": "IL5076 KAMPSVILLE",
    "styleUrl": "#waypoint",
    "Point": {
      "coordinates": "-90.661923,39.29403,0"
    }
  }, {
    "name": "IL5146 CARROLLTON",
    "styleUrl": "#waypoint",
    "Point": {
      "coordinates": "-90.39965700000001,39.309142,0"
    }
  }, {
    "name": "IL5153 GREENFIELD",
    "styleUrl": "#waypoint",
    "Point": {
      "coordinates": "-90.208747,39.364077,0"
    }
  }];
  $scope.SSiteLocs = [];
  $scope.SiteLocs = $scope.SSiteLocs.concat($scope.ASiteLocs);
  repoSortOrder = "site.name";


  function GetLocation(location, myLat, myLon) {
    myLat = location.coords.latitude;
    myLon = location.coords.longitude;
    document.getElementById("lat").innerHTML = myLat;
     document.getElementById("lon").innerHTML = myLon;
    $timeout(function() {
      calculate();
    });

  }

  $scope.getCoordDistance = function(myLat, myLon, locLat, locLon) {
    var lat1 = locLat; //41.887055
    var lon1 = locLon; //-88.469233
    var lat2 = myLat; //41.888668
    var lon2 = myLon; //-87.640371

    var R = 3959;
    var x1 = lat2 - lat1;
    var dLat = x1 * Math.PI / 180;
    var x2 = lon2 - lon1;
    var dLon = x2 * Math.PI / 180;
    a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
      Math.sin(dLon / 2) * Math.sin(dLon / 2);
    c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c;
    return d;

  };


  angular.forEach($scope.SSiteLocs, function(object) {
    object.carrier = 'Sprint';
  });
  angular.forEach($scope.ASiteLocs, function(object) {
    object.carrier = 'AT&T';
  });
var i = 0;
locX = 1;
  var calculate = function() {
    angular.forEach($scope.SiteLocs, function(location) {
      var clength = location.Point.coordinates.length;
      if (location.Point.coordinates.substring(clength - 2, clength) === ",0") {
        location.Point.coordinates = location.Point.coordinates.substring(0, clength - 2).split(",");
        Lat = location.Point.coordinates[0];
        Lon = location.Point.coordinates[1];
        Com = ",";
        location.Point.coordinates = Lon.concat(Com, Lat);
      myLat = Number(document.getElementById("lat").innerHTML)
      myLon = Number(document.getElementById("lon").innerHTML)

      locLat = Lat;
      locLon = Lon;
      d = $scope.getCoordDistance(myLat, myLon, locLat, locLon);
      location.distance = d.toFixed(1);

    if(i < 15){
      console.log("********LOCATON " + locX + "***********")
      console.log("myCoords: " + myLat + "," + myLon);
      console.log("locCoords: " + locLat + "," + locLon);

      console.log("d: " + d);
      console.log("***************************")
      i++;
      locX++;

    }
    }

    });
  };


});

The output generated by the formula seems unusually high, reaching about 9-10 thousand instead of the expected value. Interestingly, when using commented out coordinates, the correct result (42.6 Miles) is returned. The discrepancy in results between different browsers like Chrome and IE indicates that it might not be a mathematical issue. Does anyone have insight into what could be causing this discrepancy?
EDIT
Here is a plunker link to the full project for further assistance.
EDIT2
Upon further investigation, I noticed that the results vary across different browsers, with Chrome displaying one set of numbers and IE showing another, etc.

Answer №1

Your point coordinates are represented by longitude and latitude

BRUSSELS",
    "
    "Point": {
      "coordinates": "-90.58543899999999,38.955472

Incorporate the following code in your project

Lat = location.Point.coordinates[0];
Lon = location.Point.coordinates[1];

You can either modify them within your object(preferred) Refer to Google's latlng class

"Point": {
          "coordinates": "38.955472,-90.58543899999999

or

Lat = location.Point.coordinates[1];
Lon = location.Point.coordinates[0];

By keeping your current settings, the approximate distance is 9000 miles. If you interchange the coordinates, the distance will be approximately 200 miles

Answer №2

Adding onto kirinthos' input, you can verify the accuracy of your results by cross-referencing them with Google Maps. I integrated a specific function in my application to facilitate this comparison, utilizing simple Latlng objects for point1 and point2 parameters. To ensure measurement in kilometers, I included a division by 1000.

function determineDistance(point1, point2) {
    return (google.maps.geometry.spherical.computeDistanceBetween(point1, point2) / 1000).toFixed(2);
}

To incorporate this feature into your HTML page, include the following script:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,places"></script>

Answer №3

It's a bit uncertain without testing, but it seems like the GetLocation function is causing issues by reassigning the variables myLat and myLon within its scope, potentially overriding their values set earlier in the code block.

To troubleshoot, try adding a console.log(myLat, myLon) at the start of getCoordDistance to see if they hold the expected values.

Additionally, make sure to include proper semicolons and adjust variable references for "i" and "locX" not being defined errors. Here's a revised snippet with corrections for potential syntax discrepancies:

// Your updated code here
// Ensure all variables are properly defined and semicolons are applied where necessary

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

Use jQuery to retrieve the response from a JSON request and showcase it on the existing HTML page

Currently, I am working on a project that involves integrating a JSON-based web service from a remote server. The method of this service can be accessed by using specially formatted URLs such as: http://root-url/ws/service-name?request={json-string} The ...

Enable retrieval of calculated time duration in jQuery time picker

After implementing two separate timepickers for calculating a time duration, I am looking to access this computed duration for further calculations later on the page. How can I retrieve the duration that is already displayed to the user after using the sec ...

JavaScript: void(0), Internet Explorer 6, and SWFAddress are all important components

Hello there, We are on the verge of launching a secure website (regrettably, we cannot provide the URL) and have come across a rather obscure bug in IE6 that I am hoping someone may have experienced or could shed some light on. This issue only arises when ...

Choosing an ID along with a numerical value in jQuery

Being new to both stackoverflow and jQuery, I'm facing a challenge in creating a basic function. In my website, there are multiple links with IDs such as "filtro1", "filtro2", and so on. My goal is to write a single piece of code that will be trigger ...

Ant Design Table isn't triggering a re-render

My goal is to update a table to display "Tag" when the switches on my Antd table are flipped on. However, it seems like there is an issue with how the table is being rendered. https://codesandbox.io/s/staging-star-0itd6 Any assistance would be greatly ap ...

JavaScript - Identifying Repetitive Items in an Array

My goal is difficult to explain in words, but I can show you with code. Here is the array I am working with: var array = [{name:"John",lastname:"Doe"},{name:"Alex",lastname:"Bill"},{name:"John",lastname:"Doe"}] This array has duplicate elements, and I n ...

Removing a Div with Dynamic Parameters

I'm struggling to implement a feature in my form that allows the user to add multiple entries, but I'm having trouble with the removal aspect. Here is the JavaScript code: var i = 1; var divContent = document.getElementById ...

I must create text that is transparent against a colorful gradient background

Hey there! I'm seeking help in figuring out how the text on this site is designed. You can take a look at it here. Essentially, what I'm aiming for is to have the text color match the gradient of the background color from the previous div, while ...

Which takes precedence: the end of the script tag or the backtick?

Currently, I am working on developing a page builder widget. My goal is to save the entirety of the HTML code for the edited page to both local storage and a database. The PHP script will load the saved HTML from the database, while JavaScript will handle ...

The event handler on line 72 triggered an error that was not handled, resulting in an error message indicating a permission issue on OpenShift: "Error: cannot listen for connections

I have been working on creating a basic chat app. Initially, it was running smoothly on localhost:3000/chat.html. However, upon deployment on OpenShift, I encountered a crash accompanied by the following error message (as seen after running rhc tail): UPD ...

Maintain the chosen month in every dropdown toggle div in angular 4

While displaying data using toggle options, I am facing an issue where if I click on a different month, all other greyed out headers are displaying the previously selected values. I am trying to figure out a way to keep the value under Selected month as i ...

Sending images from an external source to a client using Node.js and Express

I'm struggling with a problem. Assuming I have an external image URL, like this one from IMDb.com, . How can I display this image for the client? Currently, I have this: res.write('<img src="/http://ia.media-imdb.com/images/M/MV5BMTMyMzA5ODI ...

Using Mongoose to Implement the Repository Pattern in Node.js

As a newcomer to node.js with a background in .net, I am interested in applying some of the design patterns I used with c#.net. However, I am encountering challenges due to the differences in object-oriented nature between c# and JavaScript. Specifically, ...

In Chrome version 69.0.3497.100, material design does not display dynamic elements off the screen

STACK: react: 16.8.6 redux: 4.0.1 DESCRIPTION: When using $compile to dynamically add elements on a page, I encountered an issue in Firefox (76.0) where input elements that are out of the screen are not rendered. Only the labels are displayed. view image ...

Scrolling a div automatically without affecting its parent element

On a page, I have a scrollable list of items that can be updated with a PUT request. Once the update is successful, another network request is made to fetch the updated list. The goal is to automatically highlight the recently updated item in the list. Al ...

How about we display the Extents Algorithm?

Oh wise and knowledgeable coding community, I come seeking your expertise... I am working with the three.js library and facing a challenge in implementing a 'show extents' button. This button should adjust the camera position so that all objects ...

Checking the types of arrays does not function properly within nested objects

let example: number[] = [1, 2, 3, 'a'] // this code block correctly fails due to an incorrect value type let example2 = { demo: 1, items: <number[]> ['a', 'b'], // this code block also correctly fails because of ...

Issue with integrating React, Material UI, Typescript, Webpack, and server-side rendering (SSR

I encountered an issue with my server-side rendered app when I tried to integrate Material UI into it. Here is how my directory structure looks: app/ build/ * This directory is generated by webpack server_bundle.js public/ ...

Experiencing issues with creating HTML using JavaScript?

I'm a JavaScript novice and struggling to figure out what's wrong with my code. Here is the snippet: var postCount = 0; function generatePost(title, time, text) { var div = document.createElement("div"); div.className = "content"; d ...

How many controllers should be assigned to each view and what is the best way to allocate them?

Seeking feedback on controllers and views. Currently, I assign 1 controller per view, giving the controller responsibility for the entire view. However, I have learned that you can use ng-controller to assign multiple controllers to different parts of a ...