Question

I am able to successfully get lat/long and pass it to the geocoder to get an Address. However, I don't always get an address back. Seems like it takes a couple of attempts? I'm not sure why.

Is there a better way for me to obtain the address at this point?

public List<Address> getAddresses(){
          Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
          List<Address> addresses = new ArrayList();
             try {
       addresses = geocoder.getFromLocation(latitude, longitude, 1);
      } catch (IOException e) {
       e.printStackTrace();
      }

      return addresses;
        }

I am calling this method here:

LocationListener onLocationChange=new LocationListener() {
        public void onLocationChanged(Location loc) {
            //sets and displays the lat/long when a location is provided
            String latlong = "Lat: " + loc.getLatitude() + " Long: " + loc.getLongitude();   
            latitude = loc.getLatitude();
            longitude = loc.getLongitude();

            List<Address> addresses = getAddresses();

            if(addresses.size() > 0 && addresses != null)
             zipcode = addresses.get(0).getPostalCode();

            Toast.makeText(getApplicationContext(), zipcode,Toast.LENGTH_SHORT).show();
        }
Was it helpful?

Solution

In my experience, Googles Geocoder doesn't always work, I have a couple of fixed points on the map, when I click on the overlay it pops a toast with the address for that lat/long, these points do not change, sometimes I click on a same point 10 times, but I only get an address 7 of them.

It's weird, but thats the way it is, I just modified my app to work around the problem.

OTHER TIPS

The problem with the above approach, as well as many other examples around the internet, is that they only try to retrieve data from the first returned provider with addresses.get(0).getPostalCode(). When you execute the code List<Address> addresses = getAddresses(), it retrieves a list of providers, each supplying their own data. Not all providers will contain the same data.

I had the same issue with receiving the zip code. During my initial tests, I discovered I was receiving data from 6 providers. Only 2 of those 6 providers returned a zip code. The first provider I was trying to access with address.get(0).getPostalCode(), was not one of them. A more appropriate approach would be to loop through all the returned providers to see who returned the data I was looking for.

Something like the following should work. Odds are, one of the providers will return the zip code. This can be done for any of the Geocoding data that you need returned by the providers.

List<Address> address = gc.getFromLocation(myLatitude, myLongitude, 10);

if (address.size() > 0) {
   strZipcode = address.get(0).getPostalCode();

   //if 1st provider does not have data, loop through other providers to find it.
   count = 0;
   while (strZipcode == null && count < address.size()) {
      strZipcode = address.get(count).getPostalCode();
      count++;
   }
}

in case anyone is still looking for a fix, here is what i did: first, i made sure that all the points were fine (would load) but may not always get grabbed by geocoding (getting the data is hit or miss) second, we force the code to do what we want it to do, in other words, if we know it CAN find a lat and long, lets just make it keep trying until it does! this diddnt seem to effect my load time either! so here is the code:

do {
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&key='.$key.'sensor=false');

$output= json_decode($geocode);
$lat = $output->results[0]->geometry->location->lat;
$long = $output->results[0]->geometry->location->lng;
} while($lat == '' and $long == '');

this will continue to loop until both lat and long are not empty strings!

happy coding! :P

Geocoder doesn't work in some area. Instead of using Geocoder, you can use Geocoding Api. Follow the link to get the details about the api,

https://developers.google.com/s/results/?q=geocoding+api

If you are using Autocomplete you can get place location from Place object:

private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback
        = new ResultCallback<PlaceBuffer>() {
    @Override
    public void onResult(PlaceBuffer places) {
        if (!places.getStatus().isSuccess()) {
            // Request did not complete successfully
            AALog.e("Geocoder Place query did not complete. Error: " + places.getStatus().toString());
            return;
        }
        // Get the Place object from the buffer.
        final Place place = places.get(0);
        //--------------here you can recover the place location---------------------
        ((DrawerActivity)getActivity()).lastPlace = place.getLatLng();
        //----------------------------------------------------------------------           
        places.release();
        getActivity().getFragmentManager().beginTransaction().remove(AutocompleteFragment.this).commit();
    }
};

This callback should be registered as follow inside AdapterView.OnItemClickListener:

        PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
                .getPlaceById(mGoogleApiClient, placeId);
        placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top