根据经纬度获取百度cityCode java代码
时间: 2023-11-16 19:03:56 浏览: 74
以下是使用Java代码实现的示例:
```java
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class BaiduMapUtils {
/**
* 根据经纬度获取百度cityCode
* @param lng 经度
* @param lat 纬度
* @param ak 百度地图API密钥
* @return 百度cityCode
* @throws IOException
*/
public static String getCityCode(double lng, double lat, String ak) throws IOException {
String url = "http://api.map.baidu.com/reverse_geocoding/v3/";
String location = lat + "," + lng;
String params = "ak=" + ak + "&output=json&coordtype=wgs84ll&location=" + URLEncoder.encode(location, "UTF-8");
String result = doGet(url, params);
JSONObject json = JSON.parseObject(result);
if (json.getIntValue("status") == 0) {
JSONObject addressComponent = json.getJSONObject("result").getJSONObject("addressComponent");
String cityCode = addressComponent.getString("cityCode");
return StringUtils.isNotEmpty(cityCode) ? cityCode : "";
}
return "";
}
/**
* 发送GET请求
* @param url 请求地址
* @param params 请求参数
* @return 响应内容
* @throws IOException
*/
private static String doGet(String url, String params) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url + "?" + params);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity, "UTF-8");
}
} finally {
if (response != null) {
response.close();
}
}
return "";
}
}
```
调用示例:
```java
public class Test {
public static void main(String[] args) throws IOException {
double lng = 116.404;
double lat = 39.915;
String ak = "你的百度地图API密钥";
String cityCode = BaiduMapUtils.getCityCode(lng, lat, ak);
System.out.println(cityCode);
}
}
```
注意:需要替换代码中的百度地图API密钥。
阅读全文