怎样在java中调用百度地图的API

2020-06-16 科技 99阅读
百度地图Web服务API为开发者提供http接口,即开发者通过http形式发起检索请求,获取返回json或xml格式的检索数据。
api官网说明链接:
http://developer.baidu.com/map/webservice.htm
1、可用接口列举:
获取相关地址提示 place suggestion
http://api.map.baidu.com/place/v2/suggestion?query=水杉®ion=成都&output=json&ak=42b8ececa9cd6fe72ae4cddd77c0da5d
2、获取坐标 geocoding

http://api.map.baidu.com/geocoder?address=锦江区菱安路299号&output=json&key=42b8ececa9cd6fe72ae4cddd77c0da5d
http://api.map.baidu.com/place/v2/search?ak=42b8ececa9cd6fe72ae4cddd77c0da5d&output=json&query=蓝光coco金沙&page_size=10&page_num=0&scope=1®ion=成都
{
"status":0,
"message":"ok",
"total":2,
"results":[
{
"name":"蓝光COCO金沙",
"location":{
"lat":30.687544,
"lng":103.996691
},
"address":"西三环外金沙西源大道(IT大道旁)",
"uid":"223992992c5ee7e0841541df"
},
{
"name":"蓝光COCO金沙2期",
"location":{
"lat":30.681123,
"lng":103.991123
},
"address":"青羊区金沙IT大道旁",
"uid":"b7bb5abb1cd4982213293580"
}
]
}
3、设施导航
http://api.map.baidu.com/place/v2/search?ak=42b8ececa9cd6fe72ae4cddd77c0da5d&output=json&query=图书馆&page_size=20&page_num=0&scope=2®ion=成都
4、java测试类:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class LocationUtil {
private static final String BAIDU_APP_KEY = "42b8ececa9cd6fe72ae4cddd77c0da5d";

/**
* 返回输入地址的经纬度坐标 key lng(经度),lat(纬度)
*/
public static Map getLatitude(String address) {
try {
// 将地址转换成utf-8的16进制
address = URLEncoder.encode(address, "UTF-8");
// 如果有代理,要设置代理,没代理可注释
// System.setProperty("http.proxyHost","192.168.172.23");
// System.setProperty("http.proxyPort","3209");
URL resjson = new URL("http://api.map.baidu.com/geocoder?address="
+ address + "&output=json&key=" + BAIDU_APP_KEY);
BufferedReader in = new BufferedReader(new InputStreamReader(
resjson.openStream()));
String res;
StringBuilder sb = new StringBuilder("");
while ((res = in.readLine()) != null) {
sb.append(res.trim());
}
in.close();
String str = sb.toString();
System.out.println("return json:" + str);
if(str!=null&&!str.equals("")){
Map map = null;
int lngStart = str.indexOf("lng\":");
int lngEnd = str.indexOf(",\"lat");
int latEnd = str.indexOf("},\"precise");
if (lngStart > 0 && lngEnd > 0 && latEnd > 0) {
String lng = str.substring(lngStart + 5, lngEnd);
String lat = str.substring(lngEnd + 7, latEnd);
map = new HashMap();
map.put("lng", lng);
map.put("lat", lat);
return map;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String args[]) {

Map map = LocationUtil.getLatitude("成都 高新西区西区大道1398号");
if (null != map) {
System.out.println(map.get("lng"));
System.out.println(map.get("lat"));
}
}
}
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com