0

Desc:

Using leaflet and made an class called Map to use all features easily whenever I need, All set but there is simple problem that I can't handle it. map on init create a marker on center, but I want to let user create new marker on click but remove prev one, already if you click on map it create many marker, but I want only one marker.

JSFiddle

All I need is this code:

if (marker) this.map.removeLayer(marker);

But of course it give me such error:

ReferenceError: marker is not defined"

Problem:

Because prev marker created in marker() but new marker create in newMarker() function, so I have no idea how can I remove old marker, I did this before when my code wasn't class easily access let marker, but now I confused how to access marker variable in marker() function.

Goal: (in short)

I just want one marker after click on map, already it create many markers on map!

2 Answers 2

1

You can initialize an empty layerGrooup and store the marker there every time and when you add a new one you can clear the layers of the markerGroup.

Moreover you should not instantiate your map two times so you have only one map reference.

class Map {
  constructor(map, lat_long) {
    this.map = map;
    this.lat_long = lat_long;
    this.markerLayer = L.layerGroup().addTo(this.map)
  },
 ...
 newMarker(latLng) {
    this.markerLayer.clearLayers();

    L.marker(latLng, {
      draggable: true
    }).addTo(this.markerLayer);

  }
}

class Map {
  constructor(map, lat_long) {
    this.map = map;
    this.lat_long = lat_long;
    this.markerLayer = L.layerGroup().addTo(this.map)
  }
  get init() {
    return this.display();
  }
  display() {
    this.map.setView(this.lat_long, 14);
    this.tile();
    this.marker();
  }
  tile() {
    L.tileLayer('https://tiles.stadiamaps.com/tiles/alidade_smooth/{z}/{x}/{y}{r}.png', {
      maxZoom: 20,
    }).addTo(this.map);
  }
  marker() {
    let marker = L.marker(this.lat_long, {
      draggable: true
    }).addTo(this.markerLayer);
  }
  newMarker(latLng) {
    this.markerLayer.clearLayers();

    L.marker(latLng, {
      draggable: true
    }).addTo(this.markerLayer);

  }
}

let lat_long = [40.741895, -73.989308];
let leaflet = new L.map('map');
const map = new Map(leaflet, lat_long);
map.init;

leaflet.on('click', function(e) {
  map.newMarker([e.latlng.lat, e.latlng.lng]);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ==" crossorigin="" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-BB3hKbKWOc9Ez/TAwyWxNXeoV9c1v6FIeYiBieIWkpLjauysF18NzgR1MBNBXf8/KABdlkX68nAhlwcDFLGPCQ==" crossorigin=""></script>
<div id="map" style="height:400px"></div>

0

this.mymap.addLayer(this.state.markers); prevState.markers.remove(this.mymap);

import "leaflet.markercluster/dist/leaflet.markercluster-src";
import "leaflet.markercluster/dist/leaflet.markercluster";
import "leaflet.markercluster/dist/MarkerCluster.Default.css";
import "leaflet.markercluster/dist/MarkerCluster.css";
componentDidUpdate(prevProps, prevState) {
      // console.log(
      //     'componentDidUpdate',
      //     prevState.markers,
      //     this.state.markers
      // );
      if (
        prevState.markers !== undefined&&
        prevState.markers !== this.state.markers
      ) {
          // console.log('action=remove marker');
          prevState.markers.remove(this.mymap);
      }
    }

    markerCluster(markerClusterData){
      console.log('markerClusterData',markerClusterData)
      const greenIcon = new L.Icon({
        iconUrl:
            'https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png',
        shadowUrl:
            'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
        iconSize: [25, 41],
        iconAnchor: [12, 41],
        popupAnchor: [1, -34],
        shadowSize: [41, 41],
      });
      let markers = L.markerClusterGroup();
      for (let i = 0; i < markerClusterData.length; i++) {
        let addressPoint = markerClusterData[i];
        let title = `<b>${markerClusterData[i]}</b>`;
        let marker = L.marker(new L.LatLng(addressPoint[0], addressPoint[1]), {icon: greenIcon}).bindPopup(title);
        markers.addLayer(marker);
      };
      this.setState({'markers':markers},()=>this.mymap.addLayer(this.state.markers));
    }
<Button onClick={()=>this.markerCluster([[24.6949409651268, 121.313537600025]])}>Button1</Button>
<Button onClick={()=>this.markerCluster([[24.6949409651268, 121.313537600025],[24.6944257339445, 121.308595784335]])}>Button2</Button>

Not the answer you're looking for? Browse other questions tagged or ask your own question.