Search code examples
angularleafletgeojsonngx-leaflet

Unable to create GeoJSON layer


I'm developing an app in angular that use leaflet map to show some layers and I'm trying to use GeoJSON, but I'm unable to create an L.geoJSON layer. I'm trying to add a point and every single resource I found tell me to create this structure:

import { geoJSON } from 'leaflet';

geoJSON({
    type: "Point",
    coordinates: [lat,long]
});

but when I serve the app I get this error:

Argument of type '{ type: "Point"; coordinates: number[]; }' is not assignable to parameter of type 'GeoJsonObject'.
Object literal may only specify known properties, and 'coordinates' does not exist in type 'GeoJsonObject'.

The only other property beyond type is bbox?.

I'm sure I'm doing something wrong, but I can't really understand what.

Using

"leaflet": "^1.3.1"
"@types/leaflet": "^1.2.5"
"@asymmetrik/ngx-leaflet": "^3.0.2"

Solution

  • The Typed Definition for Leaflet specifies that the geoJSON factory accepts a GeoJSON Object (spec) as 1st parameter.

    The object you pass as 1st parameter is a Point type Geometry Object (spec), that extends the GeoJSON object. Therefore you should be good by simply explicitly declaring your object as a geojson.Point:

    import { geoJSON } from 'leaflet';
    import * as geojson from 'geojson';
    
    geoJSON(<geojson.Point>{
        type: "Point",
        coordinates: [lng, lat] // Note that in GeoJSON, order is [LONG, LAT]
    });
    

    Leaflet in JavaScript actually accepts more types as 1st parameter of L.geoJSON factory: