public class GoogleMapDemo {java public static void main(String[] args) { getGoogleLatLng("廣州市天河區高普路"); String addr = getGoogleAddres(new BigDecimal(23.1716124),new BigDecimal(113.4106579)); System.err.println("addr---------------------------------"+addr);json } public static void getGoogleLatLng(String address) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { // 建立httpget. HttpGet httpget = new HttpGet("https://maps.google.com/maps/api/geocode/json?address="+address+"&sensor=false&key=AIzaSyA3a5PwotknVyiN7de6eSZkxkLLpd8hm6k"); // 執行get請求. CloseableHttpResponse response = httpclient.execute(httpget); try { // 獲取響應實體 HttpEntity entity = response.getEntity(); if (entity != null) { // 打印響應內容 String str = EntityUtils.toString(entity,"utf-8"); JSONObject o = (JSONObject) JSON.parse(str); JSONArray o2 = (JSONArray) o.get("results"); JSONObject o3 = (JSONObject) o2.get(0); JSONObject o4 = (JSONObject) o3.get("geometry"); JSONObject o5 = (JSONObject)o4.get("location"); //得到打印結果 System.err.println("lat====>>>"+o5.get("lat")+";lng=====>>>"+o5.get("lng")); } } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); System.err.println(e.getMessage()); }catch (IOException e) { e.printStackTrace(); System.err.println(e.getMessage()); } finally { httpclient.close(); } } //根據經度、緯度獲取地址詳細信息 public static String getGoogleAddres(BigDecimal lat, BigDecimal lng) { String addr = ""; if(null == lat || null == lng){ return addr; } CloseableHttpClient httpclient = HttpClients.createDefault(); try { // 建立httpget. ,參數還能夠換成英文的。 HttpGet httpget = new HttpGet(MessageFormat.format("https://maps.google.com/maps/api/geocode/json?latlng={0},{1}&sensor=false&&language=zh-CN&key=AIzaSyA3a5PwotknVyiN7de6eSZkxkLLpd8hm6k", lat, lng)); // 執行get請求. CloseableHttpResponse response = httpclient.execute(httpget); try { // 獲取響應實體 HttpEntity entity = response.getEntity(); if (entity != null) { // 打印響應內容 String str = EntityUtils.toString(entity); JSONObject o = (JSONObject) JSON.parse(str); JSONArray o1 = (JSONArray)o.get("results"); JSONObject o2 = (JSONObject)o1.get(0); if(null != o2){ addr = String.valueOf(o2.get("formatted_address")); } } } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpclient.close(); } return addr; } api |
說明:這是在java後臺還處理google map的相關功能,經過httpClient直接發請求,但這種方式可能性能比較卡,特別須要網絡的支持,通過測試在大陸測試時,常常出現不能鏈接問題,在相關跑一樣的代碼就一直正常。因此這種功能要看狀況使用。網絡