Java调用百度API获取经纬度

private String accessKey = "lfSBwCTimmaMF06HGSEkQCIVfNTQ****";//百度AK
private static final String LAT = "lat"; //纬度值
private static final String LNG = "lng";    //经度值
private InputStreamReader isr = null;

public Map getLatAndLng(String address) {
        Map lngAnglatMap = new HashMap();
        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;
    }

你可能感兴趣的:(Java,百度API,经纬度)