AMapUtils.java 2.13 KB
package com.glsx.common.utils.map;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.glsx.common.constants.Constants;
import com.glsx.common.utils.HttpUtils;
import com.glsx.common.utils.PropertiesUtil;

/**
 * 
 * @Title AMapUtils.java
 * @Package com.glsx.common.utils.map
 * @Description TODO 高德地图相关api
 * @author zhanghj
 * @date 2019年4月22日 下午5:03:01
 * @version 1.0.0
 */
public class AMapUtils {
	
	private static Logger logger = LoggerFactory.getLogger(AMapUtils.class);

	public static final String GEOCODES_URL = "https://restapi.amap.com/v3/geocode/geo";
	
	public static Integer getDistrictCodeByAddress(String address) {
		Integer district = null;
		String key = PropertiesUtil.getProperty(Constants.AMAP_USER_KEY);
		//String key = "4d8b3b5fc398f2f79f4329b5d07732fb";
		Map<String ,String> params = new HashMap<String, String>();
		params.put("address", address);
		params.put("key", key);
		try {
			String result = HttpUtils.get(GEOCODES_URL, params);
			logger.info("获取高德行政编码返回结果:" + result);
			if (StringUtils.isNotEmpty(result)) {
	            JSONObject json = JSON.parseObject(result);
	            if (json.containsKey("status")) {
	            	int status = json.getIntValue("status");
	            	if (status == 1) {
	            		JSONArray geocodes = json.getJSONArray("geocodes");
	            		JSONObject geocode = geocodes.getJSONObject(0);
	            		district = geocode.getInteger("adcode");
	            	} 
	            }
	        }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("通过高德地图获取区域编码错误", e);
		}
		return district; 
	}
	
	public static void main(String[] args) {
		String address = "广东省深圳市南山区科兴科学园";
		Integer district = getDistrictCodeByAddress(address);
		System.out.println("district="+district );
	}
}