Introduction

Integrating Google Maps into your Android application can significantly enhance the user experience by providing location-based services. This module will guide you through the process of adding Google Maps to your app, displaying a map, and customizing it to suit your needs.

Prerequisites

Before you start, ensure you have:

  • A basic understanding of Android development.
  • An active Google Cloud Platform account.
  • The Google Maps API enabled in your Google Cloud project.

Steps to Integrate Google Maps

  1. Set Up Google Cloud Project

  1. Create a new project in the Google Cloud Console.
  2. Enable the Maps SDK for Android:
    • Navigate to the API & Services > Library.
    • Search for Maps SDK for Android and enable it.
  3. Generate an API key:
    • Go to API & Services > Credentials.
    • Click on Create credentials and select API key.
    • Restrict the API key to your Android app by specifying the package name and SHA-1 certificate fingerprint.

  1. Add Google Maps Dependency

Add the following dependency to your build.gradle (Module: app) file:

dependencies {
    implementation 'com.google.android.gms:play-services-maps:18.0.2'
}

  1. Update AndroidManifest.xml

Add the following permissions and metadata to your AndroidManifest.xml file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <uses-permission android:name="android.permission.INTERNET"/>
    <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:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="YOUR_API_KEY"/>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

Replace YOUR_API_KEY with the API key you generated.

  1. Create a Map Activity

Create a new activity named MapsActivity and its corresponding layout file activity_maps.xml.

MapsActivity.java

package com.example.yourapp;

import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
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;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @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.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

activity_maps.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MapsActivity">

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

  1. Run Your Application

Run your application on an Android device or emulator. You should see a map with a marker in Sydney.

Customizing the Map

Adding Markers

You can add multiple markers to the map by using the addMarker method:

LatLng location = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(location).title("Marker Title"));

Changing Map Type

You can change the map type to normal, satellite, terrain, or hybrid:

mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

Enabling User Location

To enable the user's current location on the map, ensure you have the necessary permissions and then enable the location layer:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
    mMap.setMyLocationEnabled(true);
} else {
    // Request location permission
}

Practical Exercise

Task

  1. Add a marker at your current location.
  2. Change the map type to hybrid.
  3. Zoom in to the marker location.

Solution

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker at a specific location
    LatLng myLocation = new LatLng(37.7749, -122.4194); // Example coordinates
    mMap.addMarker(new MarkerOptions().position(myLocation).title("Marker at My Location"));
    
    // Change map type to hybrid
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    
    // Move the camera to the marker and zoom in
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 15));
}

Common Mistakes and Tips

  • API Key Restrictions: Ensure your API key is correctly restricted to your app's package name and SHA-1 fingerprint.
  • Permissions: Always check and request necessary permissions at runtime, especially for location services.
  • Error Handling: Implement error handling for scenarios where the map fails to load or the API key is invalid.

Conclusion

In this module, you learned how to integrate Google Maps into your Android application, display a map, and customize it with markers and different map types. This knowledge will enable you to create location-based features and enhance the user experience in your apps. In the next module, we will explore implementing in-app purchases to monetize your application.

© Copyright 2024. All rights reserved