Search code examples
javascriptangularleafletgeojsonngx-leaflet

Leaflet - import Geojson - Angular 6


i try to import GeoJson file to leaflet in angular's app 6.

With this solution my geojson is drawn in leafletmap but i have this error and i can't build my app. Someone know one solution ?

ERROR TS2345 Argument of type '{"type": string;"features":({"type": string; "geometry": { "type: string : "coordinates": num...' is not assignable parameter of type GeoJsonObject

Model.ts

export const Pdl = [ 'my geojson' ];

https://raw.githubusercontent.com/alanent/france-geojson/master/regions/pays-de-la-loire/departements-pays-de-la-loire.geojson

Component.ts

import { LeafletModule } from '@asymmetrik/ngx-leaflet';
import * as L from 'leaflet';
import {Pdl} from "../models/pdl.model"; 

@Component({
   selector: 'app-geo',
   templateUrl: './geo.component.html',
   styleUrls: ['./geo.component.scss']
})
export class GeoComponent implements OnInit { 

    ngOnInit() {    
       var mapboxAccessToken = "...";

       const myfrugalmap = L.map('frugalmap').setView([47.482019, -1], 7);

       L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=' + mapboxAccessToken, {
          id: 'mapbox.light',
          attribution: 'SOS'
       }).addTo(myfrugalmap);

       L.geoJSON(Pdl).addTo(myfrugalmap);
    }
}

Maybe, i can hide the error ? what is the way ?


Solution

  • You need to do it the 'angular way' since you are using ngx-leaflet

    Importing a json via import is a nightmare in my personal opinion so what I would do would be to fetch it using a get request when the map is loaded and then get a reference to the map object and add the geojson.

    template:

    import { HttpClient } from '@angular/common/http';
    import * as L from 'leaflet';
    ..
    map: L.Map;
    json;
    options = {
        layers: [
            L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { 
                maxZoom: 18, attribution: '...'
            })
        ],
        zoom: 7,
        center: L.latLng(47.482019, -1)
    };
    
    constructor(private http: HttpClient) { }
    
    onMapReady(map: L.Map) {
        this.http.get('assets/departements.json').subscribe((json: any) => {
            console.log(json);
            this.json = json;
            L.geoJSON(this.json).addTo(map);
        });
    }
    

    template

    <div leaflet style="height: 800px"
        [leafletOptions]="options"
        (leafletMapReady)="onMapReady($event)">
    </div>
    

    Demo