根据经纬度获取对应的城市名(内部封装了工具类,直接拿来用即可,傻瓜式操作)

本文分享了一个内部封装好的Java工具类,能够简单易用地根据经纬度查询到对应的城市名称,实现傻瓜式操作。适用于需要地理位置信息处理的场景。
			double latitude = co.getLatitude();     //纬度
            double longitude = co.getLongitude();   //经度
            String city = null;
            try {
                city = LocationUtils.getCity(latitude, longitude);
                serviceItemDao.insertData(s,city);
            } catch (IOException e) {
                e.printStackTrace();
            }

封装的工具类

public class LocationUtils {
    public static String getCity(double lat, double lng) throws IOException {
        JSONObject jsonObject = getLocationInfo(lat, lng).getJSONObject("result").getJSONObject("addressComponent");
        String city = jsonObject.getString("city");
        String s = jsonObject.toString();
       // System.out.println(city);
        return city;
    }
    public static JSONObject getLocationInfo(double lat, double lng) throws IOException {
        String urlString = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=0HRZaqhUGXeSzxMYZQF1xvdhvl8XRUby&output=json&coordtype=wgs84ll&location="+lat+","+lng;
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
        String line;
        String res = "";
        while((line = in.readLine())!= null) {
            res += line+"\n";
        }
        in.close();
        JSONObject jsonObject = JSONObject.parseObject(res);
        return jsonObject;
    }


    public static void main(String[] args) throws IOException {
        String address = getCity(31.845716,117.14134);
        System.out.println(address);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值