0
votes

So I'm using leaflet-react and I need to add some circle markers.

Now this code works...sometimes. On map click a circle marker should be added but sometimes it is not. Seemingly randomly it will just not add a visible marker. Sometimes the marker will become visible if I change the zoom level but not always. All the code runs each time so it's not that addMarker() isn't been called, also the removal of the last marker(by clearing the mark layer) always runs.

Thanks, Ed.

1

1 Answers

2
votes

It appears that you aren't using the react-leaflet package. I'd recommend trying that out. Here is some example code for how you'd add markers to the map on click events:

const React = window.React;
const { Map, TileLayer, Marker, Popup } = window.ReactLeaflet;

class SimpleExample extends React.Component {
  constructor() {
    super();
    this.state = {
      markers: [[51.505, -0.09]]
    };
  }

  addMarker = (e) => {
    const {markers} = this.state
    markers.push(e.latlng)
    this.setState({markers})
  }

  render() {
    return (
      <Map 
        center={[51.505, -0.09]} 
        onClick={this.addMarker}
        zoom={13} 
        >
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
        />
        {this.state.markers.map((position, idx) => 
          <Marker key={`marker-${idx}`} position={position}>
          <Popup>
            <span>A pretty CSS3 popup. <br/> Easily customizable.</span>
          </Popup>
        </Marker>
        )}
      </Map>
    );
  }
}

window.ReactDOM.render(<SimpleExample />, 
document.getElementById('container'));

And here's a jsfiddle showing the implementation: https://jsfiddle.net/q2v7t59h/413/