Search code examples
androidkotlingoogle-maps-android-api-3

Google Maps API (Android SDK). Every time location is updating through location listener, a new marker is showing in the maps


Every time location is updating through location listener, a new marker is coming in my map which looks so weird. I just want only one marker that will updated.

 override fun onMapReady(googleMap: GoogleMap?) {
    val locationListener = LocationListener {
        val latLng = LatLng(it.latitude,it.longitude)
        
        googleMap!!.addMarker(
            MarkerOptions()
                .position(latLng)
                .title("My Location")
        )

        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16f))
    }
    
    try {
        locationManager!!.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            1000, 0f, locationListener
        )
    } catch (ex: SecurityException) {
        ex.printStackTrace()
    }
}

Solution

  • Create a field in the class for the marker.

    private lateinit var locationMarker: Marker
    

    Only add a marker to map if your field has not been initialized else update the previous marker. Like so:

    val locationListener = LocationListener {
        val latLng = LatLng(it.latitude,it.longitude)
    
        if(::locationMarker.isInitialized) {
            locationMarker.position = latLng
        } else {
            locationMarker = googleMap!!.addMarker(
                MarkerOptions()
                    .position(latLng)
                    .title("My Location")
            )
        }
    
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16f))
    }