Search code examples
androidgeolocationlocationmanager

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?


Solution

  • 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;
        }