How to add marker on google map with Kotlin?

Viewed 2885

I am a beginner in Android programming. I want to add a marker at the point by tapping the Map screen. So I have tried coding below. But it doesn't work.

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

    mMap.setOnMapClickListener(object :GoogleMap.OnMapClickListener {
        override fun onMapClick(latlng :LatLng) {
            val location = LatLng(latlng.latitude,latlng.longitude)
            mMap.addMarker(MarkerOptions().position(location))
        }
    })
}
2 Answers
googleMap!!.addMarker(
    MarkerOptions()
        .position(
            LatLng(
                mapViewModel!![i].mLongitude,
                mapViewModel!![i].mLatitude
            ))
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_mc_one))
        .title("" + mapViewModel!![i].mOrganizationName.capitalize())
        .snippet("" + mapViewModel!![i].mOrganizationTagLine.capitalize())
)

Before add Marker on GoogleMap I would suggest to clean the map and animate the camera to new tapped position.

Hope this helps you:

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

    mMap.setOnMapClickListener(object :GoogleMap.OnMapClickListener {
        override fun onMapClick(latlng :LatLng) {
            // Clears the previously touched position
            mMap.clear();
            // Animating to the touched position
            mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

            val location = LatLng(latlng.latitude,latlng.longitude)
            mMap.addMarker(MarkerOptions().position(location))
        }
    })
}
Related