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

The data set in a setTimeout is not causing the Angular4 view to update as expected

I am currently working on updating a progress bar while importing data. To achieve this, I have implemented a delay of one second for each record during the import process. Although this may not be the most efficient method, it serves its purpose since thi ...

Selecting a GoJS Node using keys

In Angular with TypeScript, what is the best way to select a node from a diagram based on its key? Currently, I am required to left-click a newly created node in order to select it, but I would like for it to be automatically selected upon creation. I ha ...

How can I activate TypeScript interface IntelliSense for React projects in VSCode?

Did you know that there are TypeScript interfaces designed for DOM, ES5, and other JavaScript modules? I am curious if it is feasible to have intellisense similar to the one provided by TypeScript Playground for various interfaces in a React project. ...

Getting around using Material-UI Icons

Is it possible to utilize a Material-UI Icon for navigation using React Router Dom? I attempted the following approach without success: <NavigateBeforeIcon path="/vehicles"></NavigateBeforeIcon> With buttons, I am able to use component={Link ...

Angular Back button event not triggering

I'm attempting to redirect the user to a specific URL when they click the back button in their browser. Here is the code snippet: constructor(private router: Router,private location: PlatformLocation) { let eventUrl = window.sessionSt ...

Slim API receives a request from Ionic 5

Seeking assistance with making a GET request from my Ionic application to an API constructed using the Slim Framework. Below is the code snippet of the API: <?php header('Access-Control-Allow-Origin: *'); header('Content-Type: applicati ...

Managing time in an Angular application using Typescript

I am facing an issue with formatting the time obtained from an API in my FormArray. The time is received in the format: 14.21.00 My goal is to convert this time to the following format: 2:21 PM I have attempted to format it using Angular's DatePip ...

Exploring Angular 6: Unveiling the Secrets of Angular Specific Attributes

When working with a component, I have included the angular i18n attribute like so: <app-text i18n="meaning|description"> DeveloperText </app-text> I am trying to retrieve this property. I attempted using ElementRef to access nativeElement, bu ...

Is it possible to identify unauthorized utilization of web APIs within TypeScript?

Recently, I encountered an issue while using the URLSearchParams.size in my code. To my surprise, it didn't work on Safari as expected. Checking MDN's browser compatibility table revealed that Safari version 16.6 does not support this feature, un ...

Ensuring that a date is within a certain format in TypeScript

Can someone help me verify the validity of different date formats? I attempted the following method: let newdate = new Date(myStringDate); Date.parse(myStringDate) result = `${newdate.getDate()}/${newdate.getMonth() + 1}/${newdate.getFullYear()}` The re ...

The code encountered an error with message TS2345 stating that the argument type '(a: Test, b: Test) => boolean | 1' cannot be assigned to a parameter type of '(a: Test, b: Test) => number'

Apologies for the lengthy subject, but I am having trouble understanding the response. Here is my code snippet: this.rezerwacjeFilteredByseaarchInput.sort(function (a, b) { if (a[5]===null) { // console.log(a[5]); return 1; } ...

Maintaining checkbox selection while switching pages in Angular

When I try to edit the settings for accepting payments in all currencies under the "Pricing" component, the checkbox is unchecked every time I return to the "General" section. How can I prevent this from happening and keep the checkbox checked? Refer to ...

Stop allowing the entry of zero after a minus sign

One of the features on our platform allows users to input a number that will be automatically converted to have a negative sign. However, we want to ensure that users are unable to manually add a negative sign themselves. We need to find a solution to pre ...

I am attempting to code a program but it keeps displaying errors

What is hierarchical inheritance in AngularJS? I have been attempting to implement it, but I keep encountering errors. import {SecondcomponentComponent} from './secondcomponent/secondcomponent.Component'; import {thirdcomponentcomponent} from & ...

The `Home` object does not have the property `age` in React/TypeScript

Hey there, I'm new to React and TypeScript. Currently, I'm working on creating a React component using the SPFX framework. Interestingly, I'm encountering an error with this.age, but when I use props.age everything seems to work fine. A Typ ...

We could not find the requested command: nodejs-backend

As part of my latest project, I wanted to create a custom package that could streamline the initial setup process by using the npx command. Previously, I had success with a similar package created with node.js and inquirer. When running the following comma ...

Breaking down an object using rest syntax and type annotations

The interpreter mentions that the humanProps is expected to be of type {humanProps: IHumanProps}. How can I properly set the type for the spread operation so that humanPros has the correct type IHumanProps? Here's an example: interface IName { ...

JavaScript and Angular are used to define class level variables

Hello, I'm currently diving into Angular and have encountered an issue with a class level variable called moratoriumID in my component. I have a method that makes a POST request and assigns the returned number to moratoriumID. Everything seems to work ...

Setting up a ts-node project with ECMAScript modules. Issue: Unrecognized file extension ".ts"

I am currently in the process of setting up a minimalistic repository that incorporates ts-node and ESM for a project. Despite the existence of previous inquiries on this topic, I have encountered numerous outdated responses. Even recent answers appear to ...

What is the best way to send a search parameter to a URL?

In my asp.net core web api, I developed a method that generates an object with the string provided in the URL. I now have a search form that needs to pass this string to the URL and retrieve the objects containing it. Here is how I utilize the api: impo ...