Follow the tutorial to create a simple Android project with Google Maps:
https://developers.google.com/maps/documentation/android-api/start
-
Make your activity implement the OnMapReadyCallback interface. This interface will allow you to know when the map is ready to use when the onMapReady method is called.
-
Retrieve SupportMapFragment and retrieve the map asynchronously sending the activity as parameter to be the callback:
// Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById( R.id.map ); mapFragment.getMapAsync( this );
-
Create another field for the GoogleMap object on the Activity and save it when the onMapReady method is called:
@Override public void onMapReady( GoogleMap googleMap ) { this.googleMap = googleMap; }
-
Create a method that shows your current location and another to check for the user permission to access the location with the following code:
public void showMyLocation() { if ( googleMap != null ) { String[] permissions = { android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION }; if ( hasPermissions( this, permissions ) ) { googleMap.setMyLocationEnabled( true ); Location lastLocation = LocationServices.FusedLocationApi.getLastLocation( googleApiClient ); if ( lastLocation != null ) { addMarkerAndZoom( lastLocation, "My Location", 15 ); } } else { ActivityCompat.requestPermissions( activity, permissions, ACCESS_LOCATION_PERMISSION_CODE ); } } } public static boolean hasPermissions( Context context, String[] permissions ) { for ( String permission : permissions ) { if ( ContextCompat.checkSelfPermission( context, permission ) == PackageManager.PERMISSION_DENIED ) { return false; } } return true; }
-
Create the method addMarkerAndZoom in the main Activity:
public void addMarkerAndZoom( Location location, String title, int zoom ) { LatLng myLocation = new LatLng( location.getLatitude(), location.getLongitude() ); googleMap.addMarker( new MarkerOptions().position( myLocation ).title( title ) ); googleMap.moveCamera( CameraUpdateFactory.newLatLngZoom( myLocation, zoom ) ); }
-
Override the onRequestPermissionsResult method and check for the ACCESS_LOCATION_PERMISSION_CODE with the following code:
@Override
public void onRequestPermissionsResult( int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults )
{
for ( int grantResult : grantResults )
{
if ( grantResult == -1 )
{
return;
}
}
switch ( requestCode )
{
case ACCESS_LOCATION_PERMISSION_CODE:
showMyLocation();
break;
default:
super.onRequestPermissionsResult( requestCode, permissions, grantResults );
}
}- Test the application on a real device and make sure your location is shown.
- Add a button at the bottom of the map with the label “find address”
-
Include the Google Play Services Library on your build.gradle file:
compile 'com.google.android.gms:play-services:10.2.1' -
Declare a GoogleApiClient field on the main activity and instantiate it on the onCreate method:
//Configure Google Maps API Objects googleApiClient = new GoogleApiClient.Builder( this ).addConnectionCallbacks( this ). addOnConnectionFailedListener( this ).addApi( LocationServices.API ).build(); locationRequest.setInterval( 10000 ); locationRequest.setFastestInterval( 5000 ); locationRequest.setPriority( LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY ); googleApiClient.connect();
-
Make the main Activity Implement the GoogleApiClient.ConnectionCallbacks with the following code:
@Override public void onConnected( @Nullable Bundle bundle ) { LocationServices.FusedLocationApi.requestLocationUpdates( googleApiClient, locationRequest, new LocationListener() { @Override public void onLocationChanged( Location location ) { showMyLocation(); stopLocationUpdates(); } } ); } @Override public void onConnectionSuspended( int i ) { LocationServices.FusedLocationApi.removeLocationUpdates( googleApiClient, null); } public void stopLocationUpdates() { LocationServices.FusedLocationApi.removeLocationUpdates( googleApiClient, new LocationListener() { @Override public void onLocationChanged( Location location ) { } } ); }
-
Create a method that handles the onClick event from the Find Address button with the following code:
public void onFindAddressClicked( View view ) { startFetchAddressIntentService(); } public void startFetchAddressIntentService() { Location lastLocation = LocationServices.FusedLocationApi.getLastLocation( googleApiClient ); if ( lastLocation != null ) { AddressResultReceiver addressResultReceiver = new AddressResultReceiver( new Handler() ); addressResultReceiver.setAddressResultListener( new AddressResultListener() { @Override public void onAddressFound( final String address ) { runOnUiThread( new Runnable() { @Override public void run() { MapsActivity.this.address.setText( address ); MapsActivity.this.address.setVisibility( View.VISIBLE ); } } ); } } ); Intent intent = new Intent( this, FetchAddressIntentService.class ); intent.putExtra( FetchAddressIntentService.RECEIVER, addressResultReceiver ); intent.putExtra( FetchAddressIntentService.LOCATION_DATA_EXTRA, lastLocation ); startService( intent ); } } }
-
To be able to run the project you will need the following classes AddressResultReceiver, AddressResultListener and FetchAddressIntentService. In the following url you will be able to find a project that contains the missing classes:
-
Include the service you created in the AndroidManifest file (below the closing tag):
<service android:name=".FetchAddressIntentService" android:exported="false" />
-
Add a floating action button to the Maps view at the right bottom.
-
Implement the onClick listener for the Add Button that redirects to another Activity where the user can add a new Location to the map. A location has a name, a description and a geolocation (longitude and latitude).
-
Create a form that captures the Location data and add a save button that validates the form and submits the data.
-
Once the user creates a new Location then the Application should take you back to the map and displayed the created location.
