您的位置:首页 > 其它

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

2016-01-15 00:00 253 查看
摘要: 百度地图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);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息