How get the location coordinates of polygon in ngx-leaflet-draw?

2.6k Views Asked by At

I integrated ngx-leaflet-draw for my angular6 project.I could draw polygon over the map.But I don't know how to get the polygon location coordinates.I want to show the users inside the polygon by performing database search.I went through the official documents but it didn't help me.

My app.component.ts file as below

import { Component } from '@angular/core';
import {tileLayer,latLng, marker, Marker} from 'leaflet';
import * as L from 'leaflet';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

    title = 'map';

    options = {
        layers: [
          tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png')
        ],
        zoom: 15,
        center: latLng(8.524139,76.936638)
    };

      drawOptions = {
        position: 'topright',
    draw: {
        marker: {
            icon: L.icon({
                iconSize: [ 25, 41 ],
                iconAnchor: [ 13, 41 ],
                iconUrl: '../../assets/marker-icon.png',
                shadowUrl: '../../assets/marker-shadow.png'
            })
        },
        polyline: false,
        circle: {
            shapeOptions: {
                color: '#aaaaaa'
            }
        }
    }
};

ngOnInit(){


}

sample(e) {
    console.log(e);
}


}

and my app.component.html file as:

<div leaflet style="height: 400px;"
     leafletDraw
     [leafletOptions]="options"
     [leafletDrawOptions]="drawOptions"
     (leafletDrawReady)="sample($event)"
     >
</div>

Using leaflet map for the first time.

Please help me to find a solution.

1

There are 1 best solutions below

5
On BEST ANSWER

You need to listen to the onMapReady event, get a reference to the map and do what you would do on plain Leaflet library:

template:

<div leaflet style="height: 400px;"
    leafletDraw
    [leafletOptions]="options"
    [leafletDrawOptions]="drawOptions"
    (leafletMapReady)="onMapReady($event)">
</div>

component:

onMapReady(map: Map) {
    map.on(L.Draw.Event.CREATED, function (e) {
        // const type = (e as L.DrawEvents.Created).layerType,
        // layer = (e as L.DrawEvents.Created).layer;
        const type = (e as any).layerType,
              layer = (e as any).layer


        if (type === 'polygon') {
            // here you got the polygon coordinates
            const polygonCoordinates = layer._latlngs;
            console.log(polygonCoordinates);
        }
    });
}

Demo