Android: How to get Address from geolocation using Geocoder

来源:互联网 发布:传智播客全套java云盘 编辑:程序博客网 时间:2024/04/28 17:44

Class: HttpRetriever

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
publicclass HttpRetriever {
    privateDefaultHttpClient client = newDefaultHttpClient();
 
    publicString retrieve(String url) {
        HttpGet getRequest =new HttpGet(url);
        try{
            HttpResponse getResponse = client.execute(getRequest);
            finalint statusCode = getResponse.getStatusLine().getStatusCode();
            if(statusCode != HttpStatus.SC_OK) {
                Log.w(getClass().getSimpleName(),"Error " + statusCode
                        +" for URL " + url);
                returnnull;
            }
            HttpEntity getResponseEntity = getResponse.getEntity();
 
            if(getResponseEntity != null) {
                returnEntityUtils.toString(getResponseEntity);
            }
        }catch (IOException e) {
            getRequest.abort();
            Log.w(getClass().getSimpleName(),"Error for URL " + url, e);
        }
        returnnull;
 
    }
}

Method: getAddressFromGPSData

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
publicstatic final String GOOGLE_GEOCODER = "http://maps.googleapis.com/maps/api/geocode/json?latlng=";
 
publicstatic String getAddressFromGPSData(doublelat, doublelongi) {
        HttpRetriever agent =new HttpRetriever();
        String request = GOOGLE_GEOCODER + lat +","
                + longi +"&sensor=true";
        // Log.d("GeoCoder", request);
        String response = agent.retrieve(request);
        String formattedAddress ="";
        if(response != null) {
            Log.d("GeoCoder", response);
            try{
                JSONObject parentObject =new JSONObject(response);
                JSONArray arrayOfAddressResults = parentObject
                        .getJSONArray("results");
                JSONObject addressItem = arrayOfAddressResults.getJSONObject(0);
                formattedAddress = addressItem.getString("formatted_address");
            }catch (JSONException e) {
 
                e.printStackTrace();
            }
 
        }
 
        // Log.d("GeoCoder", response);
        returnformattedAddress;
    }
0 0