点击▲关注 “爪哇笔记” 给公众号标星置顶
更多精彩 第一时间直达
前言
群里小伙伴们说自己手撸经纬度太麻烦了,还得自己去查,太鸡儿浪费时间了。今天给大家分享一个新技能,地理编码服务,用户可通过该功能,将结构化地址(省/市/区/街道/门牌号)解析为对应的位置坐标。地址结构越完整,地址内容越准确,解析的坐标精度越高。
百度地图
首先需要注册一个百度开放平台的账号,百度这个是一网通的,只要你注册过贴吧账号,基本都可以直接登录。
一般获取到应用AK就可以了,如果启用SN校验方式,还需要获取SN校验码。
工具类
百度的说明文档挺全,各种请求参数、返回结果参数描述的十分详细,基本上不会浪费大家很多时间。撸主撸了一个工具类,大家也可以直接使用。
/**
* @Description
* @Author 爪哇笔记
* @Date 2022/9/4
* 参考:http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding
*/
public class BaiDuMapUtils {
static Logger logger = LoggerFactory.getLogger(BaiDuMapUtils.class);
static String AK = "***************";
static String SN =""***************;
static String STATUS ="status";
public static void main(String[] args) {
String dom = "北京王府井";
System.out.println("'" + dom + "'的经纬度为:" + getCoordinate(dom));
}
/**
* 调用百度地图API根据地址,获取坐标
* @param address
* @return
*/
public static Result getCoordinate(String address) {
if (address != null && !"".equals(address)) {
address = address.replaceAll("\\s*", "").replace("#", "栋");
String url = "http://api.map.baidu.com/geocoding/v3";
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("address",address);
params.add("output","json");
params.add("ak",AK);
params.add("sn",SN);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
ResponseEntity<String> response = client.exchange(url, HttpMethod.POST, requestEntity, String.class);
String json = response.getBody();
logger.info("位置信息:{}",json);
if (StringUtils.isNotBlank(json)) {
JSONObject obj = JSONObject.parseObject(json);
if (SystemConstant.CODE_0.equals(obj.getString(STATUS))) {
/**
* 经度
*/
double longitude = obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
/**
* 纬度
*/
double latitude = obj.getJSONObject("result").getJSONObject("location").getDouble("lat");
DecimalFormat df = new DecimalFormat("#.######");
Map<String, Object> map = new HashMap<>(6);
map.put("longitude",df.format(longitude));
map.put("latitude",df.format(latitude));
return Result.ok(map);
}else{
return Result.error(obj.getString("message"));
}
}else{
return Result.error();
}
}else{
return Result.error();
}
}
}
效果演示:
声明
版权申明:源码功能来源于网络二次开发,仅供学习交流之用,请勿用于用于商业用途。如有侵权,请联系我们删除。
▲加小编进群,暗号签到