首页 > 解决方案 > 传单使功能同步

问题描述

我试图在另一个函数中调用 setMarker() 函数。但是标记没有设置。我不知道为什么,但可能是因为 setMarker() 函数是异步的,因为 Promise。

获取城市()

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

我从 webDataRocksComponent 获得的 rawData

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

标签: angulartypescriptleafletgeojsonwebdatarocks

解决方案


您的代码看起来不错,请确保已将this.citiesLayerGroup其初始化并添加到地图中:

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

另外我认为您想将新标记推送到数组中而不是覆盖它:

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

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

如果它仍然不起作用,请检查是否this是正确的上下文:

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

推荐阅读