百度地图API-获得2个地方的距离



百度官方文档参考链接:

http://lbsyun.baidu.com/apiconsole/key

http://developer.baidu.com/map/index.php?title=webapi/direction-api



需要引入的jar包 jsoup

<dependency>

<groupId>org.jsoup</groupId>

<artifactId>jsoup</artifactId>

<version>1.8.1</version>

</dependency>


参考代码:

@Test

public void testDistance() throws IOException{

 

int  distance = getDistance_ThroughBaiduMapAPI("北京","故宫","重庆","鸳鸯");

System.out.println("-----");

System.out.println("--distance--:"+distance);

}

/***

* 获得2个地方的间距{单位:千米}

* 如果传入参数非法,那么返回-1

destination_region:目的地 所在的城市

*destination:目的地 名称

*origin_region :起始地 所在的城市

*origin :起始地 名称

* ***/ 

public int  getDistance_ThroughBaiduMapAPI(String destination_region,String destination,String origin_region ,String origin ) throws IOException{

String url="http://api.map.baidu.com/direction/v1?ak=wFB7i3Gw321GVI6Zdp7M4YVe&destination_region="

+destination_region+"&origin="+origin+"&origin_region="+origin_region

+"&output=xml&destination="+destination+"&mode=driving";

Document doc= Jsoup.connect(url).userAgent("Mozilla").timeout(5000).get();

Elements statusElements=doc.select("DirectionDrivingResponse status");

if(Integer.parseInt(statusElements.get(0).text() ) !=0){

return -1;

}

Elements distanceElements= null;

int type = Integer.parseInt(doc.select("DirectionDrivingResponse type").get(0).text() );

if(type==2){//起终点都是精确的

distanceElements = doc.select("DirectionDrivingResponse result routes distance");

return (int)Math.ceil( Integer.parseInt(distanceElements.get(0).text() )/1000.0 );

}else{//起终点是模糊的,此时给出的是选择页面,将地名转换成经纬度,默认选择第一个

 

Elements originElements = doc.select("DirectionDrivingResponse result origin content");

String originNew = originElements.get(new Random().nextInt(originElements.size()-1)).select("name").text().trim();

Elements destinationElements = doc.select("DirectionDrivingResponse result destination content");

String destinationNew = destinationElements.get(new Random().nextInt(destinationElements.size()-1)).select("name").text().trim();

return getDistance_ThroughBaiduMapAPI(destination_region,destinationNew,origin_region,originNew);

}

}


转载于:https://my.oschina.net/tinglanrmb32/blog/603239

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值