在开发中,有时候需要根据经纬度来获取对应的区县信息,这可以通过调用高德地图的API来实现。本篇文章将介绍如何使用Java代码调用高德地图API来根据经纬度获取区县信息。
前提条件
首先,你需要注册一个高德地图开发者账号,并获取到API Key。API Key 将用于向高德地图发送请求以获取区县信息。
代码实现
以下是一个使用 Java 代码调用高德地图 API 的示例代码:
package com.sgnbs.web.utils;
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;
@Slf4j
public class GeoLocationToAddress {
private static final String API_URL = "https://restapi.amap.com/v3/geocode/regeo";
private static final String KEY = "YOUR_API_KEY_HERE";
public static String getProvinceCityDistrict(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();
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 province = addressComponent.getString("province");
String city = addressComponent.getString("city");
String district = addressComponent.getString("district");
return "City:" + city + ", District:" + district;
} else {
log.info("Map API Response Error: " + json.getString("info"));
}
} catch (Exception e) {
log.info("Error getting address information");
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
double longitude = 123.429441;
double latitude = 41.83544;
String addressInfo = getProvinceCityDistrict(longitude, latitude);
String[] parts = addressInfo.split(", "); // 拆分成 "City:大连市" 和 "District:甘井子区"
String city = "";
String district = "";
for (String part : parts) {
if (part.startsWith("City:")) {
city = part.substring("City:".length()); // 获取 "市"
} else if (part.startsWith("District:")) {
district = part.substring("District:".length()); // 获取 "区"
}
}
System.out.println(longitude+","+latitude+"的城市区县为:"+addressInfo);
System.out.println("City: " + city);
System.out.println("District: " + district);
}
}
请注意将
YOUR_API_KEY_HERE
替换为你实际的 API Key。
总结
通过以上代码,你可以轻松地使用 Java 调用高德地图 API 来获取经纬度对应的区县信息。这对于许多需要根据地理位置信息获取相关数据的场景是非常有用的。
版权声明:本文为lps12345666原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。