Java对接高德地图计算距离_JAVA 调用高德地图查询距离接口
高德上也有詳細的申請key的教程
這里需要一個最主要的jar包,就是https://files-cdn.cnblogs.com/files/java-pan/lib.rar,直接訪問,就下載了,解壓就可以使用了,
通過高德開放者平臺http://lbs.amap.com/,注冊一個開發者賬號,獲得一個KEY(查詢接口需要使用該KEY)
不多BB,上代碼
10.package com.ghxw.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Distance {
public static void main(String[] args){
String start = “浙江省杭州市西湖區”;
String end = “鄭州市金水區”;
String startLonLat = getLonLat(start);
String endLonLat = getLonLat(end);
System.out.println(startLonLat);
System.out.println(endLonLat);
Long dis = getDistance(startLonLat,endLonLat);
System.out.println(dis);
}
private static String getLonLat(String address){
//返回輸入地址address的經緯度信息, 格式是 經度,緯度
String queryUrl = "http://restapi.amap.com/v3/geocode/geo?key=87a008a2a8840856e03e714e3315901c&address="+address;
String queryResult = getResponse(queryUrl); //高德接品返回的是JSON格式的字符串
JSONObject jo = new JSONObject().fromObject(queryResult);
System.out.println("-=======================------");
System.out.println(jo.toString());
JSONArray ja = jo.getJSONArray("geocodes");
System.out.println(ja.toString());
return new JSONObject().fromObject(ja.getString(0)).get("location").toString();
}
private static Long getDistance(String startLonLat, String endLonLat){
//返回起始地startAddr與目的地endAddr之間的距離,單位:米
Long result = new Long(0);
String queryUrl = "http://restapi.amap.com/v3/distance?key=87a008a2a8840856e03e714e3315901c&origins="+startLonLat+"&destination="+endLonLat;
String queryResult = getResponse(queryUrl);
JSONObject jo = new JSONObject().fromObject(queryResult);
JSONArray ja = jo.getJSONArray("results");
result = Long.parseLong(new JSONObject().fromObject(ja.getString(0)).get("distance").toString());
return result;
// return queryResult;
}
private static String getResponse(String serverUrl){
//用JAVA發起http請求,并返回json格式的結果
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();
}
}
可以去驗證一下
總結
以上是生活随笔為你收集整理的Java对接高德地图计算距离_JAVA 调用高德地图查询距离接口的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows xp home edit
- 下一篇: 双极型晶体管(BJT)学习总结