简体   繁体   中英

How can I make sure that the geojson files are loaded properly?

I have an angular 2 application in which I integrated google maps. I have two geojson files that I fetch from the server and need to display on the map. Those files include as properties colors for each feature.

I included the colors dynamically after the files were fetched.

In my map component I have the following:

ngOnInit() {
        this.subscription = this.service.loadGeoJson().subscribe(() => this.geoJsonInit());
    }

    ngOnDestroy() { this.subscription.unsubscribe(); }

    private geoJsonInit() {
        Promise.resolve(dashboardMapService.getAllGeoJsonData().then(geoData => this.geoJsonData.push(...geoData))).then(() => dashboardMapService.loadAPI().then(res => this.onMapsReady()));
    } 

In the map service I have the following:

    const GEO_JSON: Array<Object> = [];
    let GeoJsonPromise            = Promise.resolve(GEO_JSON);

//rest of service

static getAllGeoJsonData() {
        return GeoJsonPromise;
    }

    loadGeoJson(): Observable<any> {
        if ( GEO_JSON && GEO_JSON.length > 0 ) return Observable.of(GEO_JSON);
        else
            return Observable.forkJoin([ this.loadDistrictsGeoJson(), this.loadSubDistrictsGeoJson() ]).switchMap(d => this.GeoJsonInit(d));
    }

The problem I am facing is that on initial load, the polygons are displayed on the map but without the colors. But If i switch routes and get back to the map route, the colors are displayed.

In the console. feature.getProperty('color') displays undefined initially, but then after going back and forth from the map route, they're defined.

So I am assuming that the geojsons files that are passed don't include the colors initially.

How can I make sure that the geojsons are properly fetched before loading it to the map?

private geoJsonInit() {
    Promise.resolve(dashboardMapService.getAllGeoJsonData().then(geoData => this.geoJsonData.push(...geoData))).then(() => dashboardMapService.loadAPI().then(res => this.onMapsReady()));
}

returns undefined - what you should be doing is

private geoJsonInit() {
    return dashboardMapService.getAllGeoJsonData()
        .then(geoData => this.geoJsonData.push(...geoData))
        .then(() => dashboardMapService.loadAPI())
        .then(res => this.onMapsReady());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM