sarath
sarath

Reputation: 3201

find the nearest location among locations from our location

I am developing an Android application.

I am getting a list of latitudes and longitudes from the server.

I have to arrange those values based on my location. I mean the nearest latitude/longitude first and then the next one etc.

I have my latitude and longitude and the list of latitude and longitudes. How can I find the nearest one?

Upvotes: 0

Views: 569

Answers (3)

Hades
Hades

Reputation: 3936

This might not be the best way but it works :)

public static final double PI = 3.14159265;
    public static final double deg2radians = PI/180.0;
    public static final double miles = 0.000621371192;
    public static final double kms = 0.001;

    public static double getDistance(double latitude1, double longitude1, double latitude2,double longitude2) {

         double distance;  

         Location locationA = new Location("point A");  

         locationA.setLatitude(latitude1);  
         locationA.setLongitude(longitude1);  

         Location locationB = new Location("point B");  

         locationB.setLatitude(latitude2);  
         locationB.setLongitude(longitude2);  

         distance = locationA.distanceTo(locationB); 
         double radd = distance * kms;

         return radd;
    }

Upvotes: 1

Tony the Pony
Tony the Pony

Reputation: 41347

You can simply calculate the distances of the user's position to the downloaded locations, and select the smallest one.

Have a look here: Quicker way to calculate geographic distance between two points.

Upvotes: 1

sherif
sherif

Reputation: 2332

pseudo code :


location.distanceTo(locFromServer);
and for the sorting  
Colection.sort(listOfLocations;new Comparator(){
compareTo(){
// location.distanceTo(locFromServer) 
}
}

Upvotes: 1

Related Questions