Google Map Places Api in Android Kotlin.

Harshita Bambure
3 min readOct 21, 2021

Many times we search addresses in google map for that functionality we need google Maps places API so let's start with google places API.

First of all, you need to generate your API key from google console API.

After that, we need to add google place API dependencies in the build.Gradle(:app)

//google places api
implementation 'com.google.android.libraries.places:places:2.5.0'

For the map, I used MapActivity from android studio. So, let's start with the design part.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/txt_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="map address"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/btn_next"
android:text="next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

activity_maps.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MapsActivity">

<fragment
android:id="@+id/place_autocomplete_fragment"
android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

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



</LinearLayout>

In strings.xml you need to add your map API key.

MainActivity.kt

package com.example.mapplaceapi

import android.annotation.SuppressLint
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.app.Activity
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.Nullable


class MainActivity : AppCompatActivity() {


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


btn_next.setOnClickListener {
openActivityForResult()
}
}

fun openActivityForResult() {
val intent = Intent(this, MapsActivity::class.java)
startActivityForResult(intent, 123)
}

@SuppressLint("MissingSuperCall")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == RESULT_OK && requestCode == 123) {
var lat = data?.getStringExtra("location")
var lang = data?.getStringExtra("latlang")
txt_address.text= lat+","+lang
}

}
}

In the map activity, I also used activity result for sending data to the previous activity.

MapsActivity.kt

package com.example.mapplaceapi

import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast

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.example.mapplaceapi.databinding.ActivityMapsBinding
import com.google.android.gms.common.api.Status
import com.google.android.libraries.places.api.Places
import com.google.android.libraries.places.api.model.Place
import com.google.android.libraries.places.api.net.PlacesClient
import com.google.android.libraries.places.widget.AutocompleteSupportFragment
import com.google.android.libraries.places.widget.listener.PlaceSelectionListener
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_maps.*

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mMap: GoogleMap
private lateinit var binding: ActivityMapsBinding
var placesClient: PlacesClient? = null

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

binding = ActivityMapsBinding.inflate(layoutInflater)
setContentView(binding.root)
val apiKey = getString(R.string.google_maps_key)
if (!Places.isInitialized()) {
Places.initialize(applicationContext, apiKey)
}
// Create a new Places client instance.
placesClient = Places.createClient(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)

val autocompleteFragment =
supportFragmentManager.findFragmentById(R.id.place_autocomplete_fragment) as AutocompleteSupportFragment?
autocompleteFragment!!.setPlaceFields(
listOf(
Place.Field.ID,
Place.Field.ADDRESS,
Place.Field.LAT_LNG
)
)


autocompleteFragment.setOnPlaceSelectedListener(object : PlaceSelectionListener {
override fun onPlaceSelected(place: Place) {
val address = place.address.toString()

val latlong = "${place.latLng?.latitude!!}::${place.latLng?.longitude!!}"

val resultIntent = Intent()

resultIntent.putExtra("location", address)
resultIntent.putExtra("latlong", latlong)
setResult(Activity.RESULT_OK, resultIntent)
finish()
}

override fun onError(status: Status) {
Toast.makeText(applicationContext, status.toString(), Toast.LENGTH_SHORT).show()
}
})

}

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

// Add a marker in Ahmedabad and move the camera
val Ahmedabad = LatLng(23.0225, 72.5714)
mMap.addMarker(MarkerOptions().position(Ahmedabad).title("Marker in Ahmedabad"))
mMap.moveCamera(CameraUpdateFactory.newLatLng(Ahmedabad))
}
}

That's it. Happy Coding!!.

--

--

Harshita Bambure

Android Developer || WomenTech Global Ambassador at WomenTech Network. || Yoga Teacher || Member @WTM .