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

后端 未结 9 1035
野趣味
野趣味 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:40

    Although there has already been posted some answer, I thought I would present my implementation in java. This has been used with 4000+ markers wrapped in an AsyncTask and has been working with no problems.

    First, the logic to calculate distance (assuming you only have the markers and not Location objects, as those gives the possibility to do loc1.distanceTo(loc2)):

    private float distBetween(LatLng pos1, LatLng pos2) {
        return distBetween(pos1.latitude, pos1.longitude, pos2.latitude,
                pos2.longitude);
    }
    
    /** distance in meters **/
    private float distBetween(double lat1, double lng1, double lat2, double lng2) {
        double earthRadius = 3958.75;
        double dLat = Math.toRadians(lat2 - lat1);
        double dLng = Math.toRadians(lng2 - lng1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
                + Math.cos(Math.toRadians(lat1))
                * Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2)
                * Math.sin(dLng / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double dist = earthRadius * c;
    
        int meterConversion = 1609;
    
        return (float) (dist * meterConversion);
    }
    

    Next, the code for selecting the nearest marker:

    private Marker getNearestMarker(List markers,
            LatLng origin) {
    
        Marker nearestMarker = null;
        double lowestDistance = Double.MAX_VALUE;
    
        if (markers != null) {
    
            for (Marker marker : markers) {
    
                double dist = distBetween(origin, marker.getPosition());
    
                if (dist < lowestDistance) {
                    nearestMarker = marker;
                    lowestDistance = dist;
                }
            }
        }
    
        return nearestMarker;
    }
    

    Perhaps not relevant for your use case but I use the algorithm to select the nearest markers based on a predefined distance. This way I weed out a lot of unnecessary markers:

    private List getSurroundingMarkers(List markers,
            LatLng origin, int maxDistanceMeters) {
        List surroundingMarkers = null;
    
        if (markers != null) {
            surroundingMarkers = new ArrayList();
            for (Marker marker : markers) {
    
                double dist = distBetween(origin, marker.getPosition());
    
                if (dist < maxDistanceMeters) {
                    surroundingMarkers.add(marker);
                }
            }
        }
    
        return surroundingMarkers;
    }
    

    Hope this helps you

提交回复
热议问题