You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中使用Maps API逆地理编码:数据提取遇困求指导

获取Google Maps逆地理编码中的RegionCode/州信息

我来帮你搞定这个问题!你已经搭好了逆地理编码的请求框架,接下来只需要触发请求并解析返回结果,就能拿到你要的RegionCode或者完整地址数据了。具体操作如下:

第一步:执行请求获取返回结果

你创建的GeocodingApiRequest只是构建了请求模板,还没真正发送到Google服务器。可以调用await()方法同步执行请求,拿到GeocodingResult数组——每个元素对应一组匹配的地址信息。

第二步:解析结果提取目标信息

返回的GeocodingResult里包含了拆分好的地址组件(AddressComponent),你可以通过组件的类型来定位州或国家RegionCode:

  • administrative_area_level_1:对应一级行政区(比如你提供的坐标在巴西皮奥伊州,这个类型就对应州信息),getLongName()是州的全称,getShortName()是州的缩写代码
  • country:对应国家,getShortName()就是ISO 3166-1格式的国家RegionCode(比如BR代表巴西)

完整代码示例

String API_KEY = "AIzaSyABXoV5ktBurLqodVntX6ImhNHOjDBgciQ";
GeoApiContext apiContext = new GeoApiContext.Builder()
        .apiKey(API_KEY)
        .build();
LatLng test = new LatLng(-8.96238, -40.68703);
GeocodingApiRequest geocodingApi = GeocodingApi.reverseGeocode(apiContext, test);

try {
    // 执行请求获取结果
    GeocodingResult[] results = geocodingApi.await();
    
    // 遍历所有匹配的地址结果
    for (GeocodingResult result : results) {
        AddressComponent[] components = result.getAddressComponents();
        
        String stateFullName = null;
        String stateShortCode = null;
        String countryRegionCode = null;
        
        // 逐个检查地址组件
        for (AddressComponent component : components) {
            List<String> componentTypes = component.getTypes();
            
            // 提取州信息
            if (componentTypes.contains("administrative_area_level_1")) {
                stateFullName = component.getLongName();
                stateShortCode = component.getShortName();
            }
            
            // 提取国家RegionCode
            if (componentTypes.contains("country")) {
                countryRegionCode = component.getShortName();
            }
        }
        
        // 输出你需要的信息
        System.out.println("州全称: " + stateFullName);
        System.out.println("州短代码: " + stateShortCode);
        System.out.println("国家RegionCode: " + countryRegionCode);
        
        // 如果需要完整的地址JSON数据,用序列化工具转换即可(比如Gson)
        // Gson gson = new Gson();
        // String fullAddressJson = gson.toJson(results);
        // System.out.println("完整地址JSON: " + fullAddressJson);
    }
} catch (Exception e) {
    // 处理请求异常
    e.printStackTrace();
} finally {
    // 务必关闭上下文,释放资源
    apiContext.shutdown();
}

额外提示

  • 记得处理await()抛出的异常(网络异常、请求超时等)
  • 最后一定要调用apiContext.shutdown(),避免资源泄漏
  • 如果需要完整的返回JSON数据,用Gson这类JSON序列化库把GeocodingResult数组转换成字符串就行,示例里已经注释了这部分代码

内容的提问来源于stack exchange,提问作者Luc Damhuis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:56:19