一、返回对象类
package com.app.model;
import com.app.enumm.CodeEnum;
import java.io.Serializable;
/**
* @description :
* @Author :Rujh
* @CreatTime : 2023/4/3 10:22
**/
public class Result<T> implements Serializable {
private T datas;
private Integer resp_code;
private String resp_msg;
public static <T> Result<T> succeed(T model, String msg) {
return of(model, CodeEnum.SUCCESS.getCode(), msg);
}
public static <T> Result<T> succeed(T model) {
return of(model, CodeEnum.SUCCESS.getCode(), "SUCCESS");
}
public static <T> Result<T> of(T datas, Integer code, String msg) {
return new Result(datas, code, msg);
}
public static <T> Result<T> failed(String msg) {
return (Result<T>) of((Object)null, CodeEnum.ERROR.getCode(), msg);
}
public static <T> Result<T> failed(T model, String msg) {
return of(model, CodeEnum.ERROR.getCode(), msg);
}
public T getDatas() {
return this.datas;
}
public Integer getResp_code() {
return this.resp_code;
}
public String getResp_msg() {
return this.resp_msg;
}
public void setDatas(T datas) {
this.datas = datas;
}
public void setResp_code(Integer resp_code) {
this.resp_code = resp_code;
}
public void setResp_msg(String resp_msg) {
this.resp_msg = resp_msg;
}
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof Result)) {
return false;
} else {
Result<?> other = (Result)o;
if (!other.canEqual(this)) {
return false;
} else {
label47: {
Object this$resp_code = this.getResp_code();
Object other$resp_code = other.getResp_code();
if (this$resp_code == null) {
if (other$resp_code == null) {
break label47;
}
} else if (this$resp_code.equals(other$resp_code)) {
break label47;
}
return false;
}
Object this$datas = this.getDatas();
Object other$datas = other.getDatas();
if (this$datas == null) {
if (other$datas != null) {
return false;
}
} else if (!this$datas.equals(other$datas)) {
return false;
}
Object this$resp_msg = this.getResp_msg();
Object other$resp_msg = other.getResp_msg();
if (this$resp_msg == null) {
if (other$resp_msg != null) {
return false;
}
} else if (!this$resp_msg.equals(other$resp_msg)) {
return false;
}
return true;
}
}
}
protected boolean canEqual(Object other) {
return other instanceof Result;
}
public String toString() {
return "Result(datas=" + this.getDatas() + ", resp_code=" + this.getResp_code() + ", resp_msg=" + this.getResp_msg() + ")";
}
public Result() {
}
public Result(T datas, Integer resp_code, String resp_msg) {
this.datas = datas;
this.resp_code = resp_code;
this.resp_msg = resp_msg;
}
}
二、导入工具类所需枚举类
1、高德地图枚举类
package com.app.enumm;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @description :高德地图枚举类
* @Author :Rujh
* @CreatTime : 2023/4/3 10:11
**/
@AllArgsConstructor
@Getter
public enum GaoDeEnum {
// 高德地图固定字段
STATUS("status"),
INT_ONE("1"),
RE_GEO_CODE("regeocode"),
GEO_CODES("geocodes"),
LOCATION("location"),
FORMATTED_ADDRESS("formatted_address"),
RESULTS("results"),
DISTANCE("distance");
private String code;
}
3、Code枚举类
package com.app.enumm;
/**
* @description :
* @Author :Rujh
* @CreatTime : 2023/4/3 10:22
**/
public enum CodeEnum {
SUCCESS(0),
ERROR(1);
private Integer code;
private CodeEnum(Integer code) {
this.code = code;
}
public Integer getCode() {
return this.code;
}
}
三、进入 高德开放平台 | 高德地图API 控制台->应用管理->我的应用->创建新应用并且拿到key
1、导入工具类并将key替换
2、工具类
package com.app.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.app.enumm.GaoDeEnum;
import com.app.model.Result;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* @description :
* @Author :Rujh
* @CreatTime : 2023/4/3 10:16
**/
@Component
@Slf4j
public class GaoDeMapUtil {
/**
* 功能描述: 高德地图Key
*
* @param null
* @return
* @author 周兆宇
* @date 2022-01-26 09:13:40
*/
private static final String GAO_DE_KEY = "d36dbfa2e026e798ed9804eb600751d6";
//申请的账户Key
/**
* 功能描述: 根据地址名称得到两个地址间的距离
*
* @param start 起始位置
* @param end 结束位置
* @return long 两个地址间的距离
* @author isymikasan
* @date 2022-01-26 09:16:04
*/
public Long getDistanceByAddress(String start, String end) {
String startLonLat = getLonLat(start).getDatas().toString();
String endLonLat = getLonLat(end).getDatas().toString();
Long distance = Long.valueOf(getDistance(startLonLat, endLonLat).getDatas().toString());
return distance;
}
/**
* 功能描述: 地址转换为经纬度
*
* @param address 地址
* @return java.lang.String 经纬度
* @author isymikasan
* @date 2022-01-26 09:17:13
*/
public Result getLonLat(String address) {
try {
// 返回输入地址address的经纬度信息, 格式是 经度,纬度
String queryUrl = "http://restapi.amap.com/v3/geocode/geo?key=" + GAO_DE_KEY + "&address=" + address;
// 高德接口返回的是JSON格式的字符串
String queryResult = getResponse(queryUrl);
JSONObject job = JSONObject.parseObject(queryResult);
JSONObject jobJSON = JSONObject
.parseObject(
job.get("geocodes").toString().substring(1, job.get("geocodes").toString().length() - 1));
String LngAndLat = jobJSON.get("location").toString();
log.info("经纬度为:" + LngAndLat);
return Result.succeed(LngAndLat, "经纬度转换成功!");
} catch (Exception e) {
return Result.failed(e.toString());
}
}
/**
* 将经纬度 转换为 地址
*
* @param longitude 经度
* @param latitude 纬度
* @return 地址名称
* @throws Exception
*/
public Result getAddress(String longitude, String latitude) throws Exception {
String url;
try {
url = "http://restapi.amap.com/v3/geocode/regeo?output=JSON&location=" + longitude + "," + latitude
+ "&key=" + GAO_DE_KEY + "&radius=0&extensions=base";
log.info("经度" + longitude);
log.info("纬度:" + latitude);
log.info("url:" + url);
// 高德接口返回的是JSON格式的字符串
String queryResult = getResponse(url);
if (ObjectUtils.isNull(queryResult)) {
return Result.failed("查询结果为空");
}
// 将获取结果转为json 数据
JSONObject obj = JSONObject.parseObject(queryResult);
if (obj.get(GaoDeEnum.STATUS.getCode()).toString().equals(GaoDeEnum.INT_ONE.getCode())) {
// 如果没有返回-1
JSONObject reGeoCode = obj.getJSONObject(GaoDeEnum.RE_GEO_CODE.getCode());
if (reGeoCode.size() > 0) {
// 在regeocode中拿到 formatted_address 具体位置
String formatted = reGeoCode.get("formatted_address").toString();
return Result.succeed(formatted, "地址获取成功!");
} else {
return Result.failed("未找到相匹配的地址!");
}
} else {
return Result.failed("请求错误!");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return Result.failed("系统未知异常,请稍后再试");
}
}
/**
* 功能描述: 根据两个定位点的经纬度算出两点间的距离
* @param startLonLat 起始经纬度
* @param endLonLat 结束经纬度(目标经纬度)
* @return java.lang.Long 两个定位点之间的距离
* @author isymikasan
* @date 2022-01-26 09:47:42
*/
public Result getDistance(String startLonLat, String endLonLat) {
try {
// 返回起始地startAddr与目的地endAddr之间的距离,单位:米
Long result = new Long(0);
String queryUrl =
"http://restapi.amap.com/v3/distance?key=" + GAO_DE_KEY + "&origins=" + startLonLat
+ "&destination="
+ endLonLat;
String queryResult = getResponse(queryUrl);
JSONObject job = JSONObject.parseObject(queryResult);
JSONArray ja = job.getJSONArray("results");
JSONObject jobO = JSONObject.parseObject(ja.getString(0));
result = Long.parseLong(jobO.get("distance").toString());
log.info("距离:" + result/1000+"km");
return Result.succeed(result/1000+"km", "距离计算成功!");
} catch (Exception e) {
return Result.failed(e.toString());
}
}
/**
* 功能描述: 发送请求
*
* @param serverUrl 请求地址
* @return java.lang.String
* @author isymikasan
* @date 2022-01-26 09:15:01
*/
private static String getResponse(String serverUrl) {
// 用JAVA发起http请求,并返回json格式的结果
StringBuffer result = new StringBuffer();
try {
URL url = new URL(serverUrl);
URLConnection conn = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
}
四、导入controller层
package com.app.controller;
import com.app.model.Result;
import com.app.utils.GaoDeMapUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Resource;
/**
* @description :
* @Author :Rujh
* @CreatTime : 2023/4/3 10:33
**/
@RestController
@Api(tags = "地图")
@RequestMapping("/point")
public class GaoDeMapController {
@Resource
private GaoDeMapUtil gaoDeMapUtil;
public static final Logger log = LoggerFactory.getLogger(GaoDeMapController.class);
@ApiOperation(value = "根据经纬度获取地址")
@ApiImplicitParams({
@ApiImplicitParam(name = "longitude", value = "经度"),
@ApiImplicitParam(name = "latitude", value = "纬度")
})
@PostMapping("/getAddress")
public Result getAddress(@RequestParam("longitude") String longitude, @RequestParam("latitude") String latitude) {
try {
return gaoDeMapUtil.getAddress(longitude, latitude);
} catch (Exception e) {
return Result.failed(e.toString());
}
}
@ApiOperation(value = "根据地址获取经纬度")
@ApiImplicitParam(name = "address", value = "地理位置")
@PostMapping("/getLonLat")
public Result getLonLat(String address) {
return gaoDeMapUtil.getLonLat(address);
}
@ApiOperation(value = "根据两个定位点的经纬度算出两点间的距离(单位:km)")
@ApiImplicitParams({
@ApiImplicitParam(name = "startLonLat", value = "起始经纬度"),
@ApiImplicitParam(name = "endLonLat", value = "结束经纬度")
})
@PostMapping("/getDistance")
public Result getDistance(String startLonLat, String endLonLat) {
return gaoDeMapUtil.getDistance(startLonLat, endLonLat);
}
}
五、测试结果
1、将地址转换为经纬度
请求参数:address
参数类型:String
示例值:甘肃省酒泉市肃州区泉湖镇祁连路13号鑫源家园
结果:
### 2、根据经纬度获取地址
请求参数1:longitude
请求参数2:latitude
参数类型:String
请求参数1示例值:98.521876
请求参数2示例值:39.727607
结果:
### 3、根据经纬度算出两点间的距离
请求参数1:startLonLat
请求参数2:endLonLat
参数类型:String
请求参数1示例值:98.521876,39.727607
请求参数2示例值:118.670942,24.868273
结果: