zoukankan      html  css  js  c++  java
  • 【Android】通过经纬度查询城市信息

    public class GetCity {
        public static String STATIC_URL = "http://api.map.baidu.com/geocoder/v2/?ak=你的Key&location=";
    
        public static String getJson(double lat, double log) {
            StringBuilder builder = new StringBuilder();
            InputStreamReader in = null;
            BufferedReader buff = null;
            if(lat != 0 && log != 0) {
                String newUrl = STATIC_URL + lat + "," + log + "&output=json";
                try {
                    URL url = new URL(newUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(1000);
                    in = new InputStreamReader(conn.getInputStream(),
                            "utf-8");
                    buff = new BufferedReader(in);
                    String inputLine = null;
                    if(conn.getResponseCode() == 200) {
                        while ((inputLine = buff.readLine()) != null) {
                            builder.append(inputLine);
                        }
                    }
                }catch (MalformedURLException e) {
                    e.printStackTrace();
                }catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        if(buff != null) {
                            buff.close();
                        }if (in != null) {
                            in.close();
                        }
    
                    }catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return builder.toString();
        }
    
        public static String getCity(double lat, double log) {
            String json = getJson(lat, log);
            Gson gson = new Gson();
            Map jo = gson.fromJson(json, Map.class);
            Map result = (Map) jo.get("result");
            Map addressComponent = (Map) result.get("addressComponent");
            return (String) addressComponent.get("city");
        }
    }

    这里只需要把STATIC_URL中的key换成你在百度地图API中申请到的key就可以了,每次直接调用getCity(lat, log)就可以返回城市的名称啦!

  • 相关阅读:
    查看python关键字
    命令终端执行python
    Codeforces-462C. A Twisty Movement
    Codeforces-462A. A Compatible Pair
    Codeforces-446C. Pride
    Codeforces-Hello 2018C. Party Lemonade(贪心)
    Codeforces-33C. Wonderful Randomized Sum
    Codeforces-118D. Caesar's Legions(lazy dynamics)
    codeforces-73C. LionAge II
    Gym 101510C-Computer Science
  • 原文地址:https://www.cnblogs.com/puyangsky/p/5035597.html
Copyright © 2011-2022 走看看