JAVA谷歌地理编码API获取城市

3
我在尝试使用谷歌地理编码API通过纬度和经度获取国家和城市名称。这个库https://github.com/googlemaps/google-maps-services-java提供了API的JAVA实现。
以下是我当前的处理方式:
GeoApiContext context = new GeoApiContext().setApiKey("AI... my key");
GeocodingResult[] results =  GeocodingApi.newRequest(context)
        .latlng(new LatLng(40.714224, -73.961452)).language("en").resultType(AddressType.COUNTRY, AddressType.ADMINISTRATIVE_AREA_LEVEL_1).await();

logger.info("Results lengh: "+ results.length);

for(int i =0; i< results[0].addressComponents.length; i++) {
    logger.info("Address components "+i+": "+results[0].addressComponents[i].shortName);
}

问题是:
有5个级别的AddressType.ADMINISTRATIVE_AREA_LEVEL_1,城市名称根据特定位置/国家位于不同的级别上。
所以问题是-如何从结果中准确提取城市名称?或者我需要如何正确地形成请求?
P.S. 这不是移动应用程序。

administrative_area_level_2 应该被翻译为城市。 - Ankur Singhal
正如我之前提到的,对于不同的国家/地区,城市会显示在不同的“administrative_area_level_2”(1-5)上。 - user1935987
提供例子,给我完整的URL(不包括API密钥),我有自己的API密钥,我也会请求。 :) - Ankur Singhal
嗯,抱歉,你是指什么样的例子? 如果你是指不同的地理坐标 - 例如悉尼(纬度,经度:-33.8984101,151.2141271)与曼谷(13.7542408,100.5142316)。 - user1935987
是的,我理解这一点,我已经长期使用这个API了,我的观察是我们不能100%依赖谷歌的数据。 - Ankur Singhal
1
仅作为旁注:我曾在地理位置信息服务领域与SmartyStreets合作,我想分享一个警告。Google Mapping Services的服务条款规定,您不能在没有将其显示在地图上的情况下使用他们的结果。还有其他法律限制... - Joseph Hansen
1个回答

3
使用AddressComponentType.LOCALITYGeocodingResult中获取城市名称。以下是我使用的方法:
private PlaceName parseResult(GeocodingResult r) {

    PlaceName placeName = new PlaceName(); // simple POJO

    for (AddressComponent ac : r.addressComponents) {
        for (AddressComponentType acType : ac.types) {

            if (acType == AddressComponentType.ADMINISTRATIVE_AREA_LEVEL_1) {

                placeName.setStateName(ac.longName);

            } else if (acType == AddressComponentType.LOCALITY) {

                placeName.setCityName(ac.longName);

            } else if (acType == AddressComponentType.COUNTRY) {

                placeName.setCountry(ac.longName);
            }
        }

        if(/* your condition */){ // got required data
            break;
        }
    }

    return placeName;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接