反向地理编码JSON结构解析

时间:2014-07-13 13:08:21

标签: android google-geocoder reverse-geocoding

早些时候我要求获取特定坐标的地址。现在我想解析可以通过URL https://maps.google.com/maps/api/geocode /json?latlng=48.906233407932675,2.433183006942272接收的JSON结构 我使用了以下代码,但这会导致我的应用程序崩溃。

public void parseJSONLocation(LatLng point)
{
    Toast.makeText(getApplicationContext(), "Test", Toast.LENGTH_LONG).show();
    double lat = point.latitude;
    double lng = point.longitude;

    JSONObject ret = getJSONLocationInfo(lat, lng);
    JSONObject location;
    String location_string = "";

    try {

        //Get JSON Array called "results" and then get the 0th complete object as JSON        
        location = ret.getJSONArray("results").getJSONObject(0); 
        // Get the value of the attribute whose name is "formatted_string"
        location_string = location.getString("formatted_address");
        //Toast.makeText(getApplicationContext(), "formattted address:" + location_string, Toast.LENGTH_LONG).show();
    } catch (JSONException e1) {
        e1.printStackTrace();

    }
}

public JSONObject getJSONLocationInfo(double lat, double lng)
{
    HttpGet httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lng + "&key=AIzaSyB3hYTOGwj2FM9rSCYxTag1VkJXpFRmkOc");
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    StringBuilder stringBuilder = new StringBuilder();

    try {
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
        } catch (IOException e) {
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return jsonObject;
}

有没有人有想法解决这个问题?

0 个答案:

没有答案