0%

Adding GeoJSON layers to your Leaflet map in TypeScript

Adding a GeoJSON layer to a Leaflet map in TypeScript has some difference from that in JavaScript.

It’s because the GeoJSON is typed in TypeScript and the type declaration of Leaflet adopts it. So whenever you construct the GeoJSON object in TypeScript, it’s important to declare the type of the variable as GeoJSON type:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// it's necessary to tell variable type
let featureCollection: GeoJSON.FeatureCollection<any> = {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [0, 0]
},
properties: {}
}
]
};

// the Leaflet API is the same as the JavaScript one, except for the parameter type requirement
L.geoJSON(featureCollection).addTo(this.map);

For more about the specification and example, take a look at the GeoJSON type definition.