Issue
How to calculate distance between 2 location in android map & output must display in textview or any ?
Solution
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);
}
}
Answered By - Buddha_Peace
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.