Combining marker, circle, and polygon layers within an Angular 5 environment

I am working on a project where I have an array of places that are being displayed in both a table and a map. Each element in the table is represented by a marker, and either a circle or polygon. When an element is selected from the table, the marker icon changes for that specific element. Additionally, there is a slider to adjust the radius of the circles for each element. Currently, all these elements are updated together, but I want to separate the marker, circle, and polygon layers and then group them using layerGroup. This way, when I change the radius, only the circle layer will be updated without affecting the markers and polygons. Similarly, if I select an element from the table, only the marker layer should be updated without impacting the other layers. I have attempted to group the layers like this:

    updateLayers(layerData) {
    this.marker = [];
    for (const ld of layerData) {
      this.marker.push(
        marker([ld['latitude'], ld['longitude']], {
          icon: icon({
            iconSize: [20, 32],
            iconAnchor: [10, 16],
            iconUrl: this.selectedPlaces.indexOf(ld) !== -1 ? this.iconEnablelink : this.iconDisableLink
          })
        }),
        // ld['geofence_type'] && ld['geofence_type'] == 'POLYGON' ? polygon([ld['geofence']['coordinates'][0][0]]) : circle([ld['latitude'], ld['longitude']], { radius: this.radius }),
      );
    }
    console.log('lg', layerGroup([this.marker]));
    this.layers = layerGroup([this.marker]);
  }

The response I receive is as follows:

   options: {}
   _initHooksCalled: true
   _layers: {45: Array(25)}
   __proto__: NewClass

However, I encounter the following error: "Error trying to diff '[object Object]'. Only arrays and iterables are allowed."

I am looking for an efficient solution to implement this functionality.

Edit: I have included a snippet of the functioning code below. Whenever I click on a checkbox, I add or remove that element to selectedPlaces. Then I call the function again. Even when the slider is changed, I must continue calling this function repeatedly. The layers currently include markers, polygons, and sliders, but I aim to separate these into three distinct parts so that selecting an element updates only the marker (ideally for that particular element), and changing the radius via the slider updates only the circles without affecting the markers and polygons.

updateLayers(layerData) {
this.layers = [];
for (const ld of layerData) {
  this.layers.push(
    marker([ld['latitude'], ld['longitude']], {
      icon: icon({
        iconSize: [20, 32],
        iconAnchor: [10, 16],
        iconUrl: this.selectedPlaces.indexOf(ld) !== -1 ? this.iconEnablelink : this.iconDisableLink
      })
    }),
    ld['geofence_type'] && ld['geofence_type'] == 'POLYGON' ? polygon([ld['geofence']['coordinates'][0][0]]) : circle([ld['latitude'], ld['longitude']], { radius: this.radius }),
  );
}

Answer №1

If you're looking to adjust the radius of all your circles when using a slider, here's how you can do it:

You've already set up some layers in Leaflet and saved them in a Layer Group within your this.layers property.

To achieve this, follow these steps:

  1. Go through each layer in your Layer Group using the eachLayer method.
  2. Verify if the layer is a type of L.Circle (or Circle if you've imported it).
  3. Modify the Circle's radius by utilizing its setRadius method.

var paris = [48.86, 2.35];
var map = L.map('map').setView(paris, 11);
var group = L.layerGroup().addTo(map);

document.getElementById('radius').addEventListener('input', changeRadius);

function changeRadius(event) {
  var newRadius = event.target.value;

  group.eachLayer(function(layer) {
    if (layer instanceof L.Circle) {
      layer.setRadius(newRadius);
    }
  });
}

var circle = L.circle(paris, {
  radius: 1000,
}).addTo(group);

var marker = L.marker(paris).addTo(group);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
<link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="58343d393e343d2c1869766b766b7275">[email protected]</a>/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f79b9296919b9283b7c6d9c4d9c6">[email protected]</a>/dist/leaflet-src.js" integrity="sha512-IkGU/uDhB9u9F8k+2OsA6XXoowIhOuQL1NTgNZHY1nkURnqEGlDZq3GsfmdJdKFe1k1zOc6YU2K7qY+hF9AodA==" crossorigin=""></script>

<input id="radius" type="range" min=500 max=3000 value=1000 />
<div id="map" style="height: 160px"></div>

Answer №2

It seems like the issue here is that you are directly assigning this.layers to a layerGroup, which is not allowed. In order for this.layers to work properly, it needs to be an array or an iterable object.

You can resolve this problem by trying the following approach:

updateLayers(layerData) {
    this.marker = [];

    ...

    console.log('lg', layerGroup([this.marker]));
    this.layers = [ layerGroup([this.marker]) ];
}

The ngx-leaflet plugin specifically requires this.layers to be in array format. It can contain any object recognized by Leaflet as a Layer. This includes arrays of layerGroups, such as:

this.layers = [ layerGroup([...], layerGroup[...], ...];

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

JavaScript: Trouble accessing .target property for click event in EventTarget object

After converting my project from regular JavaScript to TypeScript, I encountered an issue where the target property of a base class EventTarget was not being recognized by TypeScript. This property worked perfectly fine in JS, so it must exist. Could it be ...

Utilizing StyleFunctionProps within JavaScript for Chakra UI Enhancements

I need help figuring out how to implement StyleFunctionProps in my Chakra UI theme for my NextJS project. The documentation on Chakra's website provides an example in Typescript, but I am working with Javascript. Can someone guide me on adapting this ...

Guide to specifying the indexer type of a function argument as T[K] being of type X in order for t[k]=x to be a permissible expression

Currently, I am attempting to create a function that can alter a boolean property within an object based on the provided object and property name. While I have found some helpful information here, the function body is still producing errors. Is there a way ...

Saving any type of file in SQL Server with a field type of varbinary(max) can be achieved by utilizing Angular with ASP.NET Core to create a REST API

I am currently facing an issue while attempting to save a file, such as an image, in the Microsoft SQL Server Management Studio through asp .NET core for the Rest API. I have managed to create a base64 representation of the file, but I am unsure about the ...

Execute the render function of the components that have been passed as

I've been grappling with a challenge lately - figuring out how to invoke a passed component's render function within another function. Let's say I have two functions named A and B: export const A = (value: any) => { return ( <div& ...

Error: The specified property is not found in type 'never' - occurring with the ngFor loop variable

When working with API responses and dynamically sorting my view, I utilize an ngFor loop. Here's the snippet of code in question: <agm-marker *ngFor="let httpResponses of response" [latitude]= "httpResponses.lat" [longitude]=& ...

What is the best approach to apply type casting in an *ngFor loop for an array containing a variety of types in Angular?

I am facing a scenario where I have two objects named DeviceA and DeviceB, both belonging to the same parent class called Device. interface Device { shared: string } interface DeviceA extends Device { attributeA: string[] } interface DeviceB extends ...

Having trouble pinpointing the specific custom exception type when using the throw statement in TypeScript?

I have run into a problem while using a customized HttpException class in TypeScript. Let me show you how the class is structured: class HttpException extends Error { public status: number | undefined; public message: string; public data: any; ...

What is the best way to loop through a formarray and assign its values to a different array in TypeScript?

Within my form, I have a FormArray with a string parameter called "Foo". In an attempt to access it, I wrote: let formArray = this.form.get("Foo") as FormArray; let formArrayValues: {Foo: string}[]; //this data will be incorporated into the TypeScript mod ...

Tips on personalizing the FirebaseUI- Web theme

Can someone help me find a way to customize the logo and colors in this code snippet? I've only come across solutions for Android so far. if (process.browser) { const firebaseui = require('firebaseui') console.log(firebaseui) ...

When I attempt to conceal the filter within mat-table using *ngIf, I encounter an issue where I am unable to read the property 'value' due to it being

After creating a mat-table, I encountered an issue when trying to show and hide my input filter area using a button. If I use *ngIf="showInputFilter" to hide the filter area, I receive the error message Cannot read property 'value' of u ...

`Running ng serve will result in the creation of a 'dist' folder within each app sub

Since beginning my project, I have encountered an issue that is both normal and frustrating. The dist folder is being created with incomplete information related to the components inside it. dashboard dist (unwanted) components panel dist (unwanted) c ...

ESLint is reporting an error of "Module path resolution failed" in a project that includes shared modules

Encountering ESLint errors when importing modules from a shared project is causing some frustration. The issue arises with every import from the shared/ project, presenting the common ESLint import error: Unable to resolve path to module 'shared/hook ...

Error: The value of the expression has been altered after it was already checked. Initial value was 'undefined'. An exception has occurred

Although this question has been asked multiple times, I have read similar issues and still struggle to organize my code to resolve this particular exception. Within my component, there is a property that dynamically changes based on a condition: public e ...

What could be causing my component to not refresh when used as a child?

I have been experimenting with some code to track rerenders. The initial approach failed when passing <MyComponent> as a child component. it("should return the same object after parent component rerenders", async () => { jest.useF ...

Using the typeof operator to test a Typescript array being passed as an object

I have a puzzling query about this particular code snippet. It goes like this: export function parseSomething(someList: string[]): string[] { someList.forEach((someField: string) => { console.log(typeof someField) }) Despite passing a s ...

Organizing Angular models and interfaces

The Angular styleguide provides best practices for using classes and interfaces in applications, but it does not offer guidance on organizing interfaces and model classes. One common question that arises is: what are the best practices for organizing file ...

Navigate using history.push with user Logout Icon

Currently, I am utilizing a Material UI icon as a logout button in my project. Here is how I have implemented it: function logout(props:any){ localStorage.removeItem("token"); return( <Redirect to="/login" /> ) //props.history.push("/log ...

When using TypeScript, it is important to ensure that the type of the Get and Set accessors for properties returning a

Why is it necessary for TypeScript to require Get/Set accessors to have the same type? For example, if we want a property that returns a promise. module App { export interface MyInterface { foo: ng.IPromise<IStuff>; } export int ...

When utilizing the catch function callback in Angular 2 with RxJs, the binding to 'this' can trigger the HTTP request to loop repeatedly

I have developed a method to handle errors resulting from http requests. Here is an example of how it functions: public handleError(err: any, caught: Observable<any>): Observable<any> { //irrelevant code omitted this.logger.debug(err);//e ...