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

Attempting to execute npm install for an Odin project task, encountered the error "Module not Found". // A new error has surfaced, continue reading below

Trying to run npm install for the Odin Project JavaScript Fundamentals Part 4 lesson has been quite a challenge. Initially, upon forking and cloning the repository and running npm install as per the instructions, I encountered a permission error. However, ...

Utilize the power of React and Framer Motion to create a visually stunning fade

After creating a preloader that appears when the variable "loading" is set to true, I now want the loader to fade out. This is an overview of my files: On the home page with all the content: return ( <> {loading ? ( ...

Is it optimal to have nested promises for an asynchronous file read operation within a for loop in Node.js?

The following Node.js function requires: an object named shop containing a regular expression an array of filenames This function reads each csv file listed in the array, tests a cell in the first row with the provided regular expression, and returns a n ...

"ModuleNotFound" error occurred when attempting to utilize Netlify lambda functions with external dependencies

https://i.stack.imgur.com/vVmky.jpg I'm currently exploring the capabilities of Netlify, specifically its lambda function feature for running a node function with dependencies. Following a tutorial from CSS-Tricks, my functions/submission-created.js ...

Lamenting the Perils of Losing AngularJS Rootscope Data upon Refresh

Currently, I am facing an issue in AngularJS 1.x. When I save a value in the $rootScope and pass to the next page or router, unfortunately, the $rootScope value gets lost upon refreshing the page (F5/Window Reload). I need a solution that doesn't inv ...

Steps for including a map in a property file for JavaScript parsing

When a checkbox is clicked, a new series of checkboxes will be displayed. The details for these checkboxes are fetched from a database. However, I now need to have certain checkboxes pre-checked based on the user's selection. Since I can't store ...

Leveraging Angular2's observable stream in combination with *ngFor

Below is the code snippet I am working with: objs = [] getObjs() { let counter = 0 this.myService.getObjs() .map((obj) => { counter = counter > 5 ? 0 : counter; obj.col = counter; counter++; return view ...

React Component is not functioning with the timer running

I am currently developing a basic timer app using React. Here is the code snippet I have so far: import React from "react" const timer = (props) => { let time = 25; let processStatus = props.timerProcessStatus; // set to true if(processSta ...

The addition of an asynchronous call caused Array.map to start experiencing errors

I am working on a React component that iterates through an array of messages and renders JSX based on certain conditions: messages.map(async (msg) => { let previewImage: URL | undefined = undefined; if (msg.mediaId) { previewImage = await stora ...

Issue: React build script does not support conversion from 'BigInt' to 'number' error

After developing the UI using create-react-app, I encountered an issue. The UI works fine with the normal npm start command, but when I try to build it with npm run build, I get an error saying 'Conversion from 'BigInt' to 'number' ...

The conditional statement for ajax is malfunctioning

I am encountering an issue with some ajax coding. The if condition is not working as expected - whenever the program runs, only the else statement gets executed even when the if statement should be satisfied. <script type="text/javascript> funct ...

Forward user to a subdomain once they have successfully logged in on an Angular 2 application

I've been working on an Angular 2 application and I'm looking to redirect users from www.example.com to admin.example.com after they successfully log in. What is the best way to accomplish this using Angular 2? Additionally, how can I test this f ...

What is the procedure for utilizing the comparator to arrange items according to various attributes?

I am trying to find a way to arrange my models in a collection based on their required flag and then alphabetically by their value. This is what my current code looks like: var myModel = Backbone.Model.extend({ defaults: { required: true, ...

What is the best way to retrieve information from a database using JSON with PHP, JQUERY, and

Trying to retrieve data from a MySQL database and pass it to a JavaScript file has been quite a challenge. Despite searching extensively online, the examples I found didn't work in my specific scenario. .html file <!DOCTYPE html PUBLIC '-//W ...

Sorting through names within a nested array based on specific criteria

I have been struggling to filter by item name for the past day and haven't been successful. The issue lies in my attempt to use a sample array for filtering. While I am able to filter by category successfully, the same cannot be said for filtering by ...

Retrieving device information through JavaScript, jQuery, or PHP

Looking to build a website that can identify the device name and model of visitors accessing the page from their devices. ...

The decision will be dependent on the outcomes provided by the $resource promise

I have been working on calling my API with AngularJS to retrieve a list of 'reports' and then displaying them in a modal or saving the sale depending on whether any results were returned. I've been struggling with this for a while and would ...

Store the output of JavaScript in a PHP variable

My objective is to convert any image to base 64 and then store the converted string in a PHP variable before inserting it into my database. JavaScript Code: function uploadFile() { if (this.files && this.files[0]) { var FR= new FileReader ...

Cannot utilize the subscribed output value within the filter function

I am in need of assistance with my Angular 7 project. I have successfully implemented a service to call a Json file and output an object array. However, I am facing an issue when trying to filter the objects in the array based on a specific property called ...

Utilizing Ajax to fetch a div element from a web page

Hey there! I have a link set up that loads a page into a specific div ID, which is #ey_4col3. The issue I'm facing is that it loads the entire page along with all its contents, but what I really want to load from that page is just the content within ...