概述
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.slf.common.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* 高德地图服务
*
* @author
* @date 2021/11/25 15:04
*/
@Slf4j
public class GaodeHelper {
@Value("${gaode.key}")
private String key;
/*根据地址获取经纬度高德url*/
private static final String urlFormat = "http://restapi.amap.com/v3/geocode/geo?address=%s&output=JSON&key=%s";
/*根据坐标解析具体地址高德url*/
private static final String parseCoorUrlFormat = "https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=%s&key=%s&radius=1000&extensions=base";
/*根据坐标解析具体地址高德url*/
private static final String ipLocation = "https://restapi.amap.com/v3/ip?ip=%s&output=JSON&key=%s";
public static final String ERROR = "error";
public static final String SUCCESS = "success";
public static final String STATUS_1 = "1";
/**
* 根据ip获取地址
*
* @param ip
* @return 经纬度和status
*/
public String getLocationByIp(String ip) {
if (StringUtils.isBlank(ip)) {
return null;
}
log.info("调用高德接口根据ip获取地理位置:address={}", ip);
String url = String.format(ipLocation, ip, key);
if (log.isInfoEnabled()) {
log.info("调用高德接口根据ip获取地理位置,url==> {}", url);
}
InputStream inputStream = null;
try {
URL _url = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) _url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(5 * 1000);//超时时间
urlConnection.setRequestProperty("contentType", "utf-8");//字符集
urlConnection.connect();
inputStream = urlConnection.getInputStream();
JsonNode jsonNode = new ObjectMapper().readTree(inputStream);//jackson
if (log.isInfoEnabled()) {
log.info("调用高德接口根据ip获取地理位置,response==> {}", jsonNode.toString());
}
if (STATUS_1.equals(jsonNode.findValue("status").textValue())) {
String province = jsonNode.findValue("province").textValue();
String city = jsonNode.findValue("city").textValue();
return province + "," + city;
}
} catch (IOException e) {
log.info("调用高德接口根据ip获取地理位置,参数:address={},异常信息:{}", ip, e);
} finally {
try {
if (null != inputStream) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 根据地址获取经纬度
*
* @param address 地址输入
* @return 经纬度和status
*/
public Map<String, String> getLngLat(String address) {
String filterAddress = Objects.requireNonNull(address).trim().replaceAll("\s*", "").replaceAll("#", "");
log.info("调用高德接口根据地址获取经纬度输入参数:address={}", filterAddress);
String url = String.format(urlFormat, filterAddress, key);
if (log.isInfoEnabled()) {
log.info("请求高德地图坐标拾取,url==> {}", url);
}
HashMap<String, String> result = new HashMap<>();
InputStream inputStream = null;
try {
URL _url = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) _url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(5 * 1000);//超时时间
urlConnection.setRequestProperty("contentType", "utf-8");//字符集
urlConnection.connect();
inputStream = urlConnection.getInputStream();
JsonNode jsonNode = new ObjectMapper().readTree(inputStream);//jackson
if (log.isInfoEnabled()) {
log.info("请求高德地图坐标拾取,response==> {}", jsonNode.toString());
}
JsonNode geoCodes = jsonNode.findValue("geocodes");
if (STATUS_1.equals(jsonNode.findValue("status").textValue()) && geoCodes.size() > 0) {
String[] degree = geoCodes.findValue("location").textValue().split(",");
if (ArrayUtils.isNotEmpty(degree)) {
result.put("longitude", degree[0]);
result.put("latitude", degree[1]);
result.put("status", SUCCESS);
}
}
log.info("调用高德接口根据地址获取经纬度返回结果:{},参数:address={}", result, filterAddress);
} catch (IOException e) {
log.info("调用高德接口根据地址获取经纬度执行异常,参数:address={},异常信息:{}", filterAddress, e);
result.put("status", ERROR);
} finally {
try {
if (null != inputStream) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 根据坐标解析具体地址
*
* @param latitude
纬度
* @param longitude 经度
* @return
*/
public Map<String, String> parseCoordinate(double longitude, double latitude) {
log.info("调用高德接口根据坐标解析具体地址输入参数:longitude={},latitude={}", longitude, latitude);
Map<String, String> resultMap = Maps.newHashMap();
String coordinate = new StringBuilder().append(longitude).append(",").append(latitude).toString();
String url = String.format(parseCoorUrlFormat, coordinate, key);
try {
JSONObject responseJson = HttpClientUtil.doGetJson(url);
if (STATUS_1.equals(responseJson.getString("status"))) {
JSONObject regeocodeJson = responseJson.getJSONObject("regeocode");
if (regeocodeJson != null) {
resultMap.put("status", SUCCESS);
resultMap.put("address", regeocodeJson.getString("formatted_address"));//具体地址,如:浙江省杭州市西湖区蒋村街道杭州互联网创新创业园
JSONObject addressComponentJson = regeocodeJson.getJSONObject("addressComponent");
if (addressComponentJson != null) {
resultMap.put("province", addressComponentJson.getString("province"));//省,如:浙江省
resultMap.put("city", addressComponentJson.getString("city"));//市,如:杭州市
resultMap.put("district", addressComponentJson.getString("district"));//区,如:西湖区
/**
* 如果是地级市需要获取townCode值
*/
resultMap.put("districtCode", addressComponentJson.getString("adcode"));//行政区编码
String townCode = addressComponentJson.getString("towncode");
if (townCode != null) {
townCode = townCode.length() <= 9 ? townCode : townCode.substring(0, 9);
resultMap.put("townCode", townCode);//乡镇街道编码
resultMap.put("townShip", addressComponentJson.getString("township"));//乡镇街道名称
}
}
}
}
log.info("调用高德接口根据坐标解析具体地址返回结果:{},参数:longitude={},latitude={}", resultMap, longitude, latitude);
return resultMap;
} catch (Exception e) {
log.info("调用高德接口根据坐标解析具体地址执行异常,参数:longitude={},latitude={},异常信息:{}", longitude, latitude, e);
resultMap.put("status", ERROR);
return resultMap;
}
}
}
最后
以上就是活泼冬日为你收集整理的高德地图工具类的全部内容,希望文章能够帮你解决高德地图工具类所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复