Exploring the Haversine Formula and Geolocation Integration in AngularJS

I am currently developing an application that will organize locations based on either name or distance from the user. Everything is functioning properly except for retrieving the distance. I believe I should be able to obtain the user's coordinates through geolocation and already have the coordinates for each location. Is it feasible to calculate the distance using the haversine formula with these coordinates and then assign the distance to each location using object.distance = d? Below is my code and a link to the project Plunk. Plunker: http://plnkr.co/edit/nRQc7Ym0lsaK6jQwd626?p=preview
Code:

    var app = angular.module('app', []);
    app.controller('firstCtrl', function($scope) {

      $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 = [More Locations...];
      $scope.SiteLocs = $scope.SSiteLocs.concat($scope.ASiteLocs);
      repoSortOrder = "site.name";
      navigator.geolocation.getCurrentPosition(GetLocation);

      function GetLocation(location) {
        Lat = location.coords.latitude;
        Lon = location.coords.longitude;

      }

      angular.forEach($scope.SSiteLocs, function(object) {
        object.carrier = 'Sprint';
        getCoordDistance();
        object.distance = $scope.d
      });
      angular.forEach($scope.ASiteLocs, function(object) {
        object.carrier = 'AT&T';
        getCoordDistance();
        object.distance = $scope.d
      });

      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);
        }
      });

      function getCoordDistance() {
        Number.prototype.toRad = function() {
          return this * Math.PI / 180;
        }
        var lat2 = Lat;
        var lon2 = Lon;
        var lat1 = 45;//Test Lat
        var lon1 = -50;//Test Lon

        var R = 3959; // Radius in miles 
        //has a problem with the .toRad() method below.
        var x1 = lat2 - lat1;
        var dLat = x1.toRad();
        var x2 = lon2 - lon1;
        var dLon = x2.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));
        $scope.d = R * c;
      }
    });

In the provided code, when using integers for the Lat/Lons in getCoordDistance() (e.g. lat1 = 5,lat2 = 10,lon1 = 0,lon2 = 0), it successfully calculates and adds the distance to each location. However, when attempting to use my actual location, it fails. Any suggestions?
Thank you in advance for any assistance.

Answer №1

After some investigation, I realized that my function calculateDistance() was not defined.

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

In the realm of Laravel, Vue, and Javascript, one may question: what is the best approach to omitting a key

When working with JSON data, I encountered a problem where leaving some keys unfilled resulted in incorrect results. I want to find a way to skip these keys if they are not filled. I have shared my code for both the backend and frontend below. Backend La ...

Error occurs when an arrow function is called before its function definition

console.log(addB(10, 15)); function addB(a, b) { return a + b; } console.log(addC(10, 15)); const addC = (a, b) => { return a + b; }; I attempted to convert a function into an arrow function and encountered the error "Cannot access 'addC&ap ...

Navigating between Vue Router pages triggers multiple events within the mounted() lifecycle of VueJS

Currently, I am immersed in a project using Electron with a Vue CLI setup and the Vue CLI Plugin Electron Builder. The overall functionality is working perfectly fine except for a peculiar bug that has recently surfaced. The issue arises when navigating b ...

Having difficulties in properly connecting faces while UV mapping a cube in Three.js

After successfully applying an image texture to a cube through UV mapping for a photo-sphere viewer, I noticed that thin straight lines are visible where the faces of the cube join. Interestingly, this issue does not occur when splitting texture tiles via ...

Using JavaScript to display dynamic data pulled from Django models

I am currently in the process of designing my own personal blog template, but I have encountered a roadblock when it comes to creating a page that displays previews of all posts. This particular page consists of two columns, #content-column-left and #conte ...

Using Ajax with Angular services

Recently, I decided to explore Angular JS and Async calls as an alternative to $JQuery. However, I encountered a peculiar issue while making ajax calls. To adhere to 'best practices', I shifted my ajax requests to a service and then initiated th ...

Retrieve the value of an unmatched ng-pattern field

<div> <input type="text" name="rate" ng-model="rate" ng-pattern="/^[0-9]+(\.[0-9]{0,2})?$/"/> </div> <span class="text-warning control-label"> {{rate}} ...

Javascript syntax error: Unexpected ending of data while trying to parse JSON data at line 1, column 1

I operate a CS:GO betting platform, and I encountered an issue when attempting to access the page for withdrawing skins. After completing the reCAPTCHA verification process to confirm that I am not a robot, I received the following error: Javascript err ...

Fixing a Dropdown Problem in Codeigniter

I have encountered a problem with the Dropdown pop-up feature. Specifically, when I click on the "Add New" option in the Dropdown, the pop-up window fails to open. Here is the code for the Dropdown: echo form_dropdown('Birth_Certificate_Storage_id[& ...

Every time the Select box choice is changed, Jade Pug will undergo a new iteration

Recently, I began using a Pug/Jade template to go through an object of events sent from an express app. Everything is working smoothly, but now I've added a select box with a dropdown populated by venues in the event object. I'm facing a seemingl ...

Saving Information to a Specific Location on the Client Side in a CSV File

I am currently working on a static application that uses Angular JS technology. My goal is to write data into a CSV file at a specific path in order for another API to read the data from that location. Despite searching extensively on the internet, I hav ...

Tips for dynamically displaying images in both horizontal and vertical orientations

I would like to showcase images in the imageList. Here is what I want: AB CD How can this be achieved? It's not a matter of being even or odd Perhaps the list could look something like this: ABCDE FG I simply want a new row or display:block when ...

Only submit the form if all files are selected to prevent any missing files from being uploaded

I am currently utilizing the Vue.js framework along with Axios. Within my HTML page, I have incorporated two separate input fields for selecting an image. Additionally, there is a form present on the page. It's important to note that these inputs and ...

endless cycle when utilizing useEffect with a mandatory function

I'm currently in the process of creating a custom hook for sorting and filtering tables within a dashboard application. However, I am encountering an issue with an infinite loop when attempting to refetch data after changing sort or filter fields. The ...

Assistance with organizing date schedules using Javascript

I'm currently assisting a friend with his small project, and we've run into an interesting situation. Imagine a scenario where a doctor informs their patient that starting today, they have X number of consultations scheduled for every Wednesday a ...

JavaScript issue causing input fields to malfunction and clear text boxes

I apologize for the simplicity of this question, but I am struggling with an issue and seeking help. Here's the problem: my calculate() method is not clearing text input as expected when testing my page. Below is the HTML markup and script: <!DOC ...

HTML5 video player with secondary playlist

Looking for a videoplayer setup where there are two playlists, but only one can play at a time. When choosing a video from the first list initially, nothing happens. However, after selecting a video from the second list, the first list starts working. HTM ...

The log indicates that there are two distinct IP addresses associated with the user

I find that this question may be better suited for another Stack Exchange board, and I am open to migrating it there if needed. In the development of a web application, we record certain event information to assist in diagnosing any potential issues. One ...

VueJS computed property not updating correctly

My web application, built with Laravel / Vue JS, includes a google map component and a Vuetify data-table component. The Vue instance also features a computed property that calculates points for the Google Map based on another computed property from the Vu ...

What sets Joomla file inclusion apart from the rest?

Can someone please explain the difference between including a JavaScript script file in the following two ways? I created this within a system plugin in Joomla and included the JavaScript file inside the "onAfterInitialise" function. 1) <script type ...