Integrate a marker onto a Leaflet map within a separate Angular component

In my Angular project, I created a const map variable in my mapComponent to add custom markers on a map. Now I'm wondering how I can achieve the same functionality from different Angular components while using the same map instance?

Answer №1

Utilizing a service is a great way to facilitate communication between different components.

Start by creating a service that will store the values of your coordinates array.

class MarkerService {
  coords: any;
  coordsChange: Subject<LatLngExpression> = new Subject<LatLngExpression>();

  constructor() {
    this.coords = [];
  }

  change(coords: Array<number>) {
    this.coords = coords;
    this.coordsChange.next(this.coords);
  }
}

For example, you can have a button in one component that triggers a function in the service to update the coordinates array. Then, in your main app component, initialize your leaflet map. Subscribe to the service to receive the updated values and render markers on the map while also adjusting the view.

map;

  constructor(private ms: MarkerService) {
    console.log(this.ms.coords);
    this.ms.coordsChange.subscribe(coords => {
      console.log(coords);
      this.map.flyTo(coords, this.map.getZoom());
      L.marker(coords, { icon }).addTo(this.map);
    });
  }

Check out the demo 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

I am trying to access a value saved in a service in Angular 8 component and use it in other services. Can anyone help

Setting a value through a component export class UniqueComponent { constructor(service:UniqueService){ } count =0 ; onRefresh(){ this.service.count = 1; } } Using the value in the service UniqueService{ count:any; doSomething(){ //using count ...

What is the proper way to compare enum values using the greater than operator?

Here is an example enum: enum Status { inactive = -1, active = 0, pending = 1, processing = 2, completed = 3, } I am trying to compare values using the greater than operator in a condition. However, the current comparison always results in false ...

What is the best way to show page content in Angular (2+) without having to use a specific selector like Material Snackbar?

@angular/material provides a convenient way to display certain items without the need for a selector in your HTML. For example, the Snackbar can be easily shown by injecting an MdSnackBar and calling the open method. You don't have to define elements ...

What is the best way to extract a variable value from the subscribe method and make it available for use in an Angular 10 service method's return statement using TypeScript?

getProductbyFilter(filter: filterDataModel): Observable<any> { this.stringtoArrayService.convertStringtoArray(some string input).subscribe(productUserResponse => { if (productUserResponse) { this.userProfileProduct = productUserResponse; ...

How should a function be correctly implemented to accept an object and modify its attributes?

I have a question regarding the update method in my code. In the function below, it takes an object called newState and uses Object.assign() to update the properties of the class instance. I want TypeScript to only allow: An object as input Properties tha ...

Any suggestions on how I can make my modal stand out more?

I'm having trouble getting the modal to show up in this HTML file. Do I need to add something here or somewhere else? Do I also need to write a button onclick function? The modal should display when the "delete" button is clicked. <div class=" ...

Adding additional properties to JSX components during typescript compilationIs there a way to include additional properties

Currently, I am employing JSX syntax in my TypeScript node.js project (without relying on React). Within my tsconfig, I have specified my custom jsxFactory { "compilerOptions": { ... "jsxFactory": "myJSXFactory", ...

The protractor-jasmine2-screenshot-reporter seems to be failing to generate the necessary screenshots within the designated folder

I have encountered an issue with my protractor.conf.js file and need some assistance. I have created the target/screenshots folder manually in the root of my angular-cli project, but when I run protractor conf.js, the protractor tests in the browser window ...

Failing to reach the nested if statements within a switch case block

Before removing my question, please read this. Despite testing with console.logs, my code does not enter the if statements. I have not come across a similar solution to my issue. In an attempt to address any timing or asynchronous problems, I added a use ...

The Angular Control View Accessor fails to recognize any changes in value after the writeValue method has been executed

Utilizing the Angular Control value accessor interface for creating reusable forms in my project has presented a challenge when it comes to setting values while constructing the parent form. For instance, let's consider an Address object that contain ...

"Subscribing in interceptor doesn't seem to have any effect

I am currently facing an issue where I try to refresh a token using an API call, but the token does not get refreshed and the logs are not appearing as expected. In my code, I have implemented a timeout for testing purposes to trigger the token refresh and ...

Creating a second optional generic parameter in TypeScript

I'm having trouble with TypeScript generics My issue is as follows: I have an interface called 'Column' and a function called makeColumn to create a new column. I want to only set the first generic (UserModel), where the accessor must be a ...

The component needs to span the entire width and height of its parent element

I'm currently working on creating a progress bar component in Angular, and everything seems to be functioning well except for covering the parent element. If you'd like to see the code in action, check it out here: Code Demo: Current Angular Co ...

Retrieving specific object properties within an Angular 2 and Ionic 2 form

Within the @Page, I have a few select inputs. In addition to storing the value of the selected option, such as {{project.title}}, I also require the ability to return another selected object property, such as {{project.id}} or even the entire object. When ...

implementing token refresh functionality in Angular using a service

In my current project, the backend has an exposed refresh token API. Upon logging in, a valid token and refresh token are received. When the token expires, a refresh call is required, authorized with the old expired token and the refresh token parameter. T ...

Customizing the choices for an ActionSheet on Ionic 2 on the fly

After making a GET request, I receive JSON data containing an array of options with id, style, and name for each element. I need to dynamically populate the options in my ActionSheet within my Ionic 2 app based on this API response. The ActionSheet is fu ...

Adding to object properties in Typescript

My goal is to dynamically generate an object: newData = { column1: "", column2: "", column3: "", ... columnN: "" } The column names are derived from another array of objects called tableColumns, which acts as a global variable: table ...

Steps to resolve the error "The value for '--target' option should be one of the following: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es201', 'esnext'."

I recently cloned an Angular application and encountered an error related to the "target" property in the tsconfig.json file within Visual Studio 2019. My Angular version is v16.1.4, with Typescript v5.1.6. I've attempted to resolve this issue by upda ...

Tips for patiently anticipating the outcome of asynchronous procedures?

I have the given code snippet: async function seedDb() { let users: Array<Users> = [ ... ]; applications.map(async (user) => await prisma.user.upsert( { create: user, update: {}, where: { id: user.id } })); } async function main() { aw ...

Problem with execution of TypeScript function from HTML

I have been facing an issue where I am attempting to click a button on an HTML page to trigger a TypeScript function called `getToken()`. Strangely, the function does not seem to get executed when the button is clicked. Surprisingly, I have tested the `get ...