Mohsen Mohseni Mohsen Mohseni - 1 month ago 8
Android Question

find closest marker to my current location

I have an arrayList of markers and I want to find the closest marker to my current location.
I had no idea how to find that marker so I searched and found same problem in here.

Google Maps Api v3 - find nearest markers

then I tried to convert those code to java but it doesn't work now.

closest
doesn't change and always it is -1.

Is there any better solution for this problem or I can make the following code usable?

public void findNearMarker(){

double pi = Math.PI;
int R = 6371; //equatorial radius
double[] distances = new double[2];
double d = 0;
int i;
int closest = -1;

for ( i = 0; i == markerArrayList.size(); i++){

double lat2 = markerArrayList.get(i).getPosition().latitude;
double lon2 = markerArrayList.get(i).getPosition().longitude;

double chLat = lat2 - currentLocation.getLatitude();
double chLon = lon2 - currentLocation.getLongitude();

double dLat = chLat*(pi/180);
double dLon = chLon*(pi/180);

double rLat1 = currentLocation.getLatitude()*(pi/180);
double rLat2 = lat2 * (pi/180);

double a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2)
* Math.sin(dLon /2) * Math.cos(rLat1) * Math.cos(rLat2);

double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

d = R * c;

distances[i] = d;
if (closest == -1 || d< distances[closest]){
closest = i;
}
}

}

Answer

first you need to import the location class of the android sdk

import android.location.Location;


 ArrayList<Marker> markers = new ArrayList<>();
markers = sortListbyDistance(markers, currentLocation.getLocation());


 public static ArrayList<Marker> sortListbyDistance(ArrayList<Marker> radars, final LatLng location){
        Collections.sort(markers, new Comparator<Marker>() {
            @Override
            public int compare(Marker marker2, Marker marker1) {
            //
                if(getDistanceBetweenPoints(marker1.getLocation(),location)>getDistanceBetweenPoints(marker2.getLocation(),location)){
                    return -1;
                } else {
                    return 1;
                }
            }
        });
        return markers;
    }


 public static float getDistanceBetweenPoints(double firstLatitude, double firstLongitude, double secondLatitude, double secondLongitude) {
        float[] results = new float[1];
        Location.distanceBetween(firstLatitude, firstLongitude, secondLatitude, secondLongitude, results);
        return results[0];
    }

and to get the nearest marker just get first item in markers, cheers :)