JSFiddle - React, Tailwind, and code Playground

by diogocosta

HTML

<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css">
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>

<div id='map'></div>
<button onclick="removeMarker()">Remove the marker</button>

CSS

html, body {
  height: 100%;
  margin: 0;
}
#map {
  width: 600px;
  height: 400px;
}
button {
  cursor: pointer;
  margin: 10px;
  padding: 8px;
  font-size: 16px;
  background-color: orange;
  border: 0;
  border-radius: 4px;
}

JavaScript

const map = L.map('map').setView([51.5, -0.09], 13);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);

const LeafIcon = L.Icon.extend({
  options: {
    shadowUrl: 'https://leafletjs.com/examples/custom-icons/leaf-shadow.png',
    iconSize:     [38, 95],
    shadowSize:   [50, 64],
    iconAnchor:   [22, 94],
    shadowAnchor: [4, 62],
    popupAnchor:  [-3, -76]
  }
});

const greenIcon = new LeafIcon({iconUrl: 'https://leafletjs.com/examples/custom-icons/leaf-green.png'})
const redIcon = new LeafIcon({iconUrl: 'https://leafletjs.com/examples/custom-icons/leaf-red.png'})
const orangeIcon = new LeafIcon({iconUrl: 'https://leafletjs.com/examples/custom-icons/leaf-orange.png'})

const greenMarker = L.marker([51.5, -0.09], {icon: greenIcon}).addTo(map)
const redMarker = L.marker([51.495, -0.083], {icon: redIcon}).addTo(map)
const orangeMarker = L.marker([51.49, -0.1], {icon: orangeIcon}).addTo(map)

const removeMarker = function () {
	/* SOLUTION ONE: REMOVE THE MARKER LAYER (GOOD) */
	map.removeLayer(orangeMarker)
	/* SOLUTION TWO: HIDE THE MARKER (POOR) */
  // orangeMarker.setOpacity(0)
}