-1

I'm working with meanstack application. so I have mongodb collection that contain worldwide locations. Schema loooks like follows.

[{
address : "example address",
langitude : 79.8816,
latitude : 6.773
},
{...}]

What is the efficient way to select all points inside Circle( pre defined point and pre defined radius) ..??

Using SQL Query also we can do this. But I want a efficient way without iterating one by one and check weather it is inside that radius or not.

Amith Dissanayaka
  • 939
  • 3
  • 12
  • 23
  • Possible duplicate of [MySQL select coordinates within range](https://stackoverflow.com/questions/21042418/mysql-select-coordinates-within-range) – MrUpsidown Feb 05 '19 at 13:04
  • @MrUpsidown Doing it by hand (in code or by SQL query) is very inefficient. That's why suggested using Elasticsearch. I think we should not point people in direction of inefficiency. – Divanshu Feb 05 '19 at 15:57
  • Yes @Divanshu Using SQL Query is very inefficient. Elasticsearch seems like efficient comparing that method. I referred some documents. – Amith Dissanayaka Feb 05 '19 at 17:33

1 Answers1

0

Distance d between two points with coordinates {lat1,lon1} and {lat2,lon2} is given by

d = 2*asin(sqrt((sin((lat1-lat2)/2))^2 +
    cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2))^2))

Above formula gives d in radians. To get the answer in km, use the formula below.

distance_km ≈ radius_km * distance_radians ≈ 6371 * d

Here, the magic number 6371 is approx. the radius of planet earth. This is the minimum computation that you will have to do in your case. You can compute this distance and select all the records having a distance less than your radius value.

Better approach

You can use Elasticsearch which supports geolocation queries for better performance.

Divanshu
  • 423
  • 3
  • 12
  • @Amith You will have to iterate if the center point from which you need to calculate the distance, keeps on changing. Otherwise, if the center point does not change or the list of centers is a small finite set then you can keep these distances pre-calculated. The best approach is to use Elasticsearch. – Divanshu Feb 05 '19 at 12:22
  • can we integrate mongodb elasticsearch with node backend ?? – Amith Dissanayaka Feb 05 '19 at 12:49
  • @Amith Elasticsearch is a search engine. You push data in JSON format into the Elasticsearch and it will index it for faster search queries. Then you make queries to the Elasticsearch. Elasticsearch provides REST APIs for doing all this. Yes, you can integrate Elasticsearch with Node. – Divanshu Feb 05 '19 at 12:53