Java调用高德地图API获取路线

高德地图API链接

地理/逆地理编码-基础 API 文档-开发指南-Web服务 API | 高德地图API (amap.com)

使用高德地图调用前,需要先注册登录控制台申请key

1.注册高德开发者账号并登录到控制台。

    有账号的直接登录,没有账户注册一个

注册账户,选择认证方式

注册成功后,登录到控制台,就能看见菜单功能栏

2.在控制台中创建一个应用,添加key,这个key请求接口时需要,先保存着。

为应用添加key

添加key成功后,复制保存这个key,留着

3.根据需求在API文档中选择合适的接口,地图显示,路线规划,地理/逆地理编码等。

4.以获取路线规划为例,Java代码示例如下。

获取路线的请求实体入参

@Data
public class GaoDeRouteRequest implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "用户在高德地图官网申请的Web服务API类型Key", required = true)
    private String key;
    @ApiModelProperty(value = "起点经纬度,经度在前,纬度在后,用逗号分割,经纬度小数点后不得超过6位", required = true)
    private String origin;
    @ApiModelProperty(value = "目的地,经度在前,纬度在后,用逗号分割,经纬度小数点后不得超过6位", required = true)
    private String destination;
    @ApiModelProperty(value = "终点的POI类别", required = false)
    private String destination_type;
    @ApiModelProperty(value = "目的地POI ID,目的地为POI时,建议填充此值", required = false)
    private String destination_id;
    @ApiModelProperty(value = "驾车算路策略", required = false, example = "32")
    private String strategy;
    @ApiModelProperty(value = "途经点坐标串,多个途径点以英文分号分隔", required = false)
    private String waypoints;
    @ApiModelProperty(value = "避让区域,多个区域以英文竖线分隔", required = false)
    private String avoidpolygons;
    @ApiModelProperty(value = "避让道路名,只支持一条避让道路", required = false)
    private String avoidroad;
    @ApiModelProperty(value = "车牌号码,支持6位传统车牌和7位新能源车牌", required = false)
    private String plate;
    @ApiModelProperty(value = "车辆类型,0:普通燃油汽车,1:纯电动汽车,2:插电式混动汽车", required = false, example = "0")
    private String cartype;
    @ApiModelProperty(value = "是否使用轮渡,0:使用渡轮,1:不使用渡轮", required = false, example = "0")
    private String ferry;

    /**
     * 返回结果控制
     * 1、具体可指定返回的字段类请见下方返回结果说明中的“show_fields”内字段类型
     * 2、多个字段间采用“,”进行分割;
     * 3、show_fields 未设置时,只返回基础信息类内字段
     */
    @ApiModelProperty(value = "返回结果控制,用来筛选response结果中可选字段,多个字段间用逗号分隔", required = false)
    private String show_fields;

    @ApiModelProperty(value = "数字签名", required = false)
    private String sig;

    @ApiModelProperty(value = "返回结果格式类型,可选值:JSON", required = false, example = "json")
    private String output = "json";

    @ApiModelProperty(value = "回调函数名称,此参数只在output参数设置为JSON时有效", required = false)
    private String callback;

}

获取路线返回的实体类

@Data
public class GaoDeRouteResponse implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "本次 API 访问状态,如果成功返回1,如果失败返回0。")
    private String status;

    @ApiModelProperty(value = "访问状态值的说明,如果成功返回\"ok\",失败返回错误原因,具体见 错误码说明。")
    private String info;

    @ApiModelProperty(value = "返回状态说明,10000代表正确,详情参阅 info 状态表")
    private String infocode;

    @ApiModelProperty(value = "路径规划方案总数")
    private String count;

    @ApiModelProperty(value = "返回的规划方案列表")
    private List<Route> route;

    @ApiModel(description = "规划方案实体")
    @Data
    public static class Route {
        @ApiModelProperty(value = "起点经纬度")
        private String origin;

        @ApiModelProperty(value = "终点经纬度")
        private String destination;

        @ApiModelProperty(value = "算路方案详情")
        private String taxi_cost;

        @ApiModelProperty(value = "路线列表")
        private List<Path> paths;

        @ApiModel(description = "路线实体")
        @Data
        public static class Path {
            @ApiModelProperty(value = "方案距离,单位:米")
            private String distance;

            @ApiModelProperty(value = "0 代表限行已规避或未限行,即该路线没有限行路段 1 代表限行无法规避,即该线路有限行路段")
            private String restriction;

            @ApiModelProperty(value = "线路耗时")
            private Cost cost;

            @ApiModel(description = "线路耗时实体")
            @Data
            public static class Cost {
                @ApiModelProperty(value = "线路耗时,")
                private String duration;

                @ApiModelProperty(value = "此路线道路收费,单位:元,包括分段信息")
                private String tolls;
            }

            @ApiModelProperty(value = "路线分段列表")
            private List<Step> steps;

            @ApiModel(description = "Route Segment")
            @Data
            public static class Step {
                @ApiModelProperty(value = "步行指示")
                private String instruction;

                @ApiModelProperty(value = "进入道路方向")
                private String orientation;

                @ApiModelProperty(value = "分段道路名称")
                private String road_name;

                @ApiModelProperty(value = "分段距离信息")
                private String step_distance;

                @ApiModelProperty(value = "设置后可返回分路段坐标点串,两点间用“;”分隔")
                private String polyline;

                @ApiModelProperty(value = "设置后可返回分段途径城市信息")
                private List<City> cities;

                @ApiModel(description = "城市信息实体")
                @Data
                public static class City {
                    @ApiModelProperty(value = "途径区域编码")
                    private String adcode;

                    @ApiModelProperty(value = "途径城市编码")
                    private String citycode;

                    @ApiModelProperty(value = "途径城市名称")
                    private String city;

                    @ApiModelProperty(value = "途径区县信息")
                    private List<District> districts;

                    @ApiModel(description = "途径区县信息实体")
                    @Data
                    public static class District {
                        @ApiModelProperty(value = "途径区县名称")
                        private String name;

                        @ApiModelProperty(value = "途径区县 adcode")
                        private String adcode;
                    }
                }
            }
        }
    }
}

调用方法

private String key = XXXXXX;//申请的key
private String show_fields = "cost,polyline,cities";//根据需要获取字段
private String url = "https://restapi.amap.com/v5/direction/driving";//url
public GaoDeRouteResponse getRoute(GaoDeRouteRequest request) {
	GaoDeRouteesponse response = new GaoDeRouteResponse();
	try {
		if(request==null){
			request = new GaoDeRouteRequest();
		}
		request.setKey(key);//提前申请好的key
		request.setShow_fields(show_fields);
		String param = ObjectFieldUtil.toGetParams(request);
		String s = HttpUtils.sendGet(url,param,"UTF-8");
		log.info("[高德路径][返回值]:{}",JsonUtil.getObjectToString(s));
		if(StringUtil.isNotEmpty(s)){
			response = JsonUtil.getJsonToBean(s,GaoDeRoutePlanningResponse.class);
			if(StringUtil.isNotNull(response)&& GaoDeCodeEnum.SUCCESS.getCode().equals(response.getStatus())&&StringUtil.isNotNull(response.getRoute())){
				return response;
			}else{
				if(StringUtil.isNotNull(response)&&GaoDeCodeEnum.SUCCESS.getCode().equals(response.getStatus())){
					log.info("[高德路径][无数据]:{}",JsonUtil.getObjectToString(response));
					return response;
				}else {
					log.info("[高德路径][异常]:{}");
				}
			}
		}
	}catch (Exception e){
		log.info("[高德路径][异常]:{}",e);
	}
	return response;
}

调用方法过程中需要的工具类,转换实体

@Slf4j
@Component
public class ObjectFieldUtil {

    public static String toGetParams(Object obj) {
        try {
            StringBuilder queryParams = new StringBuilder();
            Class<?> objClass = obj.getClass();
            Field[] fields = objClass.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Object value = null;
                value = field.get(obj);
                if (value != null) {
                    if (queryParams.length() > 0) {
                        queryParams.append("&");
                    }
                    queryParams.append(URLEncoder.encode(field.getName(), "UTF-8"))
                            .append("=")
                            .append(URLEncoder.encode(value.toString(), "UTF-8"));
                }
            }
            return queryParams.toString();
        }catch (IllegalAccessException e){
            log.info("[实体转换][异常]:{}", e);
        }catch (UnsupportedEncodingException e) {
            log.info("[实体转换][异常]:{}", e);
        }
        return "";
    }
}

调用方法过程中需要的工具类,发送请求工具

public static String sendGet(String url, String param, String contentType) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }
  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
请查看以下代码示例,这是使用高德地图API获取两个经纬度之间的路线公里数的示例代码: ```java import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class AmapApiExample { public static void main(String[] args) throws UnsupportedEncodingException { // 高德地图API的Web服务Key String apiKey = "你的高德地图API Web服务Key"; // 出发点的经纬度 String origin = "116.481028,39.989643"; // 目的地的经纬度 String destination = "116.434446,39.90816"; // 根据高德地图API的规定,将参数进行URL编码 String encodedOrigin = URLEncoder.encode(origin, "UTF-8"); String encodedDestination = URLEncoder.encode(destination, "UTF-8"); // 构造请求URL String url = "https://restapi.amap.com/v3/distance?origins=" + encodedOrigin + "&destination=" + encodedDestination + "&key=" + apiKey; // 发送HTTP请求,获取响应内容 OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = null; try { response = client.newCall(request).execute(); } catch (IOException e) { e.printStackTrace(); } // 解析响应内容,获取路线距离 if (response != null && response.isSuccessful()) { try { String responseString = response.body().string(); JSONObject responseJson = JSON.parseObject(responseString); JSONArray results = responseJson.getJSONArray("results"); if (results != null && !results.isEmpty()) { JSONObject result = results.getJSONObject(0); if (result != null) { int distance = result.getInteger("distance"); System.out.println("路线距离为:" + distance + "米"); } } } catch (IOException e) { e.printStackTrace(); } } } } ``` 请将代码中的`apiKey`替换为你自己申请的高德地图API Web服务Key,`origin`和`destination`替换为你要计算路线的两个经纬度,然后运行程序即可获取路线的公里数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值