Make leaflet function operate synchronously

There seems to be an issue with calling the setMarker() function within another function, as the markers are not being set. It's possible that this is due to the asynchronous nature of the setMarker() function because of the Promise it uses.

getCities()

getCities(rawData) {
    for (const index in rawData['data']) {
        if (rawData.meta.c0Name == 'city') {
            const city: string = rawData['data'][index]['c0'];

            if (city != undefined) {
                this.setMarker(city);
            }
        }
    }

setMarker()

 setMarker(location: string) {
    const provider = new OpenStreetMapProvider();

    const query_promise = provider.search({
        query: location,
    });

    query_promise.then(
        (value) => {
            // Success!
            const x_coor = value[0].x;
            const y_coor = value[0].y;
            const label = value[0].label;
            this.citiesLayer = [
                L.marker([y_coor, x_coor])
                    .bindPopup('<b>Found location</b><br>' + label)
                    .addTo(this.citiesLayerGroup),
            ];
        },
        (reason) => {
            console.log(reason); // Error!
        }
    );
}

The rawData received from my webDataRocksComponent

    getDataForMap() {
    this.child.webDataRocks.getData(
        {},
        (rawData) => {
            this.mapComponent.getCities(rawData);
        },
        (rawData) => {
            this.mapComponent.getCities(rawData);
        }
    );
}

Answer №1

Great job on your code, just make sure that this.citiesLayerGroup is properly initialized and added to the map:

this.citiesLayerGroup = L.featureGroup().addTo(map); // or L.layerGroup

Additionally, it seems like you want to add the new marker to the array instead of replacing it:

if(!this.citiesLayer){
   this.citiesLayer = []
}

this.citiesLayer.push(L.marker([y_coor, x_coor])
                    .bindPopup('<b>Found location</b><br>' + label)
                    .addTo(this.citiesLayerGroup),
);

If you're still facing issues, double check if this is the correct context:

var that = this;
query_promise.then(
        (value) => {
            // Success!
            const x_coor = value[0].x;
            const y_coor = value[0].y;
            const label = value[0].label;
console.log(this);
console.log(that)
            that.citiesLayer = [  // changed to that
                L.marker([y_coor, x_coor])
                    .bindPopup('<b>Found location</b><br>' + label)
                    .addTo(that.citiesLayerGroup), // changed to that
            ];
        },
        (reason) => {
            console.log(reason); // Error!
        }
    );

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

Having issues with NGXS subscription not functioning properly when selecting a variable

Currently, I am working with Angular 11 and NGXS. One issue I am facing involves a subscription for a variable in the state. Here is the problematic subscription: @Select(state => state.alert.alerts) alerts$: Observable<any[]> ngOnInit(): void { t ...

Modifying the default locale translation of specific month names in Angular: A step-by-step guide

In our project, we utilize two different locales: Russian and Kazakh. When it comes to displaying dates, we rely on Angular's default datePipe. In the Kazakh language, the word for June is "маусым" and its shortened version is "мау." However, ...

The onChange() function in the Date Picker event is failing to activate

My issue involves the Angular Material DatePicker. Everything seems to be working smoothly, however, the (change) event does not trigger when I change the date using the calendar. Manually inputting a date works just fine. I would like to display an erro ...

What is the best way to navigate back to the previous page while retaining parameters?

Is there a way to return to the previous page with specific parameters in mind? Any suggestions on how to achieve this? import {Location} from '@angular/common'; returnToPreviousPage(){ this._location.back(); } What I am looking ...

What could be causing my website to lose its responsiveness after linking a domain?

Recently, I created a basic website for an event in my town using AWS Amplify from Amazon. Initially, the website was hosted without a custom domain and had a random URL. It worked well on both web and mobile platforms. However, after connecting a custom d ...

What is the best way to define a global variable in TypeScript and access it throughout a Vue application?

In my main.ts file, I am looking to define a variable that can be accessed in all Vue files. Within my sfc.d.ts file, the following content is included: declare module '*.vue' { import Vue from 'vue' export default Vue } declar ...

Generate a placeholder payload for CdkDragDrop event

I am looking to perform unit testing on a method in angular using jest: drop(event: CdkDragDrop<string[]>) { if (event.previousContainer === event.container) { moveItemInArray(event.container.data, event.previousIndex, event.currentIndex) ...

"Utilize a loop in Angular 2 to consistently send HTTP GET requests to service

Hello, I'm new to working with Angular. Currently, I have an array of product IDs and I would like to make HTTP GET requests based on each ID in the array using a loop. Can someone assist me with this task? Service : addedProductIdArray : string[] = ...

How to retrieve the HTTPClient value in Angular?

APIservice.ts public fetchData(owner: any) { return this.http.get(`${this.url}/${owner}`, this.httpOptions).pipe( catchError(e => { throw new Error(e); }) ); } public fetchDataById(id: number, byId:string, owner: any) { ...

Node.js: Managing multiple occurrences of the same event name for testing purposes

When it comes to unit testing using mocha, I am looking for a way to set up an asynchronous queue for handling events. Previously, I used a once() Promise to wait for events like this: import EventEmitter from 'events' import { once } from ' ...

Steps for sending an image to Cloudinary using the fetch API

Struggling to figure out how to successfully upload a file to Cloudinary using fetch on my front-end. After consulting the documentation and various StackOverflow threads, I'm still facing a frustrating 400 error: export async function uploadImageToCl ...

Transform Sass modules into css during the creation of a component library

I'm in the process of developing a React TypeScript component library that will be utilized in various projects. Currently, I have been using the following script to build this project. "build": "rimraf dist && NODE_ENV=product ...

"What could be the reason behind the injected service not being successfully passed from the parent component to the child component when navigating using route.navigate in Angular

I currently have a parent component and a child component set up in my project. (parent component) @Component({ selector: 'app-parent', providers: [SimpleService] }) (child component) @Component({ selector: 'app-child' }) Everyt ...

Passing a service into a promise in Angular 2 using TypeScript

Is there a way to pass a service into a promise? I am currently working on a promise that will only resolve once all the http requests are complete. However, I am facing an issue where this.jiraService is undefined. Is there a method to pass it to the co ...

What is the best way to handle API requests within an Angular component?

I am currently diving into the world of Angular at my workplace, even though I do not have a background in web development. One challenge I am facing is how to encapsulate API calls within one of my components without knowing where to begin. The componen ...

What is the most effective way to utilize getStaticPaths in a dynamic manner within next.js

There is a need to paginate static pages for each of the 3 blog categories, but the problem lies in the variable number of pages and the inability to access which category needs to be fetched in getStaticPaths. The project folder structure appears as foll ...

Error message: The ofType method from Angular Redux was not found

Recently, I came across an old tutorial on Redux-Firebase-Angular Authentication. In the tutorial, there is a confusing function that caught my attention: The code snippet in question involves importing Actions from @ngrx/effects and other dependencies to ...

Is there a sweet TypeScript class constructor that can take in its own instance as an argument?

I have a scenario where I need to read in instances of Todo from a CSV file. The issue is that Papaparse does not handle dynamic conversion on dates, so I'm currently dropping the object into its own constructor to do the conversion: class Todo { ...

Electron and React: Alert - Exceeded MaxListenersWarning: Potential memory leak detected in EventEmitter. [EventEmitter] has 21 updateDeviceList listeners added to it

I've been tirelessly searching to understand the root cause of this issue, and I believe I'm getting closer to unraveling the mystery. My method involves using USB detection to track the connection of USB devices: usbDetect.on('add', () ...

Working with arrays in Angular 4 to include new items

I am struggling with the code below: export class FormComponent implements OnInit { name: string; empoloyeeID : number; empList: Array<{name: string, empoloyeeID: number}> = []; constructor() { } ngOnInit() { } onEmpCreate(){ conso ...