Java后台根据地理位置获取经纬度信息(百度地图)

1. 引入依赖包

<!-- 引入HttpClient依赖 -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>

2. 在yml中配置百度地图AK和地理编码

AK自己去百度地图注册获取:
地址:http://lbsyun.baidu.com/apiconsole/key#/home

#百度地图 AK
baidu:
  ak: oFj38PSnGlgyr2LGeBhx0bN1FhGOGi0B
  url: http://api.map.baidu.com/geocoding/v3/?output=json&location=showLocation
  rurl: http://api.map.baidu.com/reverse_geocoding/v3/?output=json&coordtype=BD09&pois=1

3.创建返回地理位置信息实体类

package com.kenner.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
* @author MYM_ZUOYAN
* @version 2.0
* @date 2021/4/9 15:03
* 位置信息返回实体类
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ReturnLocationBean implements Serializable {

   private static final Long serializableValue = 1L;


   /**
    * 地理位置
    */
   private String formattedAddress;


   /**
    * 经度
    */
   private Double lng;

   /**
    * 纬度
    */
   private Double lat;

   /**
    * 品级
    */
   private String level;
}

4.控制层编写

1.获取yml配置中的百度 AK、地理编码 URL、逆地理编码 URL

	/**
     * 百度 AK
     */
    @Value("${baidu.ak}")
    private String AK;

    /**
     * 地理编码 URL
     */
    @Value("${baidu.url}")
    private String ADDRESS_TO_LONGITUDEA_URL;

    /**
     * 逆地理编码 URL
     */
    @Value("${baidu.rurl}")
    private String LONGITUDE_TO_ADDRESS_URL;

2.根据地理位置获取经纬度

	/**
     * @param address
     * 根据地理位置获取经纬度信息
     * @return
     */
    @SysOperationLog(operType = "查询", operDesc = "根据地理位置获取经纬度信息")
    @PostMapping("/addressToLngLat")
    public JsonResult addressToLngLat(String address) {
        JsonResult result = new JsonResult();

        if (StringUtils.isBlank(address)) {
            result.error("地理位置不能为空!", null, StatusCode.ERROR);
        } else {
            String url = ADDRESS_TO_LONGITUDEA_URL + "&ak=" + AK + "&address=" + address;
            // 创建默认http连接
            HttpClient client = HttpClients.createDefault();

            //创建一个post请求
            HttpPost post = new HttpPost(url);

            try {
                // 用http连接去执行get请求并且获得http响应
                HttpResponse response = client.execute(post);

                // 从response中取到响实体
                HttpEntity entity = response.getEntity();

                // 把响应实体转成文本
                String html = EntityUtils.toString(entity);

                //转Json实体
                JSONObject jsonObject = JSON.parseObject(html);

                //地理信息实体封装
                ReturnLocationBean locationBean = new ReturnLocationBean();
                locationBean.setLng(jsonObject.getJSONObject("result").getJSONObject("location").getDouble("lng"));
                locationBean.setLat(jsonObject.getJSONObject("result").getJSONObject("location").getDouble("lat"));
                locationBean.setLevel(jsonObject.getJSONObject("result").getString("level"));
                locationBean.setFormattedAddress(address);

                result.markSuccess("查询成功!", locationBean, StatusCode.OK);
            } catch (Exception e) {
                result.error("查询失败!", null, StatusCode.ERROR);;
            }
        }

        return result;
    }

3.根据经纬度获取地理位置

	/**
     * 逆地理编码,根据经纬度获取地理位置
     * @param lat
     * @param lng
     * @return
     */
    @SysOperationLog(operType = "查询", operDesc = "根据经纬度获取地理位置")
    @PostMapping("/longitudeToAddress")
    public JsonResult longitudeToAddress(float lat, float lng) {
        JsonResult result = new JsonResult();

        String url = LONGITUDE_TO_ADDRESS_URL + "&ak=" + AK + "&location=" + lat + "," + lng;
        // 创建默认http连接
        HttpClient client = HttpClients.createDefault();

        // 创建一个post请求
        HttpPost post = new HttpPost(url);

        try {
            // 用http连接去执行get请求并且获得http响应
            HttpResponse response = client.execute(post);

            // 从response中取到响实体
            HttpEntity entity = response.getEntity();

            // 把响应实体转成文本
            String html = EntityUtils.toString(entity);

            //转Json实体
            JSONObject jsonObject = JSON.parseObject(html);

            //地理信息实体封装
            ReturnLocationBean locationBean = new ReturnLocationBean();
            locationBean.setLng((double) lng);
            locationBean.setLat((double) lat);
            locationBean.setFormattedAddress(jsonObject.getJSONObject("result").getString("formatted_address"));

            result.markSuccess("查询成功!", locationBean, StatusCode.OK);
        } catch (Exception e) {
            result.error("查询失败!", null, StatusCode.ERROR);
        }

        return result;
    }

完结!!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mym_zuoyan_Tmac

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值