Calculating the distance between various coordinates in AngularJS

Currently, I am developing an application that involves numerous locations with coordinates. One of the key features I want to implement is the ability to search for locations by their names or find the closest one based on user input. To achieve this, I plan to calculate the distance between two sets of coordinates using the haversine formula. My approach involves iterating through an array of location objects and adding a new element called distance, representing the distance from my current location to each respective location. However, the code I have written doesn't seem to work as intended. Any suggestions or ideas?

function GetLocation(location) {
    // Code snippet here
}

Below are examples of some locations within the application:

"name": "502 Nelson St, Greenville, MS 38701",
    // Location details here
  }, {
    "name": "242 Blackhawk Trace, Galena, IL 61036",
    // Location details here
  }, {
    "name": "3747 Ocean Dr, Vero Beach, FL 32963",
    // Location details here
  }

If you prefer, you can view the demonstration of my app's functionality through the following link:
http://plnkr.co/edit/nRQc7Ym0lsaK6jQwd626?p=preview

Answer №1

When utilizing angular.forEach to iterate over an array of objects, keep in mind that the first argument in the function is the object itself and the second argument is the array index:

angular.forEach($scope.ASiteLocs, function(location, arrayIndex) {
    ...
    location.distance = d;
})

Please note: converting the location.Point.coordinates from a string to an array within the forEach loop will cause the GetLocation function to only operate correctly once due to altering the original location array.

Additionally, defining a function inside a loop is considered bad practice and can be resource-intensive.

Answer №2

If you want to keep your code clean, consider using the npm package haversine-calculator:

const haversineCalculator = require('haversine-calculator')

const start = {
  latitude: -23.754842,
  longitude: -46.676781
}

const end = {
  latitude: -23.549588,
  longitude: -46.693210
}

console.log(haversineCalculator(start, end))
console.log(haversineCalculator(start, end, {unit: 'meter'}))
console.log(haversineCalculator(start, end, {unit: 'mile'}))
console.log(haversineCalculator(start, end, {threshold: 1}))
console.log(haversineCalculator(start, end, {threshold: 1, unit: 'meter'}))
console.log(haversineCalculator(start, end, {threshold: 1, unit: 'mile'}))

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

Angular 2 decorators grant access to private class members

Take a look at this piece of code: export class Character { constructor(private id: number, private name: string) {} } @Component({ selector: 'my-app', template: '<h1>{{title}}</h1><h2>{{character.name}} detai ...

What is the best way to redirect to a specific page when logging out of a website?

To begin, let me outline the situation at hand. We have two distinct websites - website-A and website-B. Each of these websites is hosted on separate domains. A user has the ability to log in to website-B's homepage through the login page of webs ...

Enhancing Child Elements with CSS - Evaluating Rating Systems

Is there a way to change the opacity of certain images inside my div when hovering over them? Specifically, I want the 4th image and the first three to have an opacity value of 1. I've looked into using nth-child but am unsure how to implement it for ...

Quick guide on establishing a remote websocket connection to a Node.js server hosted on Heroku

I am facing issues while trying to establish a connection with a nodejs server using a websocket. Despite my efforts, I have not been successful. The server.js file in question appears as follows: var app = require('express')(); var http = req ...

NodeJS and DiscordJS: The art of modifying JSON files

Currently, I am grappling with the concept of appending data to a JSON file. The specific file in question (users.json) has the following structure: { "users": { "id": "0123456789", "name": "GeirAnders ...

Navigating with Express 4

Currently, I am in the process of implementing Passport for user signup by referring to this helpful guide: https://scotch.io/tutorials/easy-node-authentication-setup-and-local Overall, everything is functioning properly except for one issue - after a su ...

"Error encountered when making a request to Google API using Ember.js, response remains

Trying to fetch place suggestions from Google API using Ember js. Below is the code snippet for the service module: fetch(){ let url=`https://maps.googleapis.com/maps/api/place/autocomplete/json?input=IL&types=geocode&key=API_KEY` return Ember.RSV ...

Tips for eliminating nested switchMaps with early returns

In my project, I have implemented 3 different endpoints that return upcoming, current, and past events. The requirement is to display only the event that is the farthest in the future without making unnecessary calls to all endpoints at once. To achieve th ...

The filter on the mobile version is not displaying correctly

When I select a category in the input filter, only items with the same category are displayed when clicked. However, when I click on "Others" on the desktop version, only rows with that category are shown, but on mobile after resizing and filtering, nothin ...

Utilize a Javascript function to retrieve a string and set it as the ID

I'm trying to modify a div ID by appending either a 'W' or 'H' depending on whether the screen width is greater than the height. I figured I could achieve this using JavaScript since PHP lacks the ability to detect screen sizes. A ...

Can I stream a file from an external server in NodeJS without routing it through my own server?

My website provides links for downloading or streaming media files from another server. Currently, my setup looks something like this: download = (req, res) -> song_id = req.params.id download_url = "http://mediaserver.com/#{song_id}" console.log ...

Check the box to show the corresponding sections of the form

https://i.sstatic.net/oXw8K.png.If there are two checkboxes with options true or false, how should I handle a third checkbox? I want to display different parts of the form based on the selection of the checkboxes. ...

Exploring the art of manipulating HTML code using JavaScript

I am looking to implement a specific change using JavaScript: <input id="innn" value="" /> to: <input id="innn" value="SOME_VALUE" /> I attempted the following methods: document.getElementById("innn").setAttribute("value", "189"); and als ...

Combining Objects in Angular 2: Extending Your Data Structures

Looking to combine 2 objects in Angular 2? In AngularJS 1, we used the "merge" and "extend" functions: https://docs.angularjs.org/api/ng/function/angular.merge https://docs.angularjs.org/api/ng/function/angular.extend However, it seems like there is no e ...

Identify the index of a list item using a custom list created from buttons

When dealing with a dynamically built list like this: <ul id="shortcuts"> <li><input type="checkbox" value="false"/><button>foo</button><button>-</button></li> <li><input type="checkbox" value ...

Retrieving entities from a text

I found a script on the Webdriver.io website that looks like this (adjusted for testing) const { remote } = require('webdriverio'); var assert = require('assert'); ;(async () => { const browser = await multiremote({ ...

PHP extract both the HTML body content and the associated HTML tags, not just the plain text

I am new to PHP and I am attempting to extract the entire body tag from an HTML using PHP. Here is a sample of my HTML: <html> <body > <p> Example html content </p> </body> </html> I want to extract only the followi ...

Putting together Numpy Arrays Simultaneously

I have been experimenting with parallelizing an algorithm I've been developing using the Multiprocessing and Pool.map() commands. However, I encountered a challenge and would appreciate some guidance. Consider x as an array of N rows and 1 column, in ...

IE9 Error: Uploads with Fine Uploader are unsuccessful

I'm encountering a strange issue with fine uploader (version 3.0). It functions properly on all browsers except for Internet Explorer 9. There are no JavaScript errors, but it fails to upload and results in a 0-byte file. I'm using the valums PH ...

Having trouble with accessing input field in a modal that was generated by TinyMCE React within a Next.JS environment

In my current project, I am utilizing Next.JS and looking to incorporate the TinyMCE editor onto my webpage. Here is the code snippet I have implemented: <TinyMceEditor selector='textarea' initialValue={ props.value } apiKey=<AP ...