根据经纬度、ip解析具体位置( 使用百度API解析经纬度或IP)

/**
     * 百度地图的秘钥
     */
    private static final String BAIDUMAP_AK = "A59c4e5ac4c522be01626a9e51b8ac06";

Map ipMap = BaiduMapUtil.parseAddress(longitude, latitude, ip);
                province = ipMap.get(BaiduMapUtil.PROVINCE);
                city = ipMap.get(BaiduMapUtil.CITY);
                log.info("百度解析地址,交易省:{},市:{}", province, city);
                actionInfoMap.put(RcsConstantParam.Param.PROVINCE, province);// 交易省
                actionInfoMap.put(RcsConstantParam.Param.CITY, city);// 交易市
                actionInfoMap.put(RcsConstantParam.Param.ADDRESS_DETAIL, ipMap.get(BaiduMapUtil.ADDRESS));

public static Map parseAddress(String lng, String lat, String ip) {
        Map parMap = new HashMap(2);
        // 先解析经纬度获取城市信息
        JSONObject object = getInfoByLatAndLng(lng, lat);
        if (object != null) {
            if (object.getInteger("status") == 0) {
                //成功获取城市信息
                JSONObject result = object.getJSONObject("result").getJSONObject("addressComponent");
                parMap.put(PROVINCE, result.getString("province"));
                parMap.put(CITY, result.getString("city"));
                // 区县+街道+门址
                String detail = new StringBuffer(result.getString("district")).append(
                        result.getString("street")).append(
                        result.getString("street_number")).toString();
                parMap.put(ADDRESS, detail);
                return parMap;
            }
        }
        //解析失败 通过IP获取城市信息
        return parseIpByBaidu(ip);
    }

 

public static JSONObject getInfoByLatAndLng(String lng, String lat) {
        //经纬度不确定
        if (StringUtil.isEmpty(lng) || lng.contains("E")) {
            return null;
        }
        if (StringUtil.isEmpty(lat) || lat.contains("E")) {
            return null;
        }
        logger.debug("开始获取经纬度……");
        try {
            String url = CITY_GEOCODER + lat + "," + lng;
            String retVal = HttpForPayUtil.get(url, 1000, 1000);
            retVal = retVal.replace("renderReverse&&renderReverse(", "").replace(")", "");
            JSONObject object = JSONObject.parseObject(retVal);
            logger.debug("获取经纬度完成……");
            return object;
        } catch (Exception e) {
            logger.error("获取地理位置信息出错:", e);
            logger.debug("获取经纬度完成……");
            return null;
        }
    }

 private static final String CITY_GEOCODER = "http://api.map.baidu.com/geocoder/v2/?ak=" + BAIDUMAP_AK + "&callback=renderReverse&output=json&pois=0&location=";

 

public static String get(String url, Map params,
            String charset,int connectTimeout,int soTimeout) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        List qparams = getParamsList(params);
        if (qparams != null && qparams.size() > 0) {
            charset = (charset == null ? defaultCharset : charset);
            String formatParams = URLEncodedUtils.format(qparams, charset);
            url = (url.indexOf("?")) < 0 ? (url + "?" + formatParams) : (url
                    .substring(0, url.indexOf("?") + 1) + formatParams);
        }
        DefaultHttpClient httpclient = getDefaultHttpClient(charset,connectTimeout,soTimeout);
//        logger.info("Get请求,url:"+url);
        HttpGet hg = new HttpGet(url);
        // 发送请求,得到响应
        String responseStr = null;
        try {
            responseStr = httpclient.execute(hg, responseHandler);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            responseStr = "-11,客户端连接协议错误";
        } catch (IOException e) {
            e.printStackTrace();
            responseStr = "-12,IO操作异常";
        } finally {
            abortConnection(hg, httpclient);
        }
        return responseStr;
    }

 

@SuppressWarnings("deprecation")
    private static DefaultHttpClient getDefaultHttpClient(final String charset,int connectTimeout,int soTimeout) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(
                CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        // 模拟浏览器,解决一些服务器程序只允许浏览器访问的问题
        httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
        httpclient.getParams().setParameter(
                CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
        httpclient.getParams().setParameter(
                CoreProtocolPNames.HTTP_CONTENT_CHARSET,
                charset == null ? defaultCharset : charset);
        httpclient.setHttpRequestRetryHandler(requestRetryHandler);
        //超时时间设置
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout); //连接超时30s
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); //读取超时3min
        return httpclient;
    }

 

public static Map parseIpByBaidu(String ip) {
        Map parMap = new HashMap(3);
        if (StringUtils.isEmpty(ip)) {
            return parMap;
        }
        try {
            String response = HttpForPayUtil.get(BAIDU_IP
                    + StringUtils.trimToEmpty(ip), 1000, 1000);

            Map addressMap = JSONUtil.getInstance()
                    .parseJSON2Map(response);
            logger.debug("根据百度IP定位,返回信息:" + addressMap);
            // 获取状态码
            Integer status = (Integer) addressMap.get("status");
            if (status != 0) {
                logger.error("根据百度IP查询信息错误。百度返回信息:" + response);
                return null;
            }
            Map contentMap = (Map) addressMap
                    .get("content");

            Map addressDetailMap = (Map) contentMap
                    .get("address_detail");

            String province = (String) addressDetailMap.get("province");
            String city = (String) addressDetailMap.get("city");

            // 区县+街道+门址
            String detail = new StringBuffer((String) addressDetailMap
                    .get("district")).append(
                    (String) addressDetailMap.get("street")).append(
                    (String) addressDetailMap.get("street_number")).toString();
            /**
             * 省市最多不会超过20个字符,但考虑到IP获取到外部地区时,会获取到较长字符。 为了保证当此处字符较长时,超过数据库字段长度,导致业务失败,此处截取
             */
            province = StringUtils.substring(province, 0, 20);
            city = StringUtils.substring(city, 0, 50);
            parMap.put(PROVINCE, province);
            parMap.put(CITY, city);
            parMap.put(ADDRESS, detail);
        } catch (Exception e) {
            logger.error("根据IP查询百度地图定位信息异常。IP:" + ip, e);
        }
        return parMap;
    }

 private static final String BAIDU_IP = "http://api.map.baidu.com/location/ip?ak="
            + BAIDUMAP_AK + "&ip=";

 

 

 

 

 

 

你可能感兴趣的:(根据经纬度、ip解析具体位置( 使用百度API解析经纬度或IP))