一、添加依赖
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0</version> </dependency>
二、请求工具类
import com.github.kevinsawicki.http.HttpRequest; /** * 请求工具类 */ public class RequestUtils { private static final String DEFAULT_CHARSET = "utf-8"; private static final int CONNECT_TIMEOUT_IN_MIS_SECOND = 10000; private static final int READ_TIMEOUT_IN_MIS_SECOND = 30000; public static RequestResult getJsonText(String url, String charset) { if (charset == null) charset = DEFAULT_CHARSET; HttpRequest request = HttpRequest.get(url).connectTimeout(CONNECT_TIMEOUT_IN_MIS_SECOND).readTimeout(READ_TIMEOUT_IN_MIS_SECOND); String body = request.body(charset); int code = request.code(); request.disconnect(); return new RequestResult(code, body); } }
三、返回接收类
import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; /** * 高德地图返回工具类 */ @Getter @Setter @AllArgsConstructor public class RequestResult { /** 状态码 */ private int code; /** 返回body */ private String body; }
四、高德地图工具类
import java.net.URLEncoder; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 获取高德地图经纬度 * * @author lixin.saho */ public class MapUtils { private static String API = "http://restapi.amap.com/v3/geocode/geo?key=<key>&s=rsv3&address=<address>"; private static String KEY = "key"; private static Pattern pattern = Pattern.compile("\"location\":\"(\\d+\\.\\d+),(\\d+\\.\\d+)\""); static { init(); } private static void init() { // System.out.println("高德地图工具类初始化"); // System.out.println("api: {}"+API); // System.out.println("key: {}"+KEY); API = API.replaceAll("<key>", KEY); } private static double[] getLatAndLonByAddress(String address) { try { String requestUrl = API.replaceAll("<address>", URLEncoder.encode(address, "UTF-8")); RequestResult requestResult = RequestUtils.getJsonText(requestUrl, null); if (200 != requestResult.getCode()) { return null; } requestUrl = requestResult.getBody(); if (requestUrl != null) { Matcher matcher = pattern.matcher(requestUrl); if (matcher.find() && matcher.groupCount() == 2) { double[] gps = new double[2]; gps[0] = Double.valueOf(matcher.group(1)); gps[1] = Double.valueOf(matcher.group(2)); return gps; } } } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) { double[] aaa = MapUtils.getLatAndLonByAddress("广东省深圳市福田区天安数码城创业科技大厦一期"); for (double cccc : aaa) { System.out.println(cccc); } System.out.println(MapUtils.getLatAndLonByAddress("广东省深圳市福田区天安数码城创业科技大厦一期")); }
五、高德地图的秘钥,及高德地图工具类里的key需要自己申请
原文地址:https://www.cnblogs.com/shaolixin/p/10203246.html
时间: 2024-10-27 11:39:35