1. 程式人生 > >根據地址獲取經緯度

根據地址獲取經緯度

有時候在開發中我們會需要根據模糊地址獲取經緯度,國家資訊中心的天地圖api可以幫助我們實現這個功能,通過模糊地址獲取經緯度直接上程式碼:

/**
     * 通過地址獲取經緯度
     *
     * @param address
     * @return
     */
    public static Map<String, String> getLngAndLag(String address) {
        Map<String, String> lngLat = new HashMap<>();
        String url = " http://api.tianditu.gov.cn/geocoder?ds={'keyWord':'" + address + "'}&tk=您的金鑰";
        String json = loadJSON(url);
        JSONObject jsonObject = JSONObject.fromObject(json);
        String status = getJsonValue("status", jsonObject);
        String backMsg = getJsonValue("msg", jsonObject);
        if ("0".equals(status) && "ok".equalsIgnoreCase(backMsg)) {
            if (StringUtils.isEmpty(getJsonValue("resultType", jsonObject))) {
                DecimalFormat dFormat = new DecimalFormat("#.00");
                String lon = dFormat.format(Double.valueOf(jsonObject.getJSONObject("location").getString("lon")));
                String lat = dFormat.format(Double.valueOf(jsonObject.getJSONObject("location").getString("lat")));
                lngLat.put("lng", lon);
                lngLat.put("lat", lat);
            }
            if (StringUtils.isNotEmpty(getJsonValue("resultType", jsonObject))) {
                DecimalFormat dFormat = new DecimalFormat("#.00");
                String admin = jsonObject.getString("admin");
                String s = admin.replaceAll("\\[", "").replaceAll("]", "");
                JSONObject JsonMiddle = JSONObject.fromObject(s);
                String lon = dFormat.format(Double.valueOf(JsonMiddle.getJSONObject("location").getString("lon")));
                String lat = dFormat.format(Double.valueOf(JsonMiddle.getJSONObject("location").getString("lat")));
                lngLat.put("lng", lon);
                lngLat.put("lat", lat);
            }
        }

        if ("101".equals(status) || "404".equals(status)) {

            lngLat = null;
        }
        return lngLat;
    }

網頁轉換為json字串程式碼:

/**
     * 請求網頁訊息轉換為Json字串
     *
     * @param url
     * @return
     */
    public static String loadJSON(String url) {

        StringBuffer json = new StringBuffer();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    yc.getInputStream()));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        return json.toString();
    }

剔除json key為空的情況:

    //剔除json key為空的情況
    public static String getJsonValue(String jsonKey, JSONObject jsonObject) {
        String condition = "";
        if (jsonObject.containsKey(jsonKey)) {
            condition = String.valueOf(jsonObject.get(jsonKey));
        }
        return condition;
    }

根據經緯度獲取省市縣程式碼:

    public static Map<String, String> getArea(String lng, String lat) {
        Map<String, String> area = new HashMap<>();
        String url = "http://api.tianditu.gov.cn/geocoder?postStr={'lon':" + lng + ",'lat':" + lat + ",'ver':1}&type=geocode&tk=您的key";
        String json = loadJSON(url);
        JSONObject jsonObject = JSONObject.fromObject(json);
        String status = getJsonValue("status", jsonObject);
        String backMsg = getJsonValue("msg", jsonObject);
        Map<String, String> lngLat = new HashMap<>();

        if ("0".equals(status) && "ok".equalsIgnoreCase(backMsg)) {
            String address = jsonObject.getJSONObject("result").getJSONObject("addressComponent").getString("city");
            area = addressResolution(address);
            area.put("lng", lng);
            area.put("lat", lat);
        }

        if ("101".equals(status) || "404".equals(status)) {

            area = null;
        }
        return area;
    }

解析地址程式碼:

/**
     * 解析地址
     *
     * @param address
     * @return
     * @author lin
     */
    public static Map<String, String> addressResolution(String address) {

        String[] cityName = {"上海", "北京", "天津", "重慶"};

        String[] cityArr = address.split("市", -1);

        if (ArrayUtils.contains(cityName, cityArr[0])) {
            address = cityArr[0] + "市市轄區" + cityArr[1];
        }

        String regex = "(?<province>[^省]+自治區|.*?省|.*?行政區|.*?市)(?<city>[^市]+自治州|.*?地區|.*?行政單位|.+盟|市轄區|.*?市|.*?縣)(?<county>[^縣]+縣|.+區|.+市|.+旗|.+海域|.+島)?(?<town>[^區]+區|.+鎮)?(?<village>.*)";
        Matcher m = Pattern.compile(regex).matcher(address);
        String province = null, city = null, county = null, town = null, village = null;
        Map<String, String> row = null;
        while (m.find()) {
            row = new LinkedHashMap<String, String>();
            province = m.group("province").replaceAll("省|市|自治區|壯族|維吾爾|回族", "");
            row.put("province", province == null ? "" : province.trim());
            city = m.group("city").replaceAll("市|自治州|地區|自治市", "");
            row.put("city", city == null ? "" : city.trim());
            county = m.group("county");
            row.put("county", county == null ? "" : county.trim());
            town = m.group("town");
            row.put("town", town == null ? "" : town.trim());
            village = m.group("village");
            row.put("village", village == null ? "" : village.trim());
        }
        return row;
    }