Android中使用Geocoding API

第一步:構造Geocoder API 需要的URL
URL格式
https://maps.googleapis.com/maps/api/geocode/output?parameters
其中output有兩個選項json/xml,parameters部分有address/language/sensor等多個選項
URL示例
https://maps.googleapis.com/maps/api/geocode/json?address=北京天安門&language=zh_CN&sensor=false
第二步:向API發送Http請求,返回一個json字符串
[java]
String uriAPI = "https://maps.googleapis.com/maps/api/geocode/json?address=%s&language=%s&sensor=%s"; 
                //構造Geocoder API的完整URL 
                String url = String.format(uriAPI, addr,"zh_CN","false"); 
                //創建request對象 
                HttpGet request = new HttpGet(url); 
                //創建HttpClient對象 
                HttpClient client = new DefaultHttpClient(); 
                //得到請求響應對象 
                HttpResponse response = client.execute(request); 
                //若狀態碼為200,說明請求成功 
                if(response.getStatusLine().getStatusCode()==200){ 
                    //獲得響應條目–該條目是json字符串 
                    String resultStr = EntityUtils.toString(response.getEntity()); 
                    geoPoint=parseJson(resultStr); 
                } 

第三步:解析json字符串
[java]
//解析根元素,得到一個數組 
            JSONArray jsonObjs = new JSONObject(str).getJSONArray("results"); 
            //取出數組中第一個json對象(本示例數組中實際隻包含一個元素) 
            JSONObject jsonObj = jsonObjs.getJSONObject(0); 
            //解析得formatted_address值 
            String address = jsonObj.getString("formatted_address"); 
            //解析得json對象中的geometry對象 
            JSONObject geometry = jsonObj.getJSONObject("geometry"); 
            //解析得geometry對象中的location對象 
            JSONObject location = geometry.getJSONObject("location"); 
            //解析得location對象中的latitude、longitude值 
            String lat = location.getString("lat"); 
            String lng = location.getString("lng"); 
            dLati = Double.parseDouble(lat); 
            dLong = Double.parseDouble(lng); 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *