Is there a way to filter and tally the JSON objects that have latitude and longitude within a 10km radius from the

I'm currently working on filtering and counting objects from an API endpoint that fall within a 10km radius of the specified origin. My main challenge lies in correctly filtering the API results and tallying the number of matching items.

While I successfully managed to filter the data based on cities like "Hong Kong" and count them using a simple comparison, calculating distances introduces another layer of complexity to the data filtering process.

coords = [
      {
         City: "Hong Kong",
         Lat: “22.667790”, 
         Long: “-111.909905” 
      },
      {
         City: "Atlanta",
         Lat: “22.958769”, 
         Long: “-111.948939”
      },
      {
         City: "Paris",
         Lat: “23.989803”, 
         Long: “-112.989850”
      },
      {
         City: "Sydney",
         Lat: “22.001118”,
         Long:”-111.939433”
      },
      {
         City: "Hong Kong",
         Lat: “22.667790”, 
         Long: “-111.909905” 
      }
];

origin = {  
     lat:"22.111009",
     long: "-113.667870"
};

function getDistance(lat1, lon1, lat2, lon2) {
     var R = 6371; // Radius of the earth in km
     var dLat = deg2rad(lat2 - lat1); // deg2rad below
     var dLon = deg2rad(lon2 - lon1);
     var a =
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
        Math.sin(dLon / 2) * Math.sin(dLon / 2);
     var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
     var d = R * c; // Distance in km
     return d;
}

function deg2rad(deg) {
     return deg * (Math.PI / 180);
}

var filteredCities = coords.filter(function(coord){
    distance = getDistance(coord.lat, coord.long, origin.lat, origin.long);

    if (distance < 10){
        return true;
    }

});

console.log("Number of cities within 10km of the origin: ", filteredCities.length);

So far, my attempts have only resulted in generating a list of distances between the origin and each object. The goal is to determine how many cities are situated within a 10km range of the given origin point.

Answer №1

To achieve this, utilize the filter function:

const filtered = items.filter(item => {
    result = processItem(item.property);
    return result < 20;
});

Now, the refined outcomes are saved in an array called filtered

Answer №2

To refine your list, you can utilize the array.filter method. It is essential for the distance from your starting point to be less than 10km and none of your listed cities should match. Here's an example:

var locations = [{
    City: "Hong Kong",
    lat: "22.667790",
    long: "-111.909905"
  },
  {
    City: "Atlanta",
    lat: "22.958769",
    long: "-111.948939"
  },
  {
    City: "Paris",
    lat: "23.989803",
    long: "-112.989850"
  },
  {
    City: "Sydney",
    lat: "22.001118",
    long: "-111.939433"
  },
  {
    City: "New York",
    lat: "22.679940",
    long: "-112.977915"
  }
];


startLocation = {
  lat: "22.611009",
  long: "-111.967870"
};

function calculateDistance(lat1, lon1, lat2, lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = degreesToRadians(lat2 - lat1); 
  var dLon = degreesToRadians(lon2 - lon1);
  var a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(degreesToRadians(lat1)) * Math.cos(degreesToRadians(lat2)) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var distance = R * c; // Distance in km
  return distance;

}


function degreesToRadians(deg) {
  return deg * (Math.PI / 180);
}



var matchingLocations = locations.filter(function(location) {
  return calculateDistance(location.lat, location.long, startLocation.lat, startLocation.long) < 10;
});

console.info(matchingLocations);

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

Incorporating a JavaScript workflow into Django

Currently, I am following a tutorial on integrating a modern JavaScript pipeline into my Django application. The objective is to have the JavaScript code write "Hello webpack" onto the page, but unfortunately, it is not displaying as expected. Since I alr ...

The Javascript array does not function like a typical array

I am currently facing a perplexing issue while working with the Twitter API. Below is the script causing the confusion: const Twitter = require('twitter-api-stream') const twitterCredentials = require('./credentials').twitter const t ...

Is there a way to extract the query string from a file in order to query the database using ExpressJS?

I am having trouble with this code snippet as it doesn't seem to be working properly. var content = fs.readFileSync('/home/diegonode/Desktop/ExpressCart-master/views/partials2/menu8xz.hbs', 'utf8' ); req.db.products.find( co ...

Issue with Mootools Ajax call and form submission

I'm dealing with a table that displays data from a database. I'm trying to implement a way to (a) delete rows from the table and (b) edit the content of a row in real-time. Deleting rows is working perfectly, but editing the content is proving to ...

I am searching for a way to apply a conditional class to the chosen element in react, as the toggle method does not

I'm working on customizing a dropdown menu and I want to add a functionality where if a parent li menu has an arrow class before the ul element, then clicking on that parent li menu will add a class called showMenu only to that specific sub-menu. Her ...

Steps for modifying the CSS class of an <a> tag with Jquery/Javascript

I am attempting to dynamically change the class of a tab on the dashboard based on the selected page. In the dashboard, there are 3 tabs: <div> <ul class="menu"> <li class="MenuDashboard"><a href="#" >Dashboard</a&g ...

The error message java.lang.NumberFormatException: Unable to parse the input string: "2017-01-28 13:28:20" occurred

During the execution of my java project, I encountered an error with a Gson deserializer function. The error message states: java.lang.NumberFormatException: For input string: "2017-01-28 13:28:20" at java.lang.NumberFormatException.forInputString(NumberF ...

How can I attach a click event to the left border of a div using jQuery?

I am wondering about a div element <div id="preview"> </div> Can anyone suggest a method to attach a click event specifically to the left border of this div? Your help is greatly appreciated. ...

React component rendering twice due to width awareness

In a React component that I've developed, I have utilized ResizeObserver to track its own width. Within this component, two divs are rendered with each having a "flex: 1" property to ensure equal width distribution. Under certain conditions, such as w ...

Button activated on second click

As I am working on a project, I encountered an issue with two buttons and one input field. The input field is supposed to take the value of the clicked button, but currently, the function works only after the second click on the button. I have tried using ...

"Error message pops up indicating the dispatcher is missing while using npm link with a local project

Currently, I am working on a React component library that I want to integrate into a local project for testing purposes. My initial approach was to use npm link to connect the component library with my local project. However, during this process, I encount ...

Transferring data to a child component through Route parameters

Although I have come across numerous questions and answers related to my query, I still seem unable to implement the solutions correctly. Every time I try, I end up with an 'undefined' error in my props. Let's take a look at my parent compo ...

Error encountered when attempting to send a JSON request using an Android application

Attempting to send a JSON Post request through my Android Application. Encountering some strange behavior. Below is the Android Code snippet: try { URL url = new URL(BASE_URL + params[0]); HttpURLConnection connection = (HttpURLConnection ...

Displaying Indonesian rupiah prices in jQuery using JSON data format

Here is some JSON data: {"grand_total":"1.200.000"} I need to display this JSON in $("jumlah").val(data.grand_total); Any suggestions on how to solve this? Thanks! ...

Attempting to prevent the use of the <p> tag solely before the text

My toggle function is not working correctly in my FaQ section. When a user clicks on a topic, the bottom section should appear, but the <p> tag is being displayed across the entire line instead of just one word.. Here is an image to help illustrate ...

"An unforeseen error occurred with the JSON data, there was an

I've been encountering a persistent error that I can't seem to troubleshoot. My goal is to extract data from a database and showcase it on a website, but I'm facing obstacles in achieving this. xmlhttp.onreadystatechange = function () { ...

Transferring String data between Java and JavaScript using Webview in both directions

I'm currently developing an application that allows two users to communicate via a webview. My goal is to transfer a String variable from JavaScript to Java in order to store it in my SQLite database, and also be able to do the reverse operation as we ...

Creating an asynchronous function in Node.js that returns a promise, but experiencing unexpected behavior when using console.log to display the result

Recently, I created a simple and compact API that determines the gender of a person. It functions by sending a get-request to a specific page which responds with a JSON object. This snippet illustrates how my module works: 'use strict'; const ht ...

Tips for arranging years in descending order in the material-ui Date Picker's calendar interface

This is the Code I Used - import "./styles.css"; import { DatePicker } from "@mui/x-date-pickers"; import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider"; import { AdapterDateFns } from "@mui/x-da ...

Increasing the identifier of duplicated input fields using jQuery

There is a specific section in my form that consists of a select box and three checkboxes, which needs to be duplicated on request. While I have successfully cloned the div and incremented its specific div, I am facing challenges in incrementing the checkb ...