Search code examples
javascriptreactjsleafletgeojsonreact-leaflet

Show specific marker and zoom to it on leaflet map when button is pressed


I want to call a specific object by name when one button is pressed in a json file and to be displayed on the map. And then the zoom and the map to be on this marker.

Structure of Json file:

type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [26.41389781, 41.9425557]
      },
      "properties": {
        "Name": "Парцел 1",
        "Crops": "Ябълки"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [26.41472289, 41.95044877]
      },
      "properties": {
        "Name": "Парцел 2",
        "Crops": "Ябълки"
      }
    },

A the moment i have one state which is true ot false.When is false there are no markers on the map, but when is true it shows all markers on the leaflet map.Now i want to have two or three buttons, and when one is pressed to call specific marker in the json file and show on the map

Button code,on click makes the condition to true:

   <button
            value={this.state.geojsonvisible}
            onClick={this.onGeojsonToggle}
          >
            Object 1
          </button>

Show popup for the markers:

 onEachFeaturePoint(feature, layer) {
    console.log("feature: ", feature);
    console.log("layer: ", layer);
    var popupContent =
      feature.properties.Name + "  " + feature.properties.Crops;
    layer.bindPopup(popupContent);
    layer.on({
      click: function (e) {
        console.log("e: ", e);
        console.log("click");
      },
    });
  }

This is my geojson tag:

 {this.state.geojsonvisible && (
              <GeoJSON
                data={points}
                onEachFeature={this.onEachFeaturePoint.bind(this)}
                // pointToLayer={this.pointToLayer.bind(this)}
              />
            )}

Solution

  • Place the marker coords on a featureGroup and the fit the bounds of the map using the bounds of the group where the selected marker resides.

     <Map
         ref={this.mapRef}
         center={position}
         ... />
    

    Use this event to fit the map depending on the passed coords as method params:

    onButtonClick = coords => {
        const map = this.mapRef.current;
        var group = new L.featureGroup([L.marker(coords)]);
        if (map) map.leafletElement.fitBounds(group.getBounds());
      };
    

    and invoke the method using the button click event:

    <button onClick={() => this.onButtonClick([41.9425557, 26.41389781])}>
          Zoom to marker 1
    </button>
    
    <button onClick={() => this.onButtonClick([41.95044877, 26.41472289])}>
        Zoom to marker 2
    </button>
    

    Demo