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;
    }

完结!!

  • 0
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
您可以使用百度地图API的地理编码服务实现该功能,具体步骤如下: 1. 创建百度开发者账号并申请地图API权限。 2. 在Java项目中引入百度地图API的Java SDK。 3. 调用地理编码服务的API,传入地址参数即可获取对应的经纬度信息。 以下是Java代码示例: ``` import com.baidu.mapapi.SDKInitializer; import com.baidu.mapapi.model.LatLng; import com.baidu.mapapi.utils.CoordinateConverter; import com.baidu.mapapi.utils.CoordinateConverter.CoordType; import com.baidu.mapapi.utils.HttpUtil; public class GeoCoder { private static final String GEOCODER_URL = "http://api.map.baidu.com/geocoder/v2/"; private static final String AK = "your_ak"; // 替换成申请的AK public static LatLng getLatLng(String address) { String url = GEOCODER_URL + "?address=" + address + "&output=json&ak=" + AK; String response = HttpUtil.get(url, "utf-8"); JSONObject jsonObject = JSONObject.parseObject(response); int status = jsonObject.getInteger("status"); if (status == 0) { JSONObject result = jsonObject.getJSONObject("result"); JSONObject location = result.getJSONObject("location"); double lat = location.getDouble("lat"); double lng = location.getDouble("lng"); // 将百度地图坐标转换为GPS坐标 LatLng baiduLatLng = new LatLng(lat, lng); CoordinateConverter converter = new CoordinateConverter(); converter.from(CoordType.COMMON); converter.coord(baiduLatLng); LatLng gpsLatLng = converter.convert(); return gpsLatLng; } else { return null; } } } ``` 其中,AK是百度地图API的密钥,需要替换成您自己申请的密钥。该代码实现了将百度地图坐标转换为GPS坐标,如果不需要转换可以去掉相应的代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 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、付费专栏及课程。

余额充值