package com.hollywood.applet.utils; import org.codehaus.jettison.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class AmapGeocoding { private static final String AMAP_GEOCODING_API = "https://restapi.amap.com/v3/geocode/regeo"; private static final String AMAP_KEY = "116e73b6d14f7da0292daa6037955749"; // 替换为你的高德地图API Key public static String getCityCode(double latitude, double longitude) throws Exception { String url = AMAP_GEOCODING_API + "?location=" + longitude + "," + latitude + "&output=json&key=" + AMAP_KEY + "&radius=1000&extensions=all"; HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); connection.disconnect(); JSONObject jsonObject = new JSONObject(response.toString()); if ("1".equals(jsonObject.getString("status"))) { JSONObject regeocode = jsonObject.getJSONObject("regeocode"); JSONObject addressComponent = regeocode.getJSONObject("addressComponent"); String cityCode = addressComponent.getString("adcode"); // adcode即为citycode return cityCode; } else { throw new RuntimeException("Failed to fetch city code. Error message: " + jsonObject.getString("info")); } } public static String getCityName(double latitude, double longitude) throws Exception { String url = AMAP_GEOCODING_API + "?location=" + longitude + "," + latitude + "&output=json&key=" + AMAP_KEY + "&radius=1000&extensions=all"; HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); connection.disconnect(); JSONObject jsonObject = new JSONObject(response.toString()); if ("1".equals(jsonObject.getString("status"))) { JSONObject regeocode = jsonObject.getJSONObject("regeocode"); JSONObject addressComponent = regeocode.getJSONObject("addressComponent"); String cityName = addressComponent.getString("city"); // 这里改为了获取城市名称 return cityName; } else { throw new RuntimeException("Failed to fetch city name. Error message: " + jsonObject.getString("info")); } } public static void main(String[] args) throws Exception { double lat = 116.3913; // 纬度 double lng = 39.90539; // 经度 System.out.println("City Code: " + getCityCode(lat, lng)); } }