Java 地址识别省市区县
时间: 2023-12-02 14:02:56 浏览: 188
要识别Java地址中的省市区县信息,可以使用第三方的地址库或者在线API来实现。以下是一个示例代码,使用了百度地图API来识别地址:
```java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class AddressRecognizer {
private static final String BAIDU_MAP_API_URL = "http://api.map.baidu.com/geocoding/v3/?address=%s&output=json&ak=%s";
public static void main(String[] args) throws Exception {
String address = "浙江省杭州市西湖区文三路478号浙江大学紫金港校区";
Map<String, String> addressInfo = recognizeAddress(address, "your_baidu_map_api_ak");
System.out.println(addressInfo);
}
public static Map<String, String> recognizeAddress(String address, String apiKey) throws Exception {
String url = String.format(BAIDU_MAP_API_URL, address, apiKey);
String json = IOUtils.toString(new URL(url), StandardCharsets.UTF_8);
JSONObject result = JSON.parseObject(json).getJSONObject("result");
JSONObject location = result.getJSONObject("location");
String latitude = location.getString("lat");
String longitude = location.getString("lng");
JSONArray addressComponents = result.getJSONArray("addressComponent");
String province = addressComponents.getJSONObject(0).getString("short_name");
String city = addressComponents.getJSONObject(1).getString("short_name");
String district = addressComponents.getJSONObject(2).getString("short_name");
String street = addressComponents.getJSONObject(3).getString("short_name");
Map<String, String> addressInfo = new HashMap<>();
addressInfo.put("province", province);
addressInfo.put("city", city);
addressInfo.put("district", district);
addressInfo.put("street", street);
addressInfo.put("latitude", latitude);
addressInfo.put("longitude", longitude);
return addressInfo;
}
}
```
该代码会输出地址中的省市区县信息,以及地址所在位置的经纬度。需要替换 `your_baidu_map_api_ak` 为你的百度地图API的AK密钥。
阅读全文