| | |
| | | public class AddressLookup { |
| | | |
| | | public static String getAddress(String administrativeCode) { |
| | | String apiKey = "AIzaSyBBW0XxW1FK7IXmmS7KFtAjX3o99eFPsss"; |
| | | |
| | | // 创建GeoApiContext实例 |
| | | GeoApiContext context = new GeoApiContext.Builder() |
| | | .apiKey("AIzaSyBBW0XxW1FK7IXmmS7KFtAjX3o99eFPsss") // REPLACE WITH YOUR API KEY |
| | | .apiKey(apiKey) |
| | | .build(); |
| | | |
| | | GeocodingResult[] results = GeocodingApi.geocode(context, "EN " + administrativeCode).awaitIgnoreError(); |
| | | // 设置邮政编码 |
| | | String zipcode = administrativeCode; |
| | | |
| | | if (results == null || results.length == 0) { |
| | | try { |
| | | // 发起逆地理编码请求 |
| | | GeocodingResult[] results = GeocodingApi.geocode(context, zipcode).await(); |
| | | |
| | | // 提取结果 |
| | | if (results.length > 0) { |
| | | String formattedAddress = results[0].formattedAddress; |
| | | System.out.println("地址:" + formattedAddress); |
| | | return formattedAddress; |
| | | } else { |
| | | System.out.println("未找到地址"); |
| | | } |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | AddressComponent[] components = results[0].addressComponents; |
| | | String province = getComponent(components, "administrative_area_level_1"); |
| | | String city = getComponent(components, "locality"); |
| | | String district = getComponent(components, "administrative_area_level_3"); |
| | | String street = getComponent(components, "route"); |
| | | String number = getComponent(components, "street_number"); |
| | | |
| | | StringBuilder builder = new StringBuilder(); |
| | | |
| | | if (province != null) { |
| | | builder.append(province); |
| | | } |
| | | |
| | | if (city != null && !city.equals(province)) { |
| | | builder.append(city); |
| | | } |
| | | |
| | | if (district != null && !district.equals(city)) { |
| | | builder.append(district); |
| | | } |
| | | |
| | | if (street != null) { |
| | | builder.append(street); |
| | | } |
| | | |
| | | if (number != null) { |
| | | builder.append(number); |
| | | } |
| | | |
| | | return builder.toString(); |
| | | } |
| | | |
| | | private static String getComponent(AddressComponent[] components, String type) { |