W1 D1: Adding a Google Map 🗺️💗
Tags: 100daysofcode, android, kotlin, maps
Published: 2021-09-15 14:26:51

Hi reader! I'm an Android apps developer. I'm starting this new series called #100DaysOfAndroid in which I'll be covering a cool concept in Android every day for 100 days 🔥. This series will basically have posts about something that I implement during the day & think is an important topic to explain here for your as well as my future reference. Expect a mixture of easy, medium & advanced topics to be covered in these posts. Hopefully, this series helps & motivates you in your journey as an Android developer! 👉👈

### Week 1 🗺️
This week we'll be doing all things maps in Android. Being able to pull off stunts like adding markers to the map, style the map, add geofences, get the user's last known location, etc. are indispensable to your knowledge in this area (pun intended). These things are extremely useful & are super important if you want to know how to add functionalities like sharing your location, sending notifications according to the user's location, etc.

You can check out the other posts from this week 📍 👍.

1.  [Adding a Google Map](https://dev.to/apigeoneer/w1-d1-adding-a-google-map-1gi8) 
2. [Extracting & Saving the User's Current Location](https://dev.to/apigeoneer/w1-d1-adding-a-google-map-1gi8)
3. Incremental Location Permissions
4. Incremental Location Permissions with EasyPermissions Library
5. Sharing Location Data using Firebase
6. Live Location Tracking/Sharing
7. Adding a Marker to the Map on Long-click & Storing the Marked Location/POI


### Day 1: Add a Google Map to Your App

#### Create a Google Maps project
- Add Google Maps to your Project
    - New project → Google Maps Activity -> ... -> Create
    - This will add all the code necessary for adding a map to your app. It mainly adds 3 files automatically to your project: a MapsActivity, an activity_maps.xml layout file in the **res** folder & an activity_maps_api.xml resource file in the **values** folder.


  > You don't need to add the code below. As soon as you create the project, Android Studio will add these for you.


```kotlin
// MapsActivity.kt

import androidx.appcompat.app.AppCompatActivity
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
import com.gmail.apigeoneer.sharemylocation.databinding.ActivityMapsBinding

/**
 * Once an instance of this interface is set on a MapFragment or MapView object, onMapReady(GoogleMap) method is triggered
 * when the map is ready to be used and provides a non-null instance of GoogleMap.
 */
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    // Declare a map object
    private lateinit var mMap: GoogleMap
    private lateinit var binding: ActivityMapsBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding=ActivityMapsBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment=supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }

    /**
     * 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 are 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 fun onMapReady(googleMap: GoogleMap) {
        mMap=googleMap

        // Add a marker in Sydney and move the camera
        val sydney=LatLng(-34.0, 151.0)
        mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
    }
}
```


```kotlin
// activity_maps.xml

<?xml version="1.0" encoding="utf-8"?>
<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=".MapsActivity" />
``` 


```kotlin
// google_maps_api.xml (debug)

<resources>
    <!--
    TODO: Before you run your application, you need a Google Maps API key.

    To get one, follow this link, follow the directions, and press "Create" at the end:

    https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=...

    You can also add your credentials to an existing key, using these values:

    Package name:
    ...

    SHA-1 certificate fingerprint:
    ...
    Alternatively, follow the directions here:
    https://developers.google.com/maps/documentation/android/start#get-key

    Once you have your key (it starts with "AIza"), replace the "google_maps_key"
    string in this file.
    -->
    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">YOUR_API_KEY</string>
</resources>
``` 

  > If you're wondering if you need to add any dependencies for this code to run successfully, the answer is no you don't.

  - Now, you just need to provide the API key.

#### Create a new project on Google Cloud
  - Go over to the Google Cloud page → Create a new project
![1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1631291098556/Ddanb4AkU.png)
![2.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1631291153279/Bx6cmbBOE.png)

  - Enable the ***Maps SDK for Android***
![0.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1631291369577/0dRAwtt-s.png)

  - Credentials → Create Credentials → API key → Restrict key →  Android apps, Restrict key, Maps SDK for Android (Select APIs) → save → copy key
![5.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1631290770417/P6Z--l2ny.png)
![3.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1631290757531/pE-CnyK3O.png)
![6.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1631290827537/P9El9NAWg.png)
![7.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1631290839019/-VGE3lxpT.png)

  - Save.

#### Add the API key to your app
  - Paste the key in place of *YOUR_KEY_HERE*

  ```kotlin
      // google_maps_api.xml

         
<stringname="google_maps_key"templateMergeStrategy="preserve"translatable="false">YOUR_KEY_HERE</string>
  ```

   Now run the app & a beautiful map with a marker in Sydney should appear once the app installs on your device/emulator.
![54.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1631293432315/_zODNXQDC.png)