Share
Explore

Google Location Services, City Maps, using Markers

The Completed Project:
You can either rebuild City Maps from the instructions below, or jump ahead to read the last chapter by getting the finalize Project and studying along here:

Here we work with Google Maps API, which we must register to use.
Start by visiting https://console.cloud.google.com
and Creating a Project and an API Key:

Next Steps: Make an Android Project to do the folloNextwing:
How to use the Google Maps Android API
The Google Location Services API
Show a user’s current location
Display and customize markers on a map
Display a specifed address on the map.
image.png


In creating a new lab project for building an Android app with Kotlin DSL that integrates Google Maps and location services, we will ensure that all parts of the project are consistent and use Kotlin DSL formulations.
The project will be called `myapp`.

In the Create New Project dialog, on the Create Android Project view, enter the name of the app as myapp if you wish to remain congruent with the package naming conventions in these code templates. If you name your App something else, just change the applicable package import strings.
Select your preferred folder location for the project files, make sure that Include Kotlin support, and click Next:

On the Target Android Devices view, check the Phone and Tablet box and select the minimum SDK you want the app to support. Specify API 16 from the Minimum SDK drop down and click Next.

On the Add an Activity to Mobile view, select the Google Maps Activity and click Next.
Create the standard empty activities template and do a special procedure to add maps support:
image.png
On the Configure Activity view, click Finish to complete the project creation process.

Android Studio will use Gradle to build your project. This may take a few seconds.
{When you update your starter template, frequently do File - Sync Project with Gradle Files, and do Build - Clean/ Rebuild / Make Project.


Lab Structure Overview:


1. **MainActivity.kt**:
Kotlin source file for the main activity handling user interactions with the map and location services.
2. **activity_main.xml**:
Layout file defining the UI, including the map view and address input.
3. **Project-level build.gradle.kts**:
Kotlin DSL file to configure project-wide settings like repositories and classpath dependencies.
4. **Module-level build.gradle.kts (app)**:
Kotlin DSL file for app-specific configurations like dependencies and Android-specific settings.
5. **settings.gradle.kts**:
Settings file for the project, specifying plugin management and resolution strategy.

Open MapsActivity.kt. Add the project code shown here :

image.png


MainActivity.kt : To have a complete and functional MainActivity.kt file.
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
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

class MainActivity : AppCompatActivity(), OnMapReadyCallback {

private lateinit var mMap: GoogleMap
private val LOCATION_PERMISSION_REQUEST = 1

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

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

// Check if we have location permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Request the permission
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
LOCATION_PERMISSION_REQUEST)
}
}

override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap

// Add a marker in Sydney, Australia, 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))

// If we have location permission, enable the My Location layer
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.isMyLocationEnabled = true
}
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
LOCATION_PERMISSION_REQUEST -> {
// If request is cancelled, the result arrays are empty.
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
// Permission was granted, do the location-related task you need to do.
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if(::mMap.isInitialized) {
mMap.isMyLocationEnabled = true
}
// activity_main.xml

To provide a complete activity_main.xml that includes a Google Map view and address input UI components, we can incorporate a SupportMapFragment to display the map and an EditText for user input to enter an address.
Additionally, we'll add a Button to trigger the map centering on the address entered. Here's the updated activity_main.xml:


Below is the updated activity_main.xml file that includes the SupportMapFragment for displaying Google Maps. This code assumes you want the map to fill the entire screen of the activity.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

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

</RelativeLayout>

This XML layout file defines a single SupportMapFragment that takes up the entire screen, as indicated by match_parent for both layout_width and layout_height. Once this file is set up, you can run your application, and it should display the map.
Remember to handle runtime permissions for accessing the location if you plan on showing the user's current location or any features that require location access.

You also need to implement the OnMapReadyCallback in your MainActivity to interact with the map once it's ready.



Here's a simple strings.xml file for your Android project that includes strings for the UI components in activity_main.xml:

<resources>
<string name="app_name">MyApp</string>
<string name="enter_address">Enter an address</string>
<string name="find_location">Find Location</string>
<!-- Add other strings for your app here -->
</resources>

In this strings.xml file:

The app_name string is the name of your application.
The enter_address string is used as a hint in the EditText where users will input an address.

The find_location string is the text on the Button that users can click to find the location they entered.

The strings.xml file is usually located in the res/values/ directory of your Android project. It's a good practice to use the strings.xml file for all user-facing text in your app, as it simplifies localization and maintenance.

To ensure the new lab app for location tracking and Google Maps integration is complete and functional, we need to ensure several components and configurations are correctly addressed:

AndroidManifest.xml: You need the proper permissions and metadata for Google Maps and location services:

Complete version of the AndroidManifest.xml for an application that uses Google Maps and location services:

Here's the completely updated AndroidManifest.xml file for your Android app with Google Maps integration. This includes all the necessary permissions and the Google Maps API key configuration:

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

<!-- Permissions for Google Maps and Location -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<!-- Google Maps API Key -->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY_HERE"/>

<!-- Main Activity -->
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.