i need to get distance between two location, but i need to get distance like blue line in the picture.
Use the Google Maps Directions API. You'll need to request the directions over HTTP. You can do this directly from Android, or via your own server.
For example, directions from Montreal to Toronto:
GET http://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&sensor=false
You'll end up with some JSON. In routes[].legs[].distance
, you'll get an object like this:
"legs" : [
{
"distance" : {
"text" : "542 km",
"value" : 542389
},
You can also get the polyline information directly from the response object.
private String getDistance(double lat2, double lon2){
Location loc1 = new Location("A");
loc1.setLatitude("A1");
loc1.setLongitude("B1");
Location loc2 = new Location("B");
loc2.setLatitude(lat2);
loc2.setLongitude(lon2);
float distanceInMeters = loc1.distanceTo(loc2);
float mile = distanceInMeters / 1609.34f;
String sm = String.format("%.2f", mile);
return sm;
}
Try this:
private double calculateDistance(double fromLong, double fromLat,
double toLong, double toLat) {
double d2r = Math.PI / 180;
double dLong = (toLong - fromLong) * d2r;
double dLat = (toLat - fromLat) * d2r;
double a = Math.pow(Math.sin(dLat / 2.0), 2) + Math.cos(fromLat * d2r)
* Math.cos(toLat * d2r) * Math.pow(Math.sin(dLong / 2.0), 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double d = 6367000 * c;
return Math.round(d);
}
Hope this helps.
public String getDistance(final double lat1, final double lon1, final double lat2, final double lon2){
String parsedDistance;
String response;
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL("http://maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric&mode=driving");
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
InputStream in = new BufferedInputStream(conn.getInputStream());
response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONArray legs = routes.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONObject distance = steps.getJSONObject("distance");
parsedDistance=distance.getString("text");
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return parsedDistance;
}