Search code examples
apikotlingoogle-mapslocationmarkers

clear() does not work for erasing markers while using Google Maps API


I'm using the Google Maps API in Kotlin and i'm trying to clear all the all ready generated markers from it before creating one of my own, but it doesn't seem to work.

The code is below:

        val mapFragment:SupportMapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }

    override fun onMapReady(mapaCreado: GoogleMap) {
        mapaCreado.apply{
            mapaCreado.clear()

            val coordenadas = LatLng(37.37410286896958, -5.969290673333865)
            addMarker(
                MarkerOptions()
                    .position(coordenadas)
                    .title("IES NERVION")
            )
        }
        map = mapaCreado
    }

Solution

  • Main reason code wasn't working is because .clear in Google Maps class does not refer to the actual markers that it has by default, but instead it refers to the one you create on it.

    The markers the Google Maps has by default are refered to as labels, and must be removed via styling, either using Google Maps Cloud Styling (not free apparently) or by creating your own style with JSON and setting it.

    [
      {
        "featureType": "poi",
        "elementType": "labels",
        "stylers": [
          {
            "visibility": "off"
          }
        ]
      }
    ]
    

    Then in your code.

    setMapStyle(MapStyleOptions.loadRawResourceStyle(this@MainActivity, R.raw.map_style));
    

    Where R.raw.map_styles refers to the JSON file you created earlier.