Google Map In Android

Pandiyan Mani
3 min readApr 24, 2023

Let see how to add marker to the current location first we need to add the necessary permission on the manifest need to access location.

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

Let see the entire code of manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.GMap"
tools:targetApi="31">

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

To get one, follow the directions here:

https://developers.google.com/maps/documentation/android-sdk/get-api-key

Once you have your API key (it starts with "AIza"), define a new property in your
project's local.properties file (e.g. MAPS_API_KEY=Aiza...), and replace the
"YOUR_API_KEY" string in this file with "${MAPS_API_KEY}".
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="Your APi Key" />

<activity
android:name=".MapsActivity"
android:exported="true"
android:label="@string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

</manifest>
Your APi Key --> need to be added from google api console

for getting current location we are going to use fused location which is provided by google for getting location

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

on our xml file lets add the google map fragment

<?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" />

in our MapsActivity.kt lets see the code for getting location and ploating marker on map

package com.app.gmap

import android.Manifest
import android.content.pm.PackageManager
import android.location.Location
import android.os.Bundle
import android.os.Looper
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.app.gmap.databinding.ActivityMapsBinding
import com.google.android.gms.location.*
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.CameraPosition
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

private lateinit var mGoogleMap: GoogleMap
private lateinit var binding: ActivityMapsBinding
val MY_PERMISSIONS_REQUEST_LOCATION = 99

var mLocationRequest: LocationRequest? = null
var mLastLocation: Location? = null

var mFusedLocationClient: FusedLocationProviderClient? = null

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

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

mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

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

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

mLocationRequest = LocationRequest()
mLocationRequest!!.interval = 120000 // two minute interval

mLocationRequest!!.fastestInterval = 120000
mLocationRequest!!.priority =
com.google.android.gms.location.LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY

if (ContextCompat.checkSelfPermission(
this, Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
//Location Permission already granted
mFusedLocationClient!!.requestLocationUpdates(
mLocationRequest, mLocationCallback, Looper.myLooper()
)
mGoogleMap.setMyLocationEnabled(true)
} else {
//Request Location Permission
checkLocationPermission()
}
}

override fun onPause() {
super.onPause()

//stop location updates when Activity is no longer active
mFusedLocationClient?.removeLocationUpdates(mLocationCallback)
}

var mLocationCallback: LocationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
val locationList = locationResult.locations
if (locationList.size > 0) {
//The last location in the list is the newest
val location = locationList[locationList.size - 1]
mLastLocation = location
val latLng = LatLng(location.latitude, location.longitude)
// Creating a marker
val markerOptions = MarkerOptions()

// Setting the position for the marker
markerOptions.position(latLng)

// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(location.latitude.toString() + " : " + location.longitude)

// Clears the previously touched position
mGoogleMap.clear()

// Animating to the touched position
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng))

// Placing a marker on the touched position
mGoogleMap.addMarker(markerOptions)
val cameraPosition =
CameraPosition.Builder().target(LatLng(latLng.latitude, latLng.longitude))
.zoom(18f).build()
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
}
}
}


private fun checkLocationPermission() {
if (ContextCompat.checkSelfPermission(
this, Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {

// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(
this, Manifest.permission.ACCESS_FINE_LOCATION
)
) {

// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
AlertDialog.Builder(this).setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton(
"OK"
) { _, i -> //Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(
this@MapsActivity,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
MY_PERMISSIONS_REQUEST_LOCATION
)
}.create().show()
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
MY_PERMISSIONS_REQUEST_LOCATION
)
}
}
}


}

Final output:

--

--