申请高德地图key
2.逆地理编码(坐标->地址)-地理X:
https://lbs.amap.com/demo/jsapi-v2/example/geocoder/regeocoding
3.经纬度在线查询网址:https://map.jiqrxx.com/jingweidu/
4.高德地图API资料地址:https://lbs.amap.com/api/webservice/guide/api/georegeo
5.高德地图响应错误码文档地址:https://lbs.amap.com/api/webservice/guide/tools/info
- /**
- *根据经纬度获取省市区
- */
- public static String getAddressStr(String log, String lat){
- //lat 小 log 大
- //参数解释: 纬度,经度 采用高德API可参考高德文档https://lbs.amap.com/
- //注意key是在高德开放平台申请的key,具体获得key的步骤请查看网址:https://developer.amap.com/api/webservice/guide/create-project/get-key
- String key = "个人申请的高德地图key";
- String parameters="?key="+key;
- // parameters+="&location="+"116.481488,39.990464";
- parameters+="&location="+log+","+lat;//经纬度坐标
- parameters+="&extensions=true";//返回结果控制,extensions 参数取值为 all 时会返回基本地址信息、附近 POI 内容、道路信息以及道路交叉口信息。
- parameters+="&radius=10";//搜索半径,radius取值范围在0~3000,默认是1000。单位:米
- parameters+="&batch=false";//批量查询控制,batch 参数设置为 false 时进行单点查询,此时即使传入多个经纬度也只返回第一个经纬度的地址解析查询结果。
- parameters+="&roadlevel=0";//道路等级,当 roadlevel = 0 时,显示所有道路
- // String urlString = "https://restapi.amap.com/v3/geocode/regeo?location="+lat+","+log+"&extensions=base&batch=false&roadlevel=0&key="+key;
- String urlString = "https://restapi.amap.com/v3/geocode/regeo"+parameters;
- StringBuilder res = new StringBuilder();
- try {
- URL url = new URL(urlString);
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- conn.setDoOutput(true);
- conn.setRequestMethod("POST");
- BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
- String line;
- while ((line = in.readLine()) != null) {
- res.append(line).append("\n");
- }
- in.close();
- //解析结果
- com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(res.toString());
- System.out.println("jsonObject = " + jsonObject);
- com.alibaba.fastjson.JSONObject jsonObject1 = jsonObject.getJSONObject("regeocode");
- res = new StringBuilder(jsonObject1.getString("formatted_address"));
- } catch (Exception e) {
- System.out.println("获取地址信息异常");
- e.printStackTrace();
- return null;
- }
- System.out.println("通过API获取到具体位置:"+res);
- return res.toString();
- }
- <dependency>
- <groupId>com.alibabagroupId>
- <artifactId>fastjsonartifactId>
- <version>1.2.24version>
- dependency>
- <dependency>
- <groupId>org.apache.httpcomponentsgroupId>
- <artifactId>httpclientartifactId>
- dependency>
-
代码如下:
- package ztt.map;
-
- import com.alibaba.fastjson.JSONArray;
- import com.alibaba.fastjson.JSONObject;
- import org.apache.http.HttpEntity;
- import org.apache.http.client.config.RequestConfig;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.util.EntityUtils;
-
- import java.io.IOException;
-
- /**
- * @Description:
- * @Auther: ztt
- * @Date: 2020/4/22 15:48
- */
- public class GaoDeMapUtil {
- public static void main(String[] args) {
- // 地址名称
- String address = "上海交通大学徐汇校区";
- // 刚刚申请的key。一定要换成你自己的key!!!!!!!
- String key = "aaaaaaaaaaaaaaa";
- // 调用自己写好的封装方法
- JSONObject positionObj = getLngAndLat(address, key);
- String longitude = positionObj.getString("longitude");
- String latitude = positionObj.getString("latitude");
- System.out.println("经度:" + longitude);
- System.out.println("纬度:" + latitude);
-
- }
-
- /**
- * 根据地址查询经纬度
- *
- * @param address
- * @param key
- * @return
- */
- public static JSONObject getLngAndLat(String address, String key) {
- JSONObject positionObj = new JSONObject();
-
- try {
- // 拼接请求高德的url
- String url = "http://restapi.amap.com/v3/geocode/geo?address=" + address + "&output=JSON&key=" + key;
- // 请求高德接口
- String result = sendHttpGet(url);
- JSONObject resultJOSN = JSONObject.parseObject(result);
- System.out.println("高德接口返回原始数据:");
- System.out.println(resultJOSN);
- JSONArray geocodesArray = resultJOSN.getJSONArray("geocodes");
- if (geocodesArray.size() > 0) {
- String position = geocodesArray.getJSONObject(0).getString("location");
- String[] lngAndLat = position.split(",");
- String longitude = lngAndLat[0];
- String latitude = lngAndLat[1];
- positionObj.put("longitude", longitude);
- positionObj.put("latitude", latitude);
- }
- geocodesArray.getJSONObject(0).getString("location");
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- return positionObj;
- }
-
- /**
- * 发送Get请求
- *
- * @param url
- * @return
- */
- public static String sendHttpGet(String url) {
- HttpGet httpGet = new HttpGet(url);
- RequestConfig defaultRequestConfig = RequestConfig.custom()
- .setConnectTimeout(3000)
- .setSocketTimeout(10000)
- .build();
- CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
- String result = "";
- try {
- CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpGet);
- HttpEntity entity = closeableHttpResponse.getEntity();
- result = EntityUtils.toString(entity, "UTF-8");
- } catch (IOException e) {
- e.printStackTrace();
- }
- return result;
- }
- }
代码:
- import com.alibaba.fastjson.JSONObject;
- import com.cxt.car.po.dto.address.Result;
- import com.cxt.car.util.baseUtils.JsonUtil;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.URL;
-
- /**
- * @Author: yansf
- * @Description:根据经纬度获取地址
- * @Date:Creat in 20:20 2019/12/11
- * @Modified By:
- */
- public class AddressUntils {
- static String secretKey = "此处是申请的key";
-
- /**
- * @param lat 纬度
- * @param lng 经度
- * @return
- */
- public static Result getAddress(String lat, String lng) throws IOException {
- JSONObject obj = getLocationInfo(lat, lng).getJSONObject("result");
- System.out.println(obj);
- Result result = JsonUtil.fromJson(obj.toString(), Result.class);
-
- return result;
- }
-
- public static JSONObject getLocationInfo(String lat, String lng) throws IOException {
- String urlString = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + lat + "," + lng + "&key=" + secretKey;
- System.out.println("请求经纬度url:" + urlString);
- URL url = new URL(urlString);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setDoInput(true);
- conn.setRequestMethod("GET");
- BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
- String line;
- String res = "";
- while ((line = in.readLine()) != null) {
- res += line + "\n";
- }
- in.close();
- JSONObject jsonObject = JSONObject.parseObject(res);
- return jsonObject;
- }
-
-
- public static void main(String[] args) throws IOException {
- Result address = getAddress("30.2084", "120.21201");
- System.out.println(address.ad_info.city);
-
- }
-
- }
【java自行修改一下格式】代码中用到的实体类就用下面这种方式转换即可

代码中还用到了一个工具类,将json转换成实体类
- import com.fasterxml.jackson.core.JsonProcessingException;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import java.io.IOException;
-
- /**
- * @Author: yansf
- * @Description:JSON工具类
- * @Date:Creat in 17:22 2019/12/10
- * @Modified By:
- */
- public class JsonUtil {
- private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);
-
- private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
-
- /**
- * 将POJO转换为JSON
- */
- public static
String toJson(T obj) { - String json;
- try {
- json = OBJECT_MAPPER.writeValueAsString(obj);
- } catch (JsonProcessingException e) {
- LOGGER.error("convert POJO to JSON failure", e);
- throw new RuntimeException(e);
- //e.printStackTrace();
- }
- return json;
- }
-
- /**
- * 将JSON转为POJO
- */
- public static
T fromJson(String json, Class type ) { - T pojo;
- try {
- pojo = OBJECT_MAPPER.readValue(json, type);
- } catch (IOException e) {
- LOGGER.error("convert JSON to POJO failure", e);
- throw new RuntimeException(e);
- //e.printStackTrace();
- }
- return pojo;
-
- }
- }
百度地图API
需求分析:
- 1.根据某一经纬度获取真实位置
- 2.根据某一位置获取经纬度
先创建BaiDuMapUnit工具类
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.UnsupportedEncodingException;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URLEncoder;
-
- import org.springframework.util.StringUtils;
-
- public class BaiDuMapUnit {
- /**
- * 输入地址返回经纬度坐标 key lng(经度),lat(纬度)
- */
- public static void getGeocoderLatitude(String address) {
- BufferedReader in = null;
- try {
- address = URLEncoder.encode(address, "UTF-8");
- URL tirc = new URL("http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&ak="
- + "wws9Qu73jw4QkOL6osEyIsA9Yob2yYgR"+"&callback=showLocation");
- in = new BufferedReader(new InputStreamReader(tirc.openStream(), "UTF-8"));
- String res;
- StringBuilder sb = new StringBuilder("");
- while ((res = in.readLine()) != null) {
- sb.append(res.trim());
- }
- String str = sb.toString();
- if (!StringUtils.isEmpty(str)) {
- int lngStart = str.indexOf("lng\":");
- int lngEnd = str.indexOf(",\"lat");
- int latEnd = str.indexOf("},\"precise");
- if (lngStart > 0 && lngEnd > 0 && latEnd > 0) {
- String lng = str.substring(lngStart + 5, lngEnd);
- String lat = str.substring(lngEnd + 7, latEnd);
- System.out.println("lng:" + lng + " lat:" + lat);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- in.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- /**
- * 输入经纬度返回地址 key lng(经度),lat(纬度)
- */
- public static void getPosition(String latitude, String longitude) throws MalformedURLException {
- BufferedReader in = null;
- URL tirc = new URL("http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=" + latitude + "," + longitude
- + "&output=json&pois=1&ak=" + "wws9Qu73jw4QkOL6osEyIsA9Yob2yYgR");
- try {
- in = new BufferedReader(new InputStreamReader(tirc.openStream(), "UTF-8"));
- String res;
- StringBuilder sb = new StringBuilder("");
- while ((res = in.readLine()) != null) {
- sb.append(res.trim());
- }
- String str = sb.toString();
- System.out.println(str);
- if (!StringUtils.isEmpty(str)) {
- int lngStart = str.indexOf("formatted_address\":\"");
- int lngEnd = str.indexOf("\",\"business");
- if (lngStart > 0 && lngEnd > 0 ) {
- String ads = str.substring(lngStart + 20, lngEnd);
- System.out.println("ads:" + ads);
- }
- }
-
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }