Adding a Google Map πŸ—ΊοΈπŸ’—

Adding a Google Map πŸ—ΊοΈπŸ’—

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.

// 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))
    }
}
// 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" />
// 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 2.png

  • Enable the Maps SDK for Android 0.png

  • Credentials β†’ Create Credentials β†’ API key β†’ Restrict key β†’ Android apps, Restrict key, Maps SDK for Android (Select APIs) β†’ save β†’ copy key 5.png 3.png 6.png 7.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

Β