The distance between two lat and long

I want to calculate and give the distance between the two Lat and Long sets for traveling on the road.

I looked at the Google Directions and Distance Matrix APIs. And also made many other questions about SO.

But I can’t find the best way to do this, you need to calculate the distance to about 20-25 places at any given time.

We are creating a travel application that requires this information for the user on the Android device where he is.

+6
source share
3 answers

If you are looking for a distance at a distance not the shortest distance, you can try to call the API service using a URL, for example:

http://maps.googleapis.com/maps/api/distancematrix/json?origins=54.406505,18.67708&destinations=54.446251,18.570993&mode=driving&language=en-EN&sensor=false 

As a result, JSON will look like this:

 { "destination_addresses" : [ "Powstańców Warszawy 8, Sopot, Polska" ], "origin_addresses" : [ "majora Henryka Sucharskiego 69, Gdańsk, Polska" ], "rows" : [ { "elements" : [ { "distance" : { "text" : "24,7 km", "value" : 24653 }, "duration" : { "text" : "34 min", "value" : 2062 }, "status" : "OK" } ] } ], "status" : "OK" } 

The distance to the actual distance between two points.

You can find more information in the Google Distance Matrix API

+13
source

It gives the distance between two locations.

First you need to get the latitude, longitude of the source and the same for the destination. Pass them in this method.

He returns you the distance between them.

 public float distanceFrom(float lat1, float lng1, float lat2, float 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 new Float(dist * meterConversion).floatValue(); } 
+6
source

You might want to search a little more before asking.

In any case, use the Haversin formula

 rad = function(x) {return x*Math.PI/180;} distHaversine = function(p1, p2) { var R = 6371; // earth mean radius in km var dLat = rad(p2.lat() - p1.lat()); var dLong = rad(p2.lng() - p1.lng()); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong/2) * Math.sin(dLong/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var dist = R * c; return dist.toFixed(3); } 
+5
source

All Articles