private static String getResponse(String serverUrl){
System.out.println(serverUrl);
try {
URL url = new URL(serverUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true); // 设置该连接是可以输出的
connection.setRequestMethod("GET"); // 设置请求方式
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line = null;
StringBuilder result = new StringBuilder();
while ((line = br.readLine()) != null) { // 读取数据
result.append(line + "\n");
}
connection.disconnect();
return result.toString();//返回值
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public static String getDistance(String startLonLat, String endLonLat,String city,String cityd){
String key = "你自己申请的key";
//返回起始地startAddr与目的地endAddr之间的距离,单位:米
String result = "";
String queryUrl = "https://restapi.amap.com/v3/distance?origins="+startLonLat+"&destination="+endLonLat+"&output=xml&key="+key+"&city="+city+"&cityd="+cityd+"&strategy=0&nightflag=0";
try {
String queryResult = getResponse(queryUrl);
System.out.println("++++++++++++++++++++++++++++++++++++++++++");
System.out.println(queryResult);
//截取距离长度结果值
String str = queryResult.substring(queryResult.indexOf("<distance>")+10,queryResult.indexOf("</distance>"));
System.out.println(str);
return str;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
官方链接:https://lbs.amap.com/api/javascript-api/guide/services/navigation
对应参数解释如下图: