0

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;
}
  • 1
    Is it fair to assume the 'mykey' was replaced with your actual key in your testing? If so, then provide what evidence of "not working" such as the stack trace output. –  Mar 16 '18 at 16:41
  • Yes, the word "my key" is replaced with actual key value. The URL works fine when I post it on web but the program is showing android.os.NetworkOnMainThreadException .I have already included – user9442119 Mar 16 '18 at 18:34
  • I have already included in the manifest file – user9442119 Mar 16 '18 at 18:35
  • 2
    See accepted answer: https://stackoverflow.com/questions/6343166/how-do-i-fix-android-os-networkonmainthreadexception –  Mar 16 '18 at 18:36

0 Answers0