public class BaiduMapUtils {
@Value("${baidu.map.coordinateUrl}")
public static String URL = "";
@Value("${baidu.map.ak}")
public static String AK = "";
/**
* 根据名称获取经纬度
*/
public static void getCoordinate(String position) {
try {
BaiduMapUtils snCal = new BaiduMapUtils();
Map params = new LinkedHashMap<String, String>();
RoutePlanRequestVO routePlanRequestVO = new RoutePlanRequestVO();
routePlanRequestVO.setAk(AK);
routePlanRequestVO.setAddress(position);
JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(routePlanRequestVO));
jsonObject.entrySet().forEach(item -> {
String s = StrUtil.toUnderlineCase(item.getKey());
params.put(s, item.getValue());
});
snCal.requestGetAK(URL, params);
} catch (Exception e) {
log.error("调用百度地图获取经纬度异常,异常信息为:{}", e);
}
}
/**
* 默认ak
* 选择了ak,使用IP白名单校验:
* 根据您选择的AK以为您生成调用代码
* 检测到您当前的ak设置了IP白名单校验
* 您的IP白名单中的IP非公网IP,请设置为公网IP,否则将请求失败
* 请在IP地址为xxxxxxx的计算发起请求,否则将请求失败
*/
public void requestGetAK(String strUrl, Map<String, String> param) throws Exception {
if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
return;
}
StringBuffer queryString = new StringBuffer();
queryString.append(strUrl);
for (Map.Entry<?, ?> pair : param.entrySet()) {
queryString.append(pair.getKey() + "=");
queryString.append(URLEncoder.encode((String) pair.getValue(),
"UTF-8") + "&");
}
if (queryString.length() > 0) {
queryString.deleteCharAt(queryString.length() - 1);
}
java.net.URL url = new URL(queryString.toString());
System.out.println(queryString.toString());
URLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.connect();
InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
isr.close();
System.out.println("AK: " + buffer.toString());
}
}
通过百度地图api获取城市经纬度
最新推荐文章于 2024-04-29 09:39:27 发布