How to calculate distance between two locations using their lat and long value and find the locations between those two point

Viewed 54

fun getNewLatLongs(Double latitude, Double longitude,Float distance) Pair<Double, Double> {

    double earth = 6378.137; // radius of earth in kms
    double pi = Math.PI;
    double m = 1 / (2 * pi / 360 * earth) / 1000; //1 meter in degree

    double newLatitude = ("%.4f".format(latitude + distance * m)).toDouble();

    val newLongitude =
            ("%.4f".format(longitude + distance * m / kotlin.math.cos(latitude * (pi / 180)))).toDouble();

    return Pair(newLatitude, newLongitude);
}
2 Answers

You can easily get distance between two latitude and longitude using the below method

private double distance(double lat1, double lon1, double lat2, double lon2) {
    double theta = lon1 - lon2;
    double dist = Math.sin(deg2rad(lat1)) 
                    * Math.sin(deg2rad(lat2))
                    + Math.cos(deg2rad(lat1))
                    * Math.cos(deg2rad(lat2))
                    * Math.cos(deg2rad(theta));
    dist = Math.acos(dist);
    dist = rad2deg(dist);
    dist = dist * 60 * 1.1515;
    return (dist);
}

private double deg2rad(double deg) {
    return (deg * Math.PI / 180.0);
}

private double rad2deg(double rad) {
    return (rad * 180.0 / Math.PI);
}

You can get a middle point between two locations using the below method

 private fun getCenterPointOfGivenLocation(startLatLng:LatLng , destinationLatLng:LatLng) :LatLng{
        return LatLngBounds.builder().include(startLatLng).include(destinationLatLng).build().center
    }

Try this

fun getDistanceBetween(
    destinationLatitude: Double,
    destinationLongitude: Double,
    latitude: Double,
    longitude: Double
): Int {
    val locationA = Location("point A")
    locationA.latitude = destinationLatitude
    locationA.longitude = destinationLongitude
    val locationB = Location("point B")
    locationB.latitude = latitude
    locationB.longitude = longitude
    val distance = locationA.distanceTo(locationB)
    return distance.toInt()
}
Related