要使用高德地图API来计算两个城市之间的距离,你需要首先在高德开放平台上注册并获取API密钥(AK)。以下是一个使用Java调用高德地图API来计算两个城市之间距离的示例代码。
步骤 1: 获取高德地图API密钥
访问高德开放平台(https://lbs.amap.com/),注册并创建应用,然后获取API密钥(AK)。
步骤 2: Java代码实现
org.json库来解析JSON响应。请确保你的项目中包含了org.json库
maven项目在pom文件中引入
<dependency><groupId>org.json</groupId><artifactId>json</artifactId><version>20231013</version>
</dependency>
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;/*** description: DistanceCalculator* date: 2024/6/19 3:16 PM** @author: zhang jie*/public class DistanceCalculator {public static String geocode(String address1, String address2, String apiKey) {try {// 计算第一个地址的经纬度String origins = getLocationByAddress(address1, apiKey);if (origins == null) {return "找不到结果";}// 计算第二个地址的经纬度String destination = getLocationByAddress(address2, apiKey);if (destination == null) {return "找不到结果";}// 计算两个经纬度之间的距离String distance = getDistance(origins, destination, apiKey);if (distance == null) {return "找不到结果";}return address1 + " 到 " + address2 + " 的距离 " + distance + " 米";} catch (Exception e) {e.printStackTrace();return "请求过程中出现错误";}}private static String getLocationByAddress(String address, String apiKey) throws Exception {String urlString = String.format("https://restapi.amap.com/v3/geocode/geo?address=%s&key=%s",address, apiKey);JSONObject responseJson = new JSONObject(sendGetRequest(urlString));if (!"1".equals(responseJson.getString("status"))) return null;JSONArray geocodes = responseJson.getJSONArray("geocodes");return geocodes.getJSONObject(0).getString("location");}private static String getDistance(String origins, String destination, String apiKey) throws Exception {String urlString = String.format("https://restapi.amap.com/v3/distance?origins=%s&destination=%s&output=json&key=%s",origins, destination, apiKey);JSONObject responseJson = new JSONObject(sendGetRequest(urlString));if (!"1".equals(responseJson.getString("status"))) {return null;}JSONArray results = responseJson.getJSONArray("results");return results.getJSONObject(0).getString("distance");}private static String sendGetRequest(String urlString) throws Exception {URL url = new URL(urlString);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));String inputLine;StringBuilder response = new StringBuilder();while ((inputLine = in.readLine()) != null) {response.append(inputLine);}in.close();return response.toString();}public static void main(String[] args) {String address1 = "成都市";String address2 = "巴中市";String apiKey = "YOUR_AMAP_API_KEY"; // 使用你的高德地图API密钥替换System.out.println(geocode(address1, address2, apiKey));}
}
注意事项
- 确保你的API密钥安全,不要在公共代码库中暴露它。
- 使用高德地图API可能涉及费用,请查看高德开放平台的定价信息。
- 本示例仅用于演示如何使用Java调用外部API,实际应用中需要处理更多的异常情况和错误处理。