Wednesday, September 16, 2015

Find addresses of given latitude and longitude using android.location.Geocoder

This example allow users to enter latitude and longitude, then find the addresses that are known to describe the area immediately surrounding the given latitude and longitude, using getFromLocation (double latitude, double longitude, int maxResults) method of android.location.Geocoder.



android.location.Geocoder is a class for handling geocoding and reverse geocoding. Geocoding is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate. Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a (partial) address. The amount of detail in a reverse geocoded location description may vary, for example one might contain the full street address of the closest building, while another might contain only a city name and postal code. The Geocoder class requires a backend service that is not included in the core android framework. The Geocoder query methods will return an empty list if there no backend service in the platform. Use the isPresent() method to determine whether a Geocoder implementation exists.



com.blogspot.android_er.androidlatlongtoaddress.MainActivity.java
package com.blogspot.android_er.androidlatlongtoaddress;

import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    Geocoder geocoder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText latText = (EditText)findViewById(R.id.latText);
        final EditText lonText = (EditText)findViewById(R.id.lonText);
        Button btnFind = (Button)findViewById(R.id.find);

        final ListView listResult = (ListView)findViewById(R.id.listResult);

        geocoder = new Geocoder(this);


        btnFind.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                String strLat = latText.getText().toString();
                String strLon = lonText.getText().toString();

                boolean parsable = true;
                Double lat = null, lon = null;

                try{
                    lat = Double.parseDouble(strLat);
                }catch (NumberFormatException ex){
                    parsable = false;
                    Toast.makeText(MainActivity.this,
                            "Latitude does not contain a parsable double",
                            Toast.LENGTH_LONG).show();
                }

                 try{
                    lon = Double.parseDouble(strLon);
                }catch (NumberFormatException ex){
                    parsable = false;
                    Toast.makeText(MainActivity.this,
                            "Longitude does not contain a parsable double",
                            Toast.LENGTH_LONG).show();
                }

                if(parsable){
                    Toast.makeText(MainActivity.this,
                            "find " + lat + " : " + lon,
                            Toast.LENGTH_LONG).show();

                    List<Address> geoResult = findGeocoder(lat, lon);
                    if(geoResult != null){
                        List<String> geoStringResult = new ArrayList<String>();
                        for(int i=0; i < geoResult.size(); i++){
                            Address thisAddress = geoResult.get(i);
                            String stringThisAddress = "";
                            for(int a=0; a < thisAddress.getMaxAddressLineIndex(); a++) {
                                stringThisAddress += thisAddress.getAddressLine(a) + "\n";
                            }

                            stringThisAddress +=
                                    "CountryName: " + thisAddress.getCountryName() + "\n"
                                    + "CountryCode: " + thisAddress.getCountryCode() + "\n"
                                    + "AdminArea: " + thisAddress.getAdminArea() + "\n"
                                    + "FeatureName: " + thisAddress.getFeatureName();
                            geoStringResult.add(stringThisAddress);
                        }

                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
                                android.R.layout.simple_list_item_1, android.R.id.text1, geoStringResult);

                        listResult.setAdapter(adapter);
                    }

                }

            }
        });
    }

    private List<Address> findGeocoder(Double lat, Double lon){
        final int maxResults = 5;
        List<Address> addresses = null;
        try {
            addresses = geocoder.getFromLocation(lat, lon, maxResults);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

        return addresses;
    }

}


layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/latText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="numberSigned|numberDecimal"
        android:hint="Latitude" />

    <EditText
        android:id="@+id/lonText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="numberSigned|numberDecimal"
        android:hint="Longitude" />

    <Button
        android:id="@+id/find"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="find Address"/>

    <ListView
        android:id="@+id/listResult"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>


download filesDownload the files (Android Studio Format) .

Related:
- Get ISO country code for the given latitude/longitude, using GeoNames Web Service

No comments: