package com.tools.common.util;@b@@b@import com.alibaba.fastjson.JSONObject;@b@import com.tools.common.constant.SystemConstant;@b@import com.tools.common.model.Result;@b@import org.apache.commons.lang3.StringUtils;@b@import org.slf4j.Logger;@b@import org.slf4j.LoggerFactory;@b@import org.springframework.http.*;@b@import org.springframework.util.LinkedMultiValueMap;@b@import org.springframework.util.MultiValueMap;@b@import org.springframework.web.client.RestTemplate;@b@@b@import java.text.DecimalFormat;@b@import java.util.HashMap;@b@import java.util.Map;@b@@b@/**@b@ * @Description@b@ * @Author 爪哇笔记@b@ * @Date 2022/9/4@b@ * 参考:http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding@b@ */@b@public class BaiDuMapUtils {@b@@b@ static Logger logger = LoggerFactory.getLogger(BaiDuMapUtils.class);@b@@b@ static String AK = "*****************";@b@@b@ static String SN ="*****************";@b@@b@ static String STATUS ="status";@b@@b@ public static void main(String[] args) {@b@ String dom = "北京王府井";@b@ System.out.println("'" + dom + "'的经纬度为:" + getCoordinate(dom));@b@ }@b@@b@ /**@b@ * 调用百度地图API根据地址,获取坐标@b@ * @param address@b@ * @return@b@ */@b@ public static Result getCoordinate(String address) {@b@ if (address != null && !"".equals(address)) {@b@ address = address.replaceAll("\\s*", "").replace("#", "栋");@b@ String url = "http://api.map.baidu.com/geocoding/v3";@b@ RestTemplate client = new RestTemplate();@b@ HttpHeaders headers = new HttpHeaders();@b@ headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);@b@ MultiValueMap<String, String> params = new LinkedMultiValueMap<>();@b@ params.add("address",address);@b@ params.add("output","json");@b@ params.add("ak",AK);@b@ params.add("sn",SN);@b@ HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);@b@ ResponseEntity<String> response = client.exchange(url, HttpMethod.POST, requestEntity, String.class);@b@ String json = response.getBody();@b@ logger.info("位置信息:{}",json);@b@ if (StringUtils.isNotBlank(json)) {@b@ JSONObject obj = JSONObject.parseObject(json);@b@ if (SystemConstant.CODE_0.equals(obj.getString(STATUS))) {@b@ /**@b@ * 经度@b@ */@b@ double longitude = obj.getJSONObject("result").getJSONObject("location").getDouble("lng");@b@ /**@b@ * 纬度@b@ */@b@ double latitude = obj.getJSONObject("result").getJSONObject("location").getDouble("lat");@b@ DecimalFormat df = new DecimalFormat("#.######");@b@ Map<String, Object> map = new HashMap<>(6);@b@ map.put("longitude",df.format(longitude));@b@ map.put("latitude",df.format(latitude));@b@ return Result.ok(map);@b@ }else{@b@ return Result.error(obj.getString("message"));@b@ }@b@ }else{@b@ return Result.error();@b@ }@b@ }else{@b@ return Result.error();@b@ }@b@ }@b@}