Home > Software design >  How to get latlngs values after edit a polygon in Leaflet-Geoman?
How to get latlngs values after edit a polygon in Leaflet-Geoman?

Time:10-19

Suppose I have a geojson data:

let featureCollection: GeoJSON.FeatureCollection<any> = {
  type: 'FeatureCollection',
  features: [
    {
      type: 'Feature',
      properties: {},
      geometry: {
        type: 'Polygon',
        coordinates: [
          [
            [103.80689620971681, 1.3101770944467952],
            [103.86285781860352, 1.3494769612490358],
            [103.916072845459,   1.2942167094566774],
            [103.86972427368165, 1.2540578798674866],
            [103.87229919433594, 1.3084609288747733],
            [103.83796691894533, 1.2660712704472294],
          ],
        ],
      },
    },
  ],
};

I tried to load that geojson value into a map and integrated with event handlers:

L.geoJSON(featureCollection, {
  onEachFeature: (feature: any, layer: L.Layer) => {
    layer.on('pm:edit', (e) => {
      console.log('loaded geojson - pm:edit', e);
    });
    layer.on('pm:rotateend', (e) => {
      console.log('loaded geojson - pm:rotateend', e.originLatLngs, e.newLatLngs);
    });
    map.addLayer(layer);
  },
});

Then I modified a polygon by selecting "Edit Layer" from toolbar UI, the browser will trigger pm:edit event:

See image

The debug console will print something like this:

Console output

The problem is: On pm:edit event, I didn't find any method to get coordinates of latitude and longitude due to TypeScript restriction, but the console showed _latlngs values (see output image). Moreover, some other events like pm:rotateend were able to support methods to get coordinate

What I want is: How to get the values of latitude and longitude on pm:edit event?

Edit: The leaflet version is ^1.7.1, @geoman-io/leaflet-geoman-free version is ^2.11.2

CodePudding user response:

In the pm:edit event you have the layer in the payload. From it you can use toLatLngs():

layer.on('pm:edit', (e) => {
   console.log(e.layer.getLatLngs())
});

BUT you will have a Problem with TypeScript because e.layer is from type L.Layer so you need first to cast / get the instance of the layer:

layer.on('pm:edit', (e) => {
  if(e.shape === 'Polygon'){
     (e.layer as Polygon).getLatLngs();
  }
});

More infos here: https://github.com/geoman-io/leaflet-geoman/issues/945

  • Related