Android Get Address from Latitude and Longitude in Google Map – Tutorial
In my previous tutorial ‘Android Get Location with Google API Service – Tutorial‘ you learned how to get location from GPS and Google Api service. In this tutorial you will learn how to get address from latitude and longitude with help of Geocoder.
Geocoder
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.
Step 1: Open your previously saved project
My project was ‘Android Get Location with Google API Service – Tutorial , so i opened this project.
Step 2: Import Address namespace file in import section
import android.location.Address;
Step 3: Open MapActivity.java file and create a new method to get address
public String getAddress(Context ctx, double lat,double lng){ String fullAdd=null; try{ Geocoder geocoder= new Geocoder(ctx, Locale.getDefault()); List<android.location.Address> addresses = geocoder.getFromLocation(lat,lng,1); if(addresses.size()>0){ Address address = addresses.get(0); fullAdd = address.getAddressLine(0); // if you want only city or pin code use following code // /* String Location = address.getLocality(); String zip = address.getPostalCode(); String Country = address.getCountryName(); */ } }catch(IOException ex){ ex.printStackTrace(); } return fullAdd; }
Now run your project and see the output.
Full Source Code
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.suraj.userlocationwithgoogleapiservice"> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_maps_key" /> <activity android:name=".MapsActivity" android:label="@string/title_activity_maps"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
activity_maps.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:map="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/map" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.suraj.userlocationwithgoogleapiservice.MapsActivity" />
MapsActivity
import android.*; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.location.Geocoder; import android.location.Location; import android.location.Address; import android.os.Build; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.support.v4.content.ContextCompat; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; //import com.google.android.gms.identity.intents.Address; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import java.io.IOException; import java.security.Permission; import java.util.List; import java.util.Locale; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener, com.google.android.gms.location.LocationListener { private GoogleMap mMap; SupportMapFragment mapFragment; private GoogleApiClient mGoogleApiClient; private Location mLocation; double lat, lng; private LocationRequest mLocationRequest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); // Check runtime Permission // int Permission_All = 1; String[] Permissions = {android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION}; if(!hasPermissions(this, Permissions)){ ActivityCompat.requestPermissions(this, Permissions, Permission_All); } createLocationRequest(); // make a buidler for GoogleApiClient // if(mGoogleApiClient==null) { mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext()) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } } protected void createLocationRequest(){ if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED ||ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION)== PackageManager.PERMISSION_GRANTED ) { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(20000); // 20 seconds mLocationRequest.setFastestInterval(10000); //10 seconds mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Add a marker in Sydney and move the camera LatLng sydney = new LatLng(lat, lng); String address = getAddress(this,lat,lng); mMap.addMarker(new MarkerOptions().position(sydney).title(address)); mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); } // Get Address from latitude and longitude // public String getAddress(Context ctx, double lat,double lng){ String fullAdd=null; try{ Geocoder geocoder= new Geocoder(ctx, Locale.getDefault()); List<android.location.Address> addresses = geocoder.getFromLocation(lat,lng,1); if(addresses.size()>0){ Address address = addresses.get(0); fullAdd = address.getAddressLine(0); // if you want only city or pin code use following code // /* String Location = address.getLocality(); String zip = address.getPostalCode(); String Country = address.getCountryName(); */ } }catch(IOException ex){ ex.printStackTrace(); } return fullAdd; } // must declare methods // public void onStart(){ mGoogleApiClient.connect(); super.onStart(); if(mGoogleApiClient.isConnected()){ startLocationUpdates(); } } public void onStop(){ mGoogleApiClient.disconnect(); stopLocationUpdate(); super.onStop(); } public void onPause(){ mGoogleApiClient.disconnect(); stopLocationUpdate(); super.onPause(); } public void onResume(){ mGoogleApiClient.connect(); super.onResume(); if(mGoogleApiClient.isConnected()){ startLocationUpdates(); } } // create method for location update // protected void startLocationUpdates(){ if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED ||ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION)== PackageManager.PERMISSION_GRANTED ) { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); } } protected void stopLocationUpdate(){ LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); } // Must Declare LocatonListener Methods // public void onLocationChanged(Location location){ if(location!=null){ lat = location.getLatitude(); lng = location.getLongitude(); mapFragment.getMapAsync(this); } } public void onConnectionSuspended(int arg0){ } public void onStatusChange(String provider, int status, Bundle extras){ } // Must Declare Callback Methods // public void onConnected(Bundle args0){ if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED ||ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION)== PackageManager.PERMISSION_GRANTED ) { mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if(mLocation!=null){ lat=mLocation.getLatitude(); lng = mLocation.getLatitude(); mapFragment.getMapAsync(this); } if(mGoogleApiClient.isConnected()){ startLocationUpdates(); } } } public static boolean hasPermissions(Context context, String... permissions){ if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M && context!=null && permissions!=null){ for(String permission: permissions){ if(ActivityCompat.checkSelfPermission(context, permission)!=PackageManager.PERMISSION_GRANTED){ return false; } } } return true; } public void onConnectionFailed(ConnectionResult result){ } }