0

I need to superimpose polygons on leaflet map based on the data in the geojson file as I need to display custom location names for areas. This geojson file contains co-ordinates of polygon along with the name for the location. So far I have successfully created polygons over map. But now I need to get the location for the particular polygon from geojson file based on where the marker's drag end event has stopped. I have done below code:

   this.polygons = [];

    let self = this;
    fetch('assets/Chesapeake_Bay_92_Segments.geojson')
      .then(function (response) {
        console.log("Response")
        return response.json();

      })
      .then(function (data) {
        // use geoJSON
        console.log("Use geoJSON")
        leaflet.geoJSON(data, {
          style: function (feature) {
            return {
              fillColor: 'blue',
              weight: 2,
              opacity: 1,
              color: 'white',  //Outline color
              fillOpacity: 0.7
            };
          }, onEachFeature: function (feature:any, layer) {
            console.log("Feature", feature)
          
            let polygonLocationData: PolygonLocation = {
              polygon: leaflet.polygon(geometry.coordinates, { color: 'red' }),
              location: feature.location,
              shapeArea: feature.Shape_Area
            }
            self.polygons.push(polygonLocationData);
          },
        }       
        ).addTo(self.map);
      });

1 Answer 1

0

You need to create a draggable marker and then listen on the dragend event. Then loop through all polygons and check if it contains the marker position. For example with turf.js/booleanWithin

Should look similiar to this (not tested):

var marker = L.marker(self.map.getCenter(), {draggable: true}).addTo(self.map)
marker.on('dragend',(e)=>{
   var point = marker.toGeoJSON();
   self.polygons.forEach((polygonData)=>{
      if(turf.booleanWithin(point, polygonData.polygon.toGeoJSON())){
         console.log(polygonData)
         break;
      }
   })
});

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