编程语言
首页 > 编程语言> > JAVA Google地理编码API获取城市

JAVA Google地理编码API获取城市

作者:互联网

我正在尝试使用Google地理编码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个等级.ADMINISTRATIVE_AREA_LEVEL_1和城市名称位于不同的等级,具体取决于特定的位置/国家/地区.
所以问题是-如何从结果中准确提取城市名称?还是我需要正确地提出要求?

附言它不是移动应用.

解决方法:

使用AddressComponentType.LOCALITY从GeocodingResult获取city name

我这样做:

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;
}

标签:google-maps,google-geocoder,google-geocoding-api,java
来源: https://codeday.me/bug/20191118/2030213.html