Google Maps Android tutorial 1: Adding a map, Geolocation

Before we begin

  1. Go to console.developers.google.com
  2. Add a new project.
  3. Create an API Key
  4. APIs and Services -> Select Maps SDK for Android and enable it
  5. Copy your API Key to use in the project.

Add Google Play Services to your project

In your app level build.gradle file

implementation 'com.google.android.gms:play-services-maps:16.1.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'

AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Inside the application tag, add these.

<meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />

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

Adding the map

In your activity’s layout xml file, add a map fragment.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.constraint.ConstraintLayout>

Initialize it in your activity’s java code. Don’t worry if the code doesn’t compile now, we will be adding the functions in the next steps.

public class MainActivity extends AppCompatActivity {
    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                mMap = googleMap;
                mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
                    @Override
                    public void onMapLoaded() {
                        mMap = googleMap;
                        initMapStuff();
                    }
                });
            }
        });
    }
}

Geolocation

We will first add the user location button to the map. Google map provides an inbuilt button, which appears when enabled, and moves the map to the current device location upon click.

public void initMapStuff() {
    //move map to a fixed initial location if required
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(55.3781,-3.4360),10));
    if (checkPermission()) {
        //or move map to user location. - this is defined in next step
        getLastLocation();
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
    } else {
        requestPermission();
    }
}

Then add this function to zoom the map to the user’s location automatically when the map is loaded.

public void getLastLocation() {
    FusedLocationProviderClient locationClient = LocationServices.getFusedLocationProviderClient(getActivity());
    try {
        locationClient.getLastLocation()
                .addOnSuccessListener(new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        // GPS location can be null if GPS is switched off
                        if (location != null) {
                            if (mMap != null) {
                                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()),10));
                            }
                        }
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.d("MapDemoActivity", "Error trying to get last GPS location");
                        e.printStackTrace();
                    }
                });
    } catch (SecurityException e) { e.printStackTrace(); }
}

Handling Runtime Permissions

Android 6.0+, we are required to handle permissions at runtime. so let’s do that

For requesting permission, please note:

  • If you’re using AppCompatActivity, you will use ActivityCompat.requestPermissions.
  • If using Fragment, use requestPermissions.
private void requestPermission() {
    ActivityCompat.requestPermissions(new String[] {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION }, RequestPermissionCode);
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case RequestPermissionCode:
            if (grantResults.length > 0) {
                boolean finelocation = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                boolean coarselocation = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                if (finelocation && coarselocation) {
                    if (checkPermission()) {
                        if (mMap != null) {
                            initMapStuff();
                        }
                    }
                } else {
                    //show error msg
                }
            }
            break;
    }
}

public boolean checkPermission() {
    int FirstPermissionResult = ContextCompat.checkSelfPermission(activity.getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION);
    int SecondPermissionResult = ContextCompat.checkSelfPermission(activity.getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION);
    return FirstPermissionResult == PackageManager.PERMISSION_GRANTED && SecondPermissionResult == PackageManager.PERMISSION_GRANTED;
}

That’s it. Now you have a working map, which automatically zooms to user location upon loading, and shows the user location button.

 

 

 

 

 

 

 


Also published on Medium.

By |2019-04-03T03:55:06+00:00March 14th, 2019|Categories: Android Tutorials|0 Comments

Leave A Comment