user4286621
user4286621

Reputation:

Calculate road distance between two longitudes and latitudes

I am trying to develop an android app. I have listed some places with their longitude/latitude and other descriptions in my backend(php MySQL). I am trying to grab users current location and show him the road distance to those listed places with their descriptions. But I am having difficulty finding road distances form current location to all other places. I guess one way to do this is by using Google Distance Matrix API But in this case there will be two API calls,

and after that my backend will send response to my device. Is it a good Idea to call two API for this purpose. And is there any other way to do it easily. I am new to development so please pardon me if I am wrong.

Thank You.

Upvotes: 1

Views: 1063

Answers (1)

Maycon Cardoso
Maycon Cardoso

Reputation: 179

public float distance(double lat1, double lng1, double lat2, double lng2) {
    double earthRadius = 6371; // kilometers
    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));
    float dist = (float) (earthRadius * c);

    return dist * 1000;
}

Now Call in your code

float distanceInMeters= distance(oldLatitude, oldLongitude,newLatitude, newLongitude);

Upvotes: 1

Related Questions