Search code examples
reactjsleafletreact-leafletleaflet.draw

How to create button with function of draw polygons in Leaflet?


I want to create a button which function is the same as the toolbar in leaflet map.When is pressed the user can draw figures on the map onCreate function but i have no idea how to make a button with this option to draw polygons.

This is my code of the component which initialize the leaflet map:

export class Dashboard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      filenames: [],
      downloadURLs: [],
      lat: 42.696295,
      lng: 23.303643,
      zoom: 10,
      image: null,
      url: "",
      progress: 0,
      files: [],
      uploadValue: 0,
      filesMetadata: [],
      rows: [],
    };
  }
  //Set location when the map is visualized

  mapRef = createRef();



  onCreate = (e) => {
    var layer = e.layer;
    console.log("Polygon Cordinates", layer.getLatLngs());
    console.log("Log_Create_Shape: ", e);

    var drawedCord = layer.toGeoJSON().geometry.coordinates;
    for (const result of drawedCord) this.props.saveData(result);

    console.log("shape1", drawedCord);

    var data = layer.toGeoJSON();
    var convertedData = "text/json;charset=utf-8," + JSON.stringify(data);
    console.log(convertedData);
    var FileSaver = require("file-saver");
    var blob = new Blob([convertedData], { type: "text/plain;charset=utf-8" });
    FileSaver.saveAs(blob, "cordinates.json");
  };



  componentDidMount() {}

  render() {

      return (

This is my map:

    <div id="map" className="dashboard container">
              <br />
              <HorizontalLinearStepper />
              <br />
              <hr />
<button>Draw polygon</button>
              <br />
              <Map
            style={{ height: "50vh" }}
            center={position}
            zoom={13}
            onClick={this.handleClick}
            onCreate={this.onCreate}
            onLocationfound={this.handleLocationFound}
          >
            <TileLayer
              attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
              url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"
            />
            <FeatureGroup>
              <EditControl
                position="topleft"
                onEdited={this._onEditPath}
                onCreated={this.onCreate}
                onDeleted={this._onDeleted}
                onMounted={this._mounted}
                onEditStart={this._onEditStart}
                onEditStop={this._onEditStop}
                onDeleteStart={this._onDeleteStart}
                onDeleteStop={this._onDeleteStop}
                draw={{
                  rectangle: false,
                }}
              />
            </FeatureGroup>
            <Polygon color="purple" positions={polygon} />
            <GeoJSON
              data={london_postcodes}
              style={this.geoJSONStyle}
              onEachFeature={this.onEachFeature}
            />
          </Map>


}

Solution

  • I had exactly the same issue and came up with a solution after checking this post

    So, in case of a polygon, your draw button should have an onClick event like this:

    const mapEvent =(e)=> {
        var e = document.createEvent('Event');
        e.initEvent('click', true, true);
        var cb = document.getElementsByClassName('leaflet-draw-draw-polygon');
        return !cb[0].dispatchEvent(e);
    };
    <button onClick={(e)=> {mapEvent(e)}}>
      Draw polygon
    </button>

    Use CSS to hide the default toolbar buttons:

    .leaflet-draw-draw-polygon {
      display: none !important;
    }

    You can use this method for multiple leaflet elements or actions just use the following classes instead of leaflet-draw-draw-polygon in the above example:

    • polyline: leaflet-draw-draw-polyline,
    • marker: leaflet-draw-draw-marker,
    • edit: leaflet-draw-edit-edit,
    • remove: leaflet-draw-edit-remove,
    • etc...

    It is not the most elegant solution, but it works and saved me from further trouble.