申请高德地图Key
https://developer.amap.com/api/faq/quota-key/key/39669
获取地理位置名称示例代码:
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class GeoLocationToAddress {
private static final String API_URL = "https://restapi.amap.com/v3/geocode/regeo";
private static final String KEY = "xxxxxxxxxxxxxxxxxxxxxxxx";
public static Map getAddressInfo(double longitude, double latitude) {
String parameters = "?key=" + KEY;
parameters += "&location=" + longitude + "," + latitude;
parameters += "&extensions=all";
parameters += "&output=JSON";
String urlString = API_URL + parameters;
StringBuilder res = new StringBuilder();
Map map = new HashMap<>();
try {
log.info("Amap API Request URL: " + urlString);
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = in.readLine()) != null) {
res.append(line);
}
in.close();
log.info("Map API Response: " + res);
JSONObject json = JSONObject.parseObject(res.toString());
if ("1".equals(json.getString("status"))) {
JSONObject regeocode = json.getJSONObject("regeocode");
JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
String address = regeocode.getString("formatted_address");
String province = addressComponent.getString("province");
String city = addressComponent.getString("city");
String district = addressComponent.getString("district");
map.put("address", address);
map.put("province", province);
map.put("city", city);
map.put("district", district);
return map;
} else {
log.info("Map API Response Error: " + json.getString("info"));
}
} catch (Exception e) {
log.info("Error getting address information");
e.printStackTrace();
}
return map;
}
public static void main(String[] args) {
double longitude = 108.257065;
double latitude = 33.033650;
Map addressInfo = getAddressInfo(longitude, latitude);
System.out.println(longitude+","+latitude+"的城市区县为:"+addressInfo);
System.out.println("city: " + addressInfo.get("city"));
System.out.println("district: " + addressInfo.get("district"));
System.out.println("address: " + addressInfo.get("address"));
}
}
了解更多内容 关注公众号