Java调用百度API获取经纬度

版权声明:相互学习,欢迎指正,共同进步。 https://blog.csdn.net/liyuxing6639801/article/details/80619026
private String accessKey = "lfSBwCTimmaMF06HGSEkQCIVfNTQ****";//百度AK
private static final String LAT = "lat"; //纬度值
private static final String LNG = "lng";    //经度值
private InputStreamReader isr = null;

public Map<String, Double> getLatAndLng(String address) {
        Map<String, Double> lngAnglatMap = new HashMap<String, Double>();
        StringBuilder url = new StringBuilder("http://api.map.baidu.com/geocoder/v2/?address=").append(address)
                .append("&output=json&ak=").append(accessKey);
        try {
            String json = loadJSON(url.toString());
            JSONObject object = JSONObject.parseObject(json);
            //状态码
            String statusCode = object.getInteger("status").toString();
            if ("0".equals(statusCode)) {
                double lng = object.getJSONObject("result").getJSONObject("location").getDouble(LNG);
                lngAnglatMap.put("lng", lng);
                double lat = object.getJSONObject("result").getJSONObject("location").getDouble(LAT);
                lngAnglatMap.put("lat", lat);
            } else {
                LOGGER.warn("BaiduMapService", "百度接口服务状态码错误:" + statusCode);
            }
        } catch (Exception e) {
            LOGGER.error("BaiduMapService", e);
        }
        return lngAnglatMap;
    }

private String loadJSON(String url) {
        String json = null;
        try {
            URL mapAPI = new URL(url);
            URLConnection connection = mapAPI.openConnection();
            isr = new InputStreamReader(connection.getInputStream(), "utf-8");
            json=IOUtils.toString(isr);
        } catch (Exception e) {
            LOGGER.error("BaiduMapService", e);
        } finally {
            try {
                isr.close();
            } catch (IOException e) {
                LOGGER.error("BaiduMapService", e);
            }
        }
        return json;
    }

猜你喜欢

转载自blog.csdn.net/liyuxing6639801/article/details/80619026