Search code examples
swiftfirebasefirebase-realtime-databasecore-locationcoordinate

Filter only nearest locations from DB


I have a Firebase Database where user is updating his locations (lattitude and longitude) when he is using app. In the same time the user see all locations of others users which are udating their locations the same way.

I want to display all locations of users which are in X distance from user. Is there any alghoritm or something to filter that? Right now user will see all locations event if he is in US, he can see locations of active users from France.

I'm using MapKit and CoreLocation


Solution

  • You can use the distance on a CLLocation object, and print out the ones that are within your desired distance.

    Something like this:

    let userLocation = CLLocation(latitude: userLat, longitude: userLong)
    let anotherLocation = CLLocation(latitude: anotherLat, longitude: anotherLong)
    let distance = anotherLocation.distance(from: userLocation)
    
    if distance < desiredDistance {
         // within range
    }