How to calculate distance from different markers in a map and then pick up the least one

后端 未结 9 1033
野趣味
野趣味 2020-12-05 08:53

I have to get distance from different markers on the map to the current location of the device and the pick up the shortest one. I have the lat and long for the markers and

9条回答
  •  被撕碎了的回忆
    2020-12-05 09:27

    How about looping over all markers and checking the distance using Location.distanceBetween? There is no magic involved ;)

    List markers;
    LatLng currentPosition;
    
    float minDistance = Float.MAX_VALUE;
    Marker closest = null;
    float[] currentDistance = new float[1];
    for (Marker marker : markers) {
        LatLng markerPosition = marker.getPosition();
        Location.distanceBetween(currentPosition.latitude, currentPosition.longitude, markerPosition.latitude, markerPosition.longitude, currentDistance);
        if (minDistance > currentDistance[0]) {
            minDistance = currentDistance[0];
            closest = marker;
        }
    }
    

提交回复
热议问题