0

With the geocoder API, I am trying to get the complete address of the user and need to specify the city, state, and country separately. However, I am unable to get the city parameter correctly. It sometimes picks an area name and leaves the rest null.

Any workarounds that I can use? I don't have access to paid APIs, so please suggest something that is free.

Geocoder gcd = new Geocoder(Context, Locale.getDefault());

List<Address> addresses = gcd.getFromLocation(
        lastLocation.getLatitude(), lastLocation.getLongitude(), 1);
                            
 if(addresses.get(0).getCountryName() !=null)
        country =addresses.get(0).getCountryName();

if(addresses.get(0).getAdminArea() !=null)
    state =addresses.get(0).getAdminArea();

if(addresses.get(0).getSubAdminArea() !=null)
{
    city = addresses.get(0).getSubAdminArea();
} else if(addresses.get(0).getLocality() !=null)
{
    city = addresses.get(0).getLocality();
}

Although I checked all the parameters separately, I was not able to locate a specific parameter that returns the correct city name every time. I have already checked other posts, but have not found any reliable ones.

2 Answers 2

0

at this code you provided you have already made you results max to 1. try to increase the number then filter based on which city is not null.

for sure it will be reliable. i have used it in production and it's working fine for me.

int maxResults = 10; //not just 1.
Geocoder gcd = new Geocoder(Context, Locale.getDefault());
    List<Address> addresses = gcd.getFromLocation(
            lastLocation.getLatitude(), lastLocation.getLongitude(), maxResults);
Sign up to request clarification or add additional context in comments.

1 Comment

It works, but the problem is addresses.get(i).getLocality() for fetching the city is inaccurate. It mostly fetches area name instead of city name and i need to fetch city name accurately.
0

To reliably extract the city, state, and country from Geocoding APIs like Google Maps or OpenStreetMap, you can use the following techniques:

  1. OpenStreetMap (OSM) and Nominatim: The Nominatim API is a free geocoding service provided by OpenStreetMap. It allows you to reverse geocode coordinates into detailed address components."

Example API Call:
https://nominatim.openstreetmap.org/reverse?lat=latitude&lon=longitude&format=json

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.