Get the distance between two geo points

后端 未结 9 567
旧巷少年郎
旧巷少年郎 2020-11-27 09:11

I want to make an app which checks the nearest place where a user is. I can easily get the location of the user and I have already a list of places with latitude and longitu

相关标签:
9条回答
  • 2020-11-27 10:07

    http://developer.android.com/reference/android/location/Location.html

    Look into distanceTo or distanceBetween. You can create a Location object from a latitude and longitude:

    Location location = new Location("");
    location.setLatitude(lat);
    location.setLongitude(lon);
    
    0 讨论(0)
  • 2020-11-27 10:09
    Location loc1 = new Location("");
    loc1.setLatitude(lat1);
    loc1.setLongitude(lon1);
    
    Location loc2 = new Location("");
    loc2.setLatitude(lat2);
    loc2.setLongitude(lon2);
    
    float distanceInMeters = loc1.distanceTo(loc2);
    

    Reference: http://developer.android.com/reference/android/location/Location.html#distanceTo(android.location.Location)

    0 讨论(0)
  • 2020-11-27 10:11

    Just use the following method, pass it lat and long and get distance in meter:

    private static double distance_in_meter(final double lat1, final double lon1, final double lat2, final double lon2) {
        double R = 6371000f; // Radius of the earth in m
        double dLat = (lat1 - lat2) * Math.PI / 180f;
        double dLon = (lon1 - lon2) * Math.PI / 180f;
        double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.cos(latlong1.latitude * Math.PI / 180f) * Math.cos(latlong2.latitude * Math.PI / 180f) *
                        Math.sin(dLon/2) * Math.sin(dLon/2);
        double c = 2f * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        double d = R * c;
        return d;
    }
    
    0 讨论(0)
提交回复
热议问题