Android中使用Geocoding API

來源:互聯網
上載者:User

第一步:構造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 = "http://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); 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.