Maps in applications have taken customer experience to a whole new level. Whether its showing the current user location or showing the direction to your business office maps have always been very useful. The good news here is even though displaying the complete world map inside your app might sound a very complex task thanks to Google its ridiculously easy

In this tutorial we will deal with the basics of Google Location and Map Android Integration, we will register our project in Google Developer Console and obtain the API key . Using the API key we will show the Map in our app and with the help of FusedLocationProvider API mark the current location on the map.

Register your App

In order for your app to show Google maps you will have to register it with Google Dev Console. Steps on how to register your app are mentioned here

Create a Activity:

In this example we will be showing our map inside a Activity . Hence we should create a Activity class which extends Fragment Activity. This activity will be named MapsActivity

public class MapsActivity extends FragmentActivity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); } }

Fetching Current Location:

There are two methods for obtaining location in Android

Android Framework – LocationManager API Google Play Services – FusedLocationProvider API

Android docs encourages us to use FusedLocation APIs as they are found to be more accurate and easy to implement

Check for permissions :

As of Android Marshmallow device location perimission should to be asked at runtime rather than at install time . You can read more about this here.

Add the following to AndroidManifest.xml <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Before fetching location you need to check if the user has granted location permissions for this app. If the permission is not granted you can request the user by adding this code in your activity. User will see a system dialog with two option “YES” and “NO”

//Checking if the user has granted location permission for this app if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { /* Requesting the Location permission 1st Param - Activity 2nd Param - String Array of permissions requested 3rd Param -Unique Request code. Used to identify these set of requested permission */ ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},LOCATION_REQUEST_CODE); return; }

Once any of the option is clicked following method is invoked. You need to override this in your MapActivity

public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case LOCATION_REQUEST_CODE: if (grantResults.length > 0 && grantResults[0] == PERMISSION_GRANTED) { //Permission Granted } else Toast.makeText(this, "Location Permission Denied", Toast.LENGTH_SHORT).show(); break; } }

Current Location with FusedLocationProviderAPI

Add the following dependency to build.gradle

compile 'com.google.android.gms:play-services:11.0.2'

You will need a instance of GoogleApiClient to obtain the location with FusedLocationProviderAPI. So first we will instantiate a GoogleApiClient object as shown the code snippet below

You can notice we have added a added listeners to notify us when our Api client is connected. Our MapActivity should implement these interfaces and override the following methods

onConnectionSuspended onConnectionFailed onConnected

Call connect() on the GoogleApiClient object. This call should be ideally be done in the onStart() lifecycle method of your activity. Similarly you should disconnect the GoogleApiClient in onStop().

Once the connection is succesful onConnected is invoked and we can begin extracting the location.

public class MapsActivity extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private GoogleApiClient googleApiClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); //Instantiating the GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); } public void onStart() { super.onStart(); // Initiating the connection googleApiClient.connect(); } public void onStop() { super.onStop(); // Disconnecting the connection googleApiClient.disconnect(); } //Callback invoked once the GoogleApiClient is connected successfully @Override public void onConnected(Bundle bundle) { //Fetching the last known location using the FusedLocationProviderApi Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); } @Override public void onConnectionSuspended(int i) { } //Callback invoked if the GoogleApiClient connection fails @Override public void onConnectionFailed(ConnectionResult connectionResult) { }

The above code will give us the current location of the device. But as we are planning to show that location inside a map we now need to integrate Google Maps in our application.

Integrate Google Maps:

Once you have your API key you can now go ahead and create your own application.

Since we have already added Google Play services dependency for location we don’t need to add a seperate dependency for displaying maps. But if not following dependency needs to be added

compile 'com.google.android.gms:play-services-maps:11.0.2'

Add the following to AndroidManifest.xml

<meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_maps_key" />

Create a file by the name google_maps_api.xml in the res>values folder.You will have to add the API Key created in the first step in this file. Add the following

<resources> <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">[YOUR-API-KEY]</string> </resources>

Add the following fragment to the layout file for your MapsActivity. Placing the SupportMapFragment is the simplest way of displaying a map in your app. SupportMapFragment is basically a wrapper around a MapView to automatically handle the necessary life cycle needs.

<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"/>

Note: You can also display a map by using a MapView in your own activity. But then you will have to explicitly handle all the lifecycle callbacks while MapFragment handles this for you.

Your MapActivity should implement OnMapReadyCallback interface and override onMapReady method. Calling getMapAsync will invoke the onMapReady callback along with the GoogleMap object when the map is ready. GoogleMap is the main class of the Google Maps Android API and is the entry point for all methods related to the map

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private GoogleMap mMap; private GoogleApiClient googleApiClient; private static final int LOCATION_REQUEST_CODE = 101; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); googleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); } public void onStart() { super.onStart(); googleApiClient.connect(); } public void onStop() { super.onStop(); googleApiClient.disconnect(); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; checkLocationandAddToMap(); } @Override public void onConnected(Bundle bundle) { SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case LOCATION_REQUEST_CODE: if (grantResults.length > 0 && grantResults[0] == PERMISSION_GRANTED) { checkLocationandAddToMap(); } else Toast.makeText(this, "Location Permission Denied", Toast.LENGTH_SHORT).show(); break; } } private void checkLocationandAddToMap() { //Checking if the user has granted the permission if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { //Requesting the Location permission ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE); return; } //Fetching the last known location using the Fus Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); //MarkerOptions are used to create a new Marker.You can specify location, title etc with MarkerOptions MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("You are Here"); //Adding the created the marker on the map mMap.addMarker(markerOptions); } }

Conclusion

Thats it! I hope this tutorial helped you. If YES please share it with your friends. Dont forget to like and comment. Also if you want to learn how to customize Google Maps in your application read this.

Want to know how display current location on Google Maps ? Read this