• 基础(四)之java后端根据经纬度获取地址


    1.高德地图写法

    申请高德地图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

    1.     /**
    2.      *根据经纬度获取省市区
    3.      */
    4.     public static String getAddressStr(String log, String lat){
    5.         //lat 小  log  大
    6.         //参数解释: 纬度,经度 采用高德API可参考高德文档https://lbs.amap.com/
    7.         //注意key是在高德开放平台申请的key,具体获得key的步骤请查看网址:https://developer.amap.com/api/webservice/guide/create-project/get-key
    8.         String key = "个人申请的高德地图key";
    9.         String parameters="?key="+key;
    10. //        parameters+="&location="+"116.481488,39.990464";
    11.         parameters+="&location="+log+","+lat;//经纬度坐标
    12.         parameters+="&extensions=true";//返回结果控制,extensions 参数取值为 all 时会返回基本地址信息、附近 POI 内容、道路信息以及道路交叉口信息。
    13.         parameters+="&radius=10";//搜索半径,radius取值范围在0~3000,默认是1000。单位:米
    14.         parameters+="&batch=false";//批量查询控制,batch 参数设置为 false 时进行单点查询,此时即使传入多个经纬度也只返回第一个经纬度的地址解析查询结果。
    15.         parameters+="&roadlevel=0";//道路等级,当 roadlevel = 0 时,显示所有道路
    16. //        String urlString = "https://restapi.amap.com/v3/geocode/regeo?location="+lat+","+log+"&extensions=base&batch=false&roadlevel=0&key="+key;
    17.         String urlString = "https://restapi.amap.com/v3/geocode/regeo"+parameters;
    18.         StringBuilder res = new StringBuilder();
    19.         try {
    20.             URL url = new URL(urlString);
    21.             HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    22.             conn.setDoOutput(true);
    23.             conn.setRequestMethod("POST");
    24.             BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
    25.             String line;
    26.             while ((line = in.readLine()) != null) {
    27.                 res.append(line).append("\n");
    28.             }
    29.             in.close();
    30.             //解析结果
    31.             com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(res.toString());
    32.             System.out.println("jsonObject = " + jsonObject);
    33.             com.alibaba.fastjson.JSONObject jsonObject1 = jsonObject.getJSONObject("regeocode");
    34.             res = new StringBuilder(jsonObject1.getString("formatted_address"));
    35.         } catch (Exception e) {
    36.             System.out.println("获取地址信息异常");
    37.             e.printStackTrace();
    38.             return null;
    39.         }
    40.         System.out.println("通过API获取到具体位置:"+res);
    41.         return res.toString();
    42.     }

    代码根据地址获取经纬度

    1. <dependency>
    2. <groupId>com.alibabagroupId>
    3. <artifactId>fastjsonartifactId>
    4. <version>1.2.24version>
    5. dependency>
    6. <dependency>
    7. <groupId>org.apache.httpcomponentsgroupId>
    8. <artifactId>httpclientartifactId>
    9. dependency>

    代码如下:

    1. package ztt.map;
    2. import com.alibaba.fastjson.JSONArray;
    3. import com.alibaba.fastjson.JSONObject;
    4. import org.apache.http.HttpEntity;
    5. import org.apache.http.client.config.RequestConfig;
    6. import org.apache.http.client.methods.CloseableHttpResponse;
    7. import org.apache.http.client.methods.HttpGet;
    8. import org.apache.http.impl.client.CloseableHttpClient;
    9. import org.apache.http.impl.client.HttpClients;
    10. import org.apache.http.util.EntityUtils;
    11. import java.io.IOException;
    12. /**
    13. * @Description:
    14. * @Auther: ztt
    15. * @Date: 2020/4/22 15:48
    16. */
    17. public class GaoDeMapUtil {
    18. public static void main(String[] args) {
    19. // 地址名称
    20. String address = "上海交通大学徐汇校区";
    21. // 刚刚申请的key。一定要换成你自己的key!!!!!!!
    22. String key = "aaaaaaaaaaaaaaa";
    23. // 调用自己写好的封装方法
    24. JSONObject positionObj = getLngAndLat(address, key);
    25. String longitude = positionObj.getString("longitude");
    26. String latitude = positionObj.getString("latitude");
    27. System.out.println("经度:" + longitude);
    28. System.out.println("纬度:" + latitude);
    29. }
    30. /**
    31. * 根据地址查询经纬度
    32. *
    33. * @param address
    34. * @param key
    35. * @return
    36. */
    37. public static JSONObject getLngAndLat(String address, String key) {
    38. JSONObject positionObj = new JSONObject();
    39. try {
    40. // 拼接请求高德的url
    41. String url = "http://restapi.amap.com/v3/geocode/geo?address=" + address + "&output=JSON&key=" + key;
    42. // 请求高德接口
    43. String result = sendHttpGet(url);
    44. JSONObject resultJOSN = JSONObject.parseObject(result);
    45. System.out.println("高德接口返回原始数据:");
    46. System.out.println(resultJOSN);
    47. JSONArray geocodesArray = resultJOSN.getJSONArray("geocodes");
    48. if (geocodesArray.size() > 0) {
    49. String position = geocodesArray.getJSONObject(0).getString("location");
    50. String[] lngAndLat = position.split(",");
    51. String longitude = lngAndLat[0];
    52. String latitude = lngAndLat[1];
    53. positionObj.put("longitude", longitude);
    54. positionObj.put("latitude", latitude);
    55. }
    56. geocodesArray.getJSONObject(0).getString("location");
    57. } catch (Exception e) {
    58. e.printStackTrace();
    59. }
    60. return positionObj;
    61. }
    62. /**
    63. * 发送Get请求
    64. *
    65. * @param url
    66. * @return
    67. */
    68. public static String sendHttpGet(String url) {
    69. HttpGet httpGet = new HttpGet(url);
    70. RequestConfig defaultRequestConfig = RequestConfig.custom()
    71. .setConnectTimeout(3000)
    72. .setSocketTimeout(10000)
    73. .build();
    74. CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
    75. String result = "";
    76. try {
    77. CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpGet);
    78. HttpEntity entity = closeableHttpResponse.getEntity();
    79. result = EntityUtils.toString(entity, "UTF-8");
    80. } catch (IOException e) {
    81. e.printStackTrace();
    82. }
    83. return result;
    84. }
    85. }

    腾讯

    官网:腾讯位置服务 - 立足生态,连接未来

    代码:

    1. import com.alibaba.fastjson.JSONObject;
    2. import com.cxt.car.po.dto.address.Result;
    3. import com.cxt.car.util.baseUtils.JsonUtil;
    4. import java.io.BufferedReader;
    5. import java.io.IOException;
    6. import java.io.InputStreamReader;
    7. import java.net.HttpURLConnection;
    8. import java.net.URL;
    9. /**
    10. * @Author: yansf
    11. * @Description:根据经纬度获取地址
    12. * @Date:Creat in 20:20 2019/12/11
    13. * @Modified By:
    14. */
    15. public class AddressUntils {
    16. static String secretKey = "此处是申请的key";
    17. /**
    18. * @param lat 纬度
    19. * @param lng 经度
    20. * @return
    21. */
    22. public static Result getAddress(String lat, String lng) throws IOException {
    23. JSONObject obj = getLocationInfo(lat, lng).getJSONObject("result");
    24. System.out.println(obj);
    25. Result result = JsonUtil.fromJson(obj.toString(), Result.class);
    26. return result;
    27. }
    28. public static JSONObject getLocationInfo(String lat, String lng) throws IOException {
    29. String urlString = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + lat + "," + lng + "&key=" + secretKey;
    30. System.out.println("请求经纬度url:" + urlString);
    31. URL url = new URL(urlString);
    32. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    33. conn.setDoInput(true);
    34. conn.setRequestMethod("GET");
    35. BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
    36. String line;
    37. String res = "";
    38. while ((line = in.readLine()) != null) {
    39. res += line + "\n";
    40. }
    41. in.close();
    42. JSONObject jsonObject = JSONObject.parseObject(res);
    43. return jsonObject;
    44. }
    45. public static void main(String[] args) throws IOException {
    46. Result address = getAddress("30.2084", "120.21201");
    47. System.out.println(address.ad_info.city);
    48. }
    49. }

    【java自行修改一下格式】代码中用到的实体类就用下面这种方式转换即可

    代码中还用到了一个工具类,将json转换成实体类

    1. import com.fasterxml.jackson.core.JsonProcessingException;
    2. import com.fasterxml.jackson.databind.ObjectMapper;
    3. import org.slf4j.Logger;
    4. import org.slf4j.LoggerFactory;
    5. import java.io.IOException;
    6. /**
    7. * @Author: yansf
    8. * @Description:JSON工具类
    9. * @Date:Creat in 17:22 2019/12/10
    10. * @Modified By:
    11. */
    12. public class JsonUtil {
    13. private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);
    14. private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    15. /**
    16. * 将POJO转换为JSON
    17. */
    18. public static String toJson(T obj) {
    19. String json;
    20. try {
    21. json = OBJECT_MAPPER.writeValueAsString(obj);
    22. } catch (JsonProcessingException e) {
    23. LOGGER.error("convert POJO to JSON failure", e);
    24. throw new RuntimeException(e);
    25. //e.printStackTrace();
    26. }
    27. return json;
    28. }
    29. /**
    30. * 将JSON转为POJO
    31. */
    32. public static T fromJson(String json, Class type) {
    33. T pojo;
    34. try {
    35. pojo = OBJECT_MAPPER.readValue(json, type);
    36. } catch (IOException e) {
    37. LOGGER.error("convert JSON to POJO failure", e);
    38. throw new RuntimeException(e);
    39. //e.printStackTrace();
    40. }
    41. return pojo;
    42. }
    43. }

    百度地图API

    需求分析:

    1. 1.根据某一经纬度获取真实位置
    2. 2.根据某一位置获取经纬度

    先创建BaiDuMapUnit工具类

    1. import java.io.BufferedReader;
    2. import java.io.IOException;
    3. import java.io.InputStreamReader;
    4. import java.io.UnsupportedEncodingException;
    5. import java.net.MalformedURLException;
    6. import java.net.URL;
    7. import java.net.URLEncoder;
    8. import org.springframework.util.StringUtils;
    9. public class BaiDuMapUnit {
    10. /**
    11. * 输入地址返回经纬度坐标 key lng(经度),lat(纬度)
    12. */
    13. public static void getGeocoderLatitude(String address) {
    14. BufferedReader in = null;
    15. try {
    16. address = URLEncoder.encode(address, "UTF-8");
    17. URL tirc = new URL("http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&ak="
    18. + "wws9Qu73jw4QkOL6osEyIsA9Yob2yYgR"+"&callback=showLocation");
    19. in = new BufferedReader(new InputStreamReader(tirc.openStream(), "UTF-8"));
    20. String res;
    21. StringBuilder sb = new StringBuilder("");
    22. while ((res = in.readLine()) != null) {
    23. sb.append(res.trim());
    24. }
    25. String str = sb.toString();
    26. if (!StringUtils.isEmpty(str)) {
    27. int lngStart = str.indexOf("lng\":");
    28. int lngEnd = str.indexOf(",\"lat");
    29. int latEnd = str.indexOf("},\"precise");
    30. if (lngStart > 0 && lngEnd > 0 && latEnd > 0) {
    31. String lng = str.substring(lngStart + 5, lngEnd);
    32. String lat = str.substring(lngEnd + 7, latEnd);
    33. System.out.println("lng:" + lng + " lat:" + lat);
    34. }
    35. }
    36. } catch (Exception e) {
    37. e.printStackTrace();
    38. } finally {
    39. try {
    40. in.close();
    41. } catch (IOException e) {
    42. e.printStackTrace();
    43. }
    44. }
    45. }
    46. /**
    47. * 输入经纬度返回地址 key lng(经度),lat(纬度)
    48. */
    49. public static void getPosition(String latitude, String longitude) throws MalformedURLException {
    50. BufferedReader in = null;
    51. URL tirc = new URL("http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=" + latitude + "," + longitude
    52. + "&output=json&pois=1&ak=" + "wws9Qu73jw4QkOL6osEyIsA9Yob2yYgR");
    53. try {
    54. in = new BufferedReader(new InputStreamReader(tirc.openStream(), "UTF-8"));
    55. String res;
    56. StringBuilder sb = new StringBuilder("");
    57. while ((res = in.readLine()) != null) {
    58. sb.append(res.trim());
    59. }
    60. String str = sb.toString();
    61. System.out.println(str);
    62. if (!StringUtils.isEmpty(str)) {
    63. int lngStart = str.indexOf("formatted_address\":\"");
    64. int lngEnd = str.indexOf("\",\"business");
    65. if (lngStart > 0 && lngEnd > 0 ) {
    66. String ads = str.substring(lngStart + 20, lngEnd);
    67. System.out.println("ads:" + ads);
    68. }
    69. }
    70. } catch (UnsupportedEncodingException e) {
    71. e.printStackTrace();
    72. } catch (IOException e) {
    73. e.printStackTrace();
    74. }
    75. }
    76. }

  • 相关阅读:
    使用 promise 重构 Android 异步代码
    Kingbase+sqlsugar 携手助力医疗国产化替换 【人大金仓 .NET ORM】
    代码随想录算法训练营第四天 | leetcode19、24、142、面试题02.07
    【论文解析】笔触渲染生成 前沿工作梳理
    时间序列分析(12)| 脉冲响应函数、格兰杰因果检验
    KNN算法回归问题介绍和实现
    java sql字符串解析
    阿里云服务器上安装docker命令记录
    服务治理的狭义治理和广义治理介绍
    【性能测试】Jmeter+InfluxDB+Grafana 搭建性能监控平台
  • 原文地址:https://blog.csdn.net/weixin_53998054/article/details/126174533