I need to calculate distance between two points on google map given their latitude and longitude. Because of some reason my code is not working. Please let know if anything wrong with it.My project is Google maps distance matrix enabled. Below is my program....
public double distance(double lat, double lng, double glat, double glng)
{
URL a = null;
try {
a = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins="+lat+","+lng+"&destinations="+glat+","+glng+"&mode=driving&key=mykey&sensor=true");
} catch (MalformedURLException e) {
e.printStackTrace();}HttpURLConnection c1 = null;
try {
c1 = (HttpURLConnection) a.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
c1.setRequestMethod("GET");
} catch (ProtocolException e) {
e.printStackTrace();
}
try {
c1.connect();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(c1.getInputStream()));
StringBuilder sb = new StringBuilder();
String s, s1 = "";
while ((s = br.readLine()) != null) {
sb.append(s1);
}
String jsonStr = sb.toString();
Log.d("demo",jsonStr+"here");
String d=parseJSON(jsonStr);
}catch (IOException e) {
e.printStackTrace();
}
// System.out.println(s1);
return (Double.parseDouble(d));
}
private String parseJSON(String s) {
//String d="";
try {
JSONObject ob=new JSONObject(s);
Log.d("demo","ob\t"+ob.toString());
JSONArray jarray=ob.getJSONArray("destination_address");
d=ob.getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0).getJSONObject("distance").get("value").toString();
} catch (JSONException e) {
e.printStackTrace();
}
return d;
}