springboot整合高德地图

221900309何晨康 学生 2022-06-26 10:45:10

目录

  • 技术概述
  • 技术详述
  • 环境搭建
  • 添加依赖
  • 编写地图工具类
  • 调用工具类
  • 遇到的问题
  • 解决过程
  • 总结
  • 参考资料

技术概述

高德API向开发者提供HTTP接口,开发者可通过这些接口使用各类型的地理数据服务,返回结果支持JSON和XML格式。在springboot中整合高德地图API,可以轻松实现地址定位、距离计算等功能。

技术详述

环境搭建

首先需要在高德开发平台上进行注册,并实名认证。然后在控制台中创建新的应用并为应用添加Key:

在这里插入图片描述


因为要在springboot中向高德地图API发送请求,因此服务平台选择Web服务

在这里插入图片描述

添加依赖

这里主要是引入了fastjson:

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>

编写地图工具类

MapUtils类中包含getLocationgetRealAddressgetResponse三个方法。
getLocation方法通过 HTTP 协议访问远程服务的地址编码接口,并从返回的json中将需要的location(经纬度)截取出来,从而实现将地址与经纬度信息之间的转化:

    public String getLocation(String address) {
        String url,query,result;
        JSONObject temp,jsonObject;
        try {
            url = "http://restapi.amap.com/v3/place/around?key=" + Map_KEY
            +"&location="+LONTITUDE+","+LATITUDE+"&radius=50000&keywords=" + address;
            query = getResponse(url);
            temp = JSONObject.parseObject(query);
            String[] pois = temp.get("pois").toString().split("},\\{");
            jsonObject = JSONObject.parseObject(pois[0].substring(1) + "}");
            result = jsonObject.get("location").toString();
        }
        catch(Exception e) {
            url = "http://restapi.amap.com/v3/geocode/geo?key=" + Map_KEY 
            + "&address=" + address;
            query = getResponse(url);
            temp = JSONObject.parseObject(query);
            jsonObject = JSONObject.parseObject(temp.get("geocodes")
            .toString().substring(1, temp.get("geocodes").toString().length() - 1));
            result = jsonObject.get("location").toString();
        }
        return result;
    }

同理,getRealAddress方法向API发送请求,并从返回的json中将查询到的地址截取出来,实现用户模糊搜索的地址向具体地址的转化:

    public String getRealAddress(String address) {
        String url,query,result;
        JSONObject temp,jsonObject;
        try {
            url = "http://restapi.amap.com/v3/place/around?key=" + Map_KEY
             + "&location="+LONTITUDE+","+LATITUDE+"&radius=50000&keywords=" + address;
            query = getResponse(url);
            temp = JSONObject.parseObject(query);
            String[] pois = temp.get("pois").toString().split("},\\{");
            jsonObject = JSONObject.parseObject(pois[0].substring(1) + "}");
            if(!jsonObject.get("address").toString().equals("[]")){
                result = jsonObject.get("address").toString()+jsonObject.get("name").toString();
            }
            else{
                result = jsonObject.get("adname").toString()+jsonObject.get("name").toString();
            }
        }
        catch(Exception e) {
            url = "http://restapi.amap.com/v3/geocode/geo?key=" + Map_KEY + "&address=" + address;
            query= getResponse(url);
            temp = JSONObject.parseObject(query);
            jsonObject = JSONObject.parseObject(temp.get("geocodes").toString()
            .substring(1, temp.get("geocodes").toString().length() - 1));
            result = jsonObject.get("formatted_address").toString();
        }
        return result;
    }

getResponse方法通过URLConnection发送http网络请求,并以输入流的形式获取返回的json格式结果:

    private static String getResponse(String serverUrl) {
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

调用工具类

编写好工具类后,通过工具类的调用即可处理前端传来的数据并返回处理结果:

    public CommonResult getLocation(String address) {
        try {
            String result = MapUtil.getLocation(address);
            String location[]=result.split(",");
            Location loc=new Location();
            loc.setLongtitude(Double.parseDouble(location[0].substring(0)));
            loc.setLatitude(Double.parseDouble(location[1].substring(0)));
            String newAddress = MapUtil.getRealAddress(address);
            loc.setAddress(newAddress);
            return CommonResult.success(loc,"success");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("获取经纬度失败");
        }
    }

遇到的问题

因为我们团队项目是关于福大校园App,因此我们的想法是将用户通过地图搜索功能能够优先返回福大周边地区,而如果直接使用高德地图api提供的地址编码会使得搜索不够精确。而如果使用高德地图的周边服务搜索又会导致搜索范围太小,很多地点无法检索。

解决过程

首先通过请求以下url对福大周边地区进行搜索:
https://restapi.amap.com/v3/place/around?parameters
使用locationradius作为请求参数:

参数名含义规则说明是否必须缺省值
location中心点坐标规则: 经度和纬度用","分割,经度在前,纬度在后,经纬度小数点后不得超过6位必填
radius查询半径取值范围:0-50000。规则:大于50000按默认值,单位:米可选3000

若请求结果为空,则继续请求地址编码url来扩大搜索范围:
https://restapi.amap.com/v3/geocode/geo?parameters

使用请求参数city可以对查询范围进行限制:

参数名含义规则说明是否必须缺省值
city指定查询的城市指定城市,当指定城市查询内容为空时,会进行全国范围内的地址转换检索。可选无,会进行全国范围内搜索

总结

  • 高德地图为开发者提供了许多功能齐全、简单易用的api,通过对这些api进行整合能快速地开发地图相关功能,为开发者提供便利;此外,根据用户需求也可以定制API的功能。
  • 在学习一门新知识的过程中,需要善于阅读官方文档,官方文档具有权威性和准确性,相比于网络中的教程,从文档中能获取更全面的信息,并且不会出错。

参考资料

高德地图API文档

...全文
2071 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

142

社区成员

发帖
与我相关
我的任务
社区描述
2022年福大-软件工程;软件工程实践-W班
软件工程 高校
社区管理员
  • FZU_SE_teacherW
  • 丝雨_xrc
  • Lyu-
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧