-5

I have data set with shops Latitude and Longitude, how do i find shops in 100 meter range from my current location(latitude,longitude)?

Juned Ansari
  • 5,035
  • 7
  • 56
  • 89
  • your question is incomplete. do you want to calculate the distance between 2 points and as answered by jo_va or it is something like google map distance(road distance from one shop too another)? are you fetching latitude and longitude from database? – Sayed Mohd Ali Mar 05 '19 at 10:58
  • Possible duplicate of [Calculate distance between two latitude-longitude points? (Haversine formula)](https://stackoverflow.com/questions/27928/calculate-distance-between-two-latitude-longitude-points-haversine-formula) – Sayed Mohd Ali Mar 05 '19 at 11:04

1 Answers1

3

Use the Haversine formula for that.

function distance(coords1, coords2) {
  const { lat: lat1, lon: lon1 } = coords1;
  const { lat: lat2, lon: lon2 } = coords2;
  const degToRad = x => x * Math.PI / 180;
  const R = 6371;
  const halfDLat = degToRad(lat2 - lat1) / 2;  
  const halfDLon = degToRad(lon2 - lon1) / 2;  
  const a = Math.sin(halfDLat) * Math.sin(halfDLat) + 
            Math.cos(degToRad(lat1)) * Math.cos(degToRad(lat2)) * 
            Math.sin(halfDLon) * Math.sin(halfDLon);  
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); 
  return R * c; 
}

const paris = { lat: 48.864716, lon: 2.349014 };
const newYork = { lat: 40.730610, lon: -73.935242 };

console.log(distance(paris, newYork), 'km');

Then you simply need to iterate over your shops, calculate their distance to your location with the above function and only keep those whose distance is less than 100 meters.

I don't know how your data is structured, but if your shops are in an array, you could use filter:

const shopsNearMe =
    shopLocations.filter(shop => distance(shop.coords, myLocation) <= 0.1);
jo_va
  • 13,504
  • 3
  • 23
  • 47