使用谷歌距离矩阵api

时间:2018-03-16 16:17:56

标签: android google-maps google-api

考虑到纬度和经度,我需要计算谷歌地图上两点之间的距离。由于某些原因我的代码不起作用。请知道它是否有任何问题。我的项目是谷歌地图距离矩阵启用。以下是我的计划......

     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;
}

0 个答案:

没有答案