简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM