0

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?

dinesh sharma
  • 3,312
  • 1
  • 22
  • 32
sarath
  • 3,181
  • 7
  • 36
  • 58

3 Answers3

1

pseudo code :


location.distanceTo(locFromServer);
and for the sorting  
Colection.sort(listOfLocations;new Comparator(){
compareTo(){
// location.distanceTo(locFromServer) 
}
}
sherif
  • 2,282
  • 19
  • 21
  • location means my geolocation object ..right???.....locFromServer means the geolocation i have to create from server ide latitude and longitude..right??? – sarath May 16 '12 at 11:01
  • yes the same type as the one provided from the location service I cant test the code now but you can probably create a Location object with a specific latitude/longtitude or set it later – sherif May 16 '12 at 16:24
1

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.

Community
  • 1
  • 1
Tony the Pony
  • 40,327
  • 71
  • 187
  • 281
1

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;
    }
Hades
  • 3,916
  • 3
  • 34
  • 74