How to calculate distance between 2 location in android map & output must display in textview or any ?
For those people like me, who are learning now/late. Have made use of the code written by @NaserShaikh below. Here you go a working code to get driving distance on google map when u have lat,long of two points!! distance is in miles ! There are better way to parse the JSON response pls look for it. Havent tested it for extremes when there is a ocean btw and other stuffs. Hope it helps.
package havefun;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.JSONArray;
import org.json.JSONObject;
class Distance {
private Double dist;
public Distance() {
dist = (double) -1;
}
private Double getDistance(){
StringBuffer jsonString = new StringBuffer();
HttpPost httpPost = new HttpPost("http://maps.googleapis.com/maps/api/directions/json?origin=<src_lat>,<src_long>&destination=<dst_lat>,<dst_long>&sensor=false&mode=driving");
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
CloseableHttpResponse HttpResponse = httpClient.execute(httpPost);
InputStream in = HttpResponse.getEntity().getContent();
int ch = 0;
while ((ch = in.read()) != -1) {
jsonString.append((char) ch);
}
in.close();
JSONObject jsonObject = new JSONObject(jsonString.toString());
//System.out.println(jsonObject);
//System.out.println("========================");
//System.out.println(jsonObject.get("status"));
if (jsonObject.get("status").toString().equals("OK") == false) {
System.err.println("Error");
return dist;
}
String distance = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("distance").getString("text");
System.out.println(distance);
String temp[] = distance.split(" ");
System.out.println(temp[1]);
System.out.println(temp[0]);
dist = Double.parseDouble(temp[0]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dist;
}
public static void main(String[] args) {
Distance d = new Distance();
Double dist = d.getDistance();
System.out.println("Distance ="+dist);
}
}
/**
* Calculate the distance between 2 points based on their GeoPoint coordinates. <br>
* Return the value in Km or miles based on the unit input
* @param gp1 (GeoPoint): First point.
* @param gp2 (GeoPoint): Second point.
* @param unit (char): Unit of measurement: 'm' for miles and 'k' for Km.
* @return (double): The distance in miles or Km.
*/
public static double getDistance(GeoPoint gp1, GeoPoint gp2, char unit)
{
//Convert from degrees to radians
final double d2r = Math.PI / 180.0;
//Change lat and lon from GeoPoint E6 format
final double lat1 = gp1.getLatitudeE6() / 1E6;
final double lat2 = gp2.getLatitudeE6() / 1E6;
final double lon1 = gp1.getLongitudeE6() / 1E6;
final double lon2 = gp2.getLongitudeE6() / 1E6;
//The difference between latitudes and longitudes
double dLat = Math.abs(lat1 - lat2) * d2r;
double dLon = Math.abs(lon1 - lon2) * d2r;
double a = Math.pow(Math.sin(dLat / 2.0), 2)
+ Math.cos(lat1 * d2r) * Math.cos(lat2 * d2r)
* Math.pow(Math.sin(dLon / 2.0), 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
//Return the distance
return (unit == 'm' ? 3956 : 6367) * c;
} //End getDistance()
TextView textView.setText("" + getDistance(gp1, gp2, 'k'));
textView.setText(""+location1.distanceTo(location2));
i think you need googleapi for that, i had use such service before.. you can get distance from your current location to destination.
simply uee following url:
http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=false&mode=driving
here, origin=%f,%f = origin=latitude,longitude destination=%f,%f = destination=latitude,longitude
google response:
{
"routes": [
{
"bounds": {
"northeast": { … },
"southwest": { … }
},
"copyrights": "Map data ©2012 Inav/Geosistemas SRL",
"legs": [
{
"distance": {
"text": "1 m",
"value": 0
},
"duration": { … },
"end_address": "Formosa Province, Argentina",
"end_location": { … },
"start_address": "Formosa Province, Argentina",
"start_location": { … },
"steps": [ … ],
"via_waypoint": [ ]
}
],
"overview_polyline": { … },
"summary": "RP 3",
"warnings": [ ],
"waypoint_order": [ ]
}
],
"status": "OK"
}
Above u can see
"distance": {
"text": "1 m",
"value": 0
},
there is your distance:
code may look like this:
private void getDistance(){
StringBuffer jsonString = new StringBuffer();
httpPost = new HttpPost("http://maps.googleapis.com/maps/api/directions/json?origin=<latitude>,<longitude>&destination=<latitude>,<longitude>&sensor=false&mode=driving");
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
httpResponse = httpClient.execute(httpPost);
InputStream in = httpResponse.getEntity().getContent();
int ch = 0;
while ((ch = in.read()) != -1) {
jsonString.append((char) ch);
}
in.close();
JSONObject jsonObject = new JSONObject(jsonString.toString());
JSONArray jsonArray = jsonObject.getJSONArray(""legs");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObj = jsonArray.getJSONObject(i);
String text = jObj.getString("text");
String value = jObj.getString("value");//value is ur distance
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
hope it help.