I'm trying to get the Country and City names from latitude and longtitude using google geocoding API. This library https://github.com/googlemaps/google-maps-services-java as a JAVA implementation for the API.
This is the current way i'm making it:
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);
}
The problem is:
There is a 5 levels of AddressType.ADMINISTRATIVE_AREA_LEVEL_1
and city name is on different levels depends on specific location/country.
So the question is - how can i extract exactly the city name from the results? or how do i need form a request properly ?
P.S. it is not a mobile app.
Use AddressComponentType.LOCALITY
to get city name from GeocodingResult
I do it on this way:
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;
}