Search code examples
javaandroidgoogle-geocoder

Java Geocoding - convert latitude and longitude into an address


I need for my Android App the name of the city where my car is located in the moment.

I have the latitude and longitude and want to convert this with the geocoder in the address and want to get the city.

I read some blocks but because I'm new to this I dont get the clue.

Please can anyone help me how to do this?

EDIT:

I dont use this geocoding in my app. I want to use it in my Java web service and I think I have to this with HTTPRequest, is it? and with the google api url.


Solution

  • What you are looking for is Reverse Geocoding.

    The Geocoder class should help you do what you need (taken from here):

    public static void getAddressFromLocation(
            final Location location, final Context context, final Handler handler) {
        Thread thread = new Thread() {
            @Override public void run() {
                Geocoder geocoder = new Geocoder(context, Locale.getDefault());   
                String result = null;
                try {
                    List<Address> list = geocoder.getFromLocation(
                            location.getLatitude(), location.getLongitude(), 1);
                    if (list != null && list.size() > 0) {
                        Address address = list.get(0);
                        // sending back first address line and locality
                        result = address.getAddressLine(0) + ", " + address.getLocality();
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Impossible to connect to Geocoder", e);
                } finally {
                    Message msg = Message.obtain();
                    msg.setTarget(handler);
                    if (result != null) {
                        msg.what = 1;
                        Bundle bundle = new Bundle();
                        bundle.putString("address", result);
                        msg.setData(bundle);
                    } else 
                        msg.what = 0;
                    msg.sendToTarget();
                }
            }
        };
        thread.start();
    }
    

    EDIT: As per your comment, then no, you can't use the Geocoder class on a normal Java web service. That being said, there are alternatives. The Google Geocoding API is usually a good place to start, that being said, they do seem to have limits.

    Alternatively, you could take a look at Nominatim which is an open source Reverse Geocoding service albeit it seems to be slightly limited when compared to Google's services.