Android: How to get Address from geolocation using Geocoder

本文介绍了一个基于HTTP协议的数据获取类,用于从Google API获取GPS数据的地理位置信息,并详细解释了其实现过程和关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
public class HttpRetriever {
     private DefaultHttpClient client = new DefaultHttpClient();
 
     public String retrieve(String url) {
         HttpGet getRequest = new HttpGet(url);
         try {
             HttpResponse getResponse = client.execute(getRequest);
             final int statusCode = getResponse.getStatusLine().getStatusCode();
             if (statusCode != HttpStatus.SC_OK) {
                 Log.w(getClass().getSimpleName(), "Error " + statusCode
                         + " for URL " + url);
                 return null ;
             }
             HttpEntity getResponseEntity = getResponse.getEntity();
 
             if (getResponseEntity != null ) {
                 return EntityUtils.toString(getResponseEntity);
             }
         } catch (IOException e) {
             getRequest.abort();
             Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
         }
         return null ;
 
     }
}

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
public static final String GOOGLE_GEOCODER = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" ;
 
public static String getAddressFromGPSData( double lat, double longi) {
         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);
         return formattedAddress;
     }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值