What is the way to obtain the location coordinates of a polygon using ngx-leaflet-draw?

I have successfully integrated ngx-leaflet-draw into my angular6 project and am able to draw polygons on the map. However, I am struggling to retrieve the coordinates of the polygon locations. My goal is to show users within the polygon area by querying a database. Despite consulting the official documentation, I have not been able to find a solution.

Below is an excerpt from my app.component.ts file:

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);
}


}

Here is a snippet from my app.component.html file:

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

This is my first time using the Leaflet map library. Any assistance in finding a solution would be greatly appreciated.

Answer №1

To interact with the map using Leaflet library, listen for the onMapReady event and follow these steps:

Include this in your template:

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

In your component file, add the following code snippet:

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

        if (type === 'polygon') {
            const polygonCoordinates = layer._latlngs;
            console.log(polygonCoordinates);
        }
    });
}

For a demo, visit here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Converting an object array into my own custom type array: A step-by

I have a class: export class Items { id: string; itemName: string; } Previously, when using Angular version less than 4.3, I had this method: getItems(): Observable<Items[]> { return this.http.get('api-url-here/items&ap ...

Determining if an object aligns with a specific type in Typescript

Hey there, I've got a little dilemma. Imagine I have a type called A: type A = { prop1: string, prop2: { prop3: string } } Now, let's say I'm getting a JSON object from an outside service and I need to check if that JSO ...

How long do route providers typically last?

When using standalone components, we have the ability to place services into route providers. I couldn't locate this information in the documentation - what is the lifespan of these service instances? Are they destroyed when the route becomes inacti ...

Building stateless functional components in React using Typescript version 0.14

Demonstration: import * as React from 'react' declare function obtainMarineLife(x: any): any; declare var Tank: any; var OceanicHabitat = ({category}) => ( <Tank> {obtainMarineLife(category)} </Tank> ); let y = <Ocea ...

Organize collections according to the unique identifiers of the documents

My goal is to display a list of documents based on their IDs stored in an array. Here are the rules I am using: rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { function isSignedIn() { return r ...

Properly managing variable overrides in an Angular library

I am currently developing a unique design library using the latest versions of Bootstrap 5 and Angular. In order to customize the look to fit my specific design needs, I am utilizing the core Bootstrap framework and adding extensions or custom styles. My ...

The art of connecting models in Angular 2

Hey there! I've got a setup that seems to be giving me some unexpected results. Whenever I make changes to either the Kelvin or Celsius field, I end up with strange outputs like multiplying by 1000 or other inexplicable numbers. I'm new to Angula ...

Developing collaborative functions in Angular

Is there a way in Angular 9 to directly call static methods from HTML without using shared services or defining methods in components? I came across an old approach on How to call static method of other class in .html (not in .ts)?, but I am curious if the ...

Navigating from one page to another in Ionic is a crucial aspect of building a smooth user

As I explore transitioning between pages in the IONIC framework, I have developed the following code: <div *ngFor="let list of product"> <img [src] ='list.imge'/> <button ion-button round (click)="Contact()">view</button ...

Instantly share data lists between unrelated components using RxJS in Angular

Having an issue with sharing data via Service and BehaviorSubject in Angular application. The scenario involves two components that are not related. When clicking on the main outlet, the goal is to update the data list on the service and change the data on ...

Having trouble locating the Angular Material core theme within the asp.net core 2.0 template using Angular 5

CustomConfig.js const treeModules = [ '@angular/animations', '@angular/common', '@angular/compiler', '@angular/core', '@angular/forms', '@angular/http', '@angular ...

Is it feasible to use a component in a recursively manner?

Following a two-hour search for a solution, I decided to reach out to experts as I suspected the answer might be simpler than expected. The project in question is an Angular7 one. In my goals component, I aim to include a "goal" with a button labeled "+". ...

Tips for updating the value of a dynamically fetched field in a Firestore document using Cloud Functions

I have a simple question: How can I update a field in a firestore document when the field name is only known dynamically through a variable? const myCounterName = "exampleName"; const docRef = admin.firestore().collection("metadata").do ...

How can I apply styling to Angular 2 component selector tags?

As I explore various Angular 2 frameworks, particularly Angular Material 2 and Ionic 2, I've noticed a difference in their component stylings. Some components have CSS directly applied to the tags, while others use classes for styling. For instance, w ...

Utilizing Dual Destructuring for Handling Undefined Main Objects

Before we proceed, I want to clarify that my question is not a duplicate of ES6 double destructure Let's examine the code snippet related to Apollo Client GraphQL: import { gql, useQuery, useMutation } from '@apollo/client'; ... const { loa ...

redux-saga 'call' effect fails to properly type saga parameters

My saga is defined as follows: type GenericFunction = (...args: any[]) => any; interface IFetchSaga<T extends GenericFunction> { saga: T, args: Parameters<T> } function* triggerChange<T extends GenericFunction>(fetchSaga: IFetchS ...

Adding an external JavaScript library to a gateway project: A step-by-step guide

I've been attempting to integrate the Simpl5 JavaScript library into my gateway, but I have encountered some issues. I placed SIPml-api.js and SIPml.js in the webapp/content/scripts directory. In .angular-cli.json, I updated the scripts array as follo ...

Simplify if statements by eliminating repetition

I have been tasked with refactoring the code below and I have already done so (check the image for reference). However, my supervisor is still not satisfied with the changes, LOL. const { appTargetId, appUserTargetId, appUserId } = buildIndexKeys(input); ...

When working with ag-grid in Angular 2, the gridOptions.api.refreshView() method may not effectively update the grid data

When the Edit button is clicked, I am updating the gridOptions by toggling the editable property of columns to true and making other data changes. Although the gridOptions property is updated correctly, calling this.gridOptions.api.refreshView() inside the ...

When in development mode, opt for the unminified version of the library in Web

My TypeScript project utilizes a forked version of the apexcharts npm package. When building the project with webpack in development mode, I want to use the unminified version of the apex charts library. However, for production, I prefer to stick with the ...