mapbox-gl-js icon indicating copy to clipboard operation
mapbox-gl-js copied to clipboard

Validate GeoJSON

Open stevage opened this issue 8 years ago • 4 comments

mapbox-gl-js version: 0.39.1

Due to some sloppy code I passed some pretty defective GeoJSON, like:

{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "coordinates": [145, -37]
        }
    ]
}

Instead of raising a " Error: Input data is not a valid GeoJSON object." error, this error is thrown:

Error: TypeError: Cannot read property 'type' of undefined
    at Actor.receive (mapbox-gl.js:397)
    at e.whenMapLoaded ((index):58)
    at e.Evented.fire (mapbox-gl.js:417)
    at e._render (mapbox-gl.js:391)

Adding at least a "geometry" attribute to the Feature object triggers the correct error.

stevage avatar Aug 11 '17 01:08 stevage

We don't currently have any GeoJSON validation. It's something we could add, albeit at a performance cost.

jfirebaugh avatar Aug 17 '17 17:08 jfirebaugh

A compromise re: performance would be to validate everything but coordinates

anandthakker avatar Aug 17 '17 18:08 anandthakker

Thanks @jfirebaugh, I didn't realise that. It might be worth mentioning in the docs that GeoJSON sources aren't validated.

stevage avatar Aug 21 '17 22:08 stevage

In some circumstances, invalid GeoJSON data does cause an error to be thrown. For example, when the type field of a geometry is unrecognized or a different data type is supplied where string is expected. These checks can be found by searching the codebase for the string "not a valid GeoJSON object".

However, today I was calling source.setData() on a GeoJSON source with incorrectly structured data and it failed silently. Having previously seen the error messages mentioned above, I didn't realize that incorrect data would be quietly ignored. I ended up spending a very long time working through every possible combination of layer ordering, visibility and paint properties, coordinate ordering, polygon winding order etc. trying to find some clue as to why my layer was not displaying before finally realizing that the data were simply incorrectly structured rather than hidden or misplaced.

It's understandable that you don't want to degrade performance by fully validating millions of coordinates. But in this case, the problem was a polygon directly containing an array of points, rather than a one-element ring array containing that array of points. (That is: coordinates: [[x0, y0], [x1, y1]...] instead of coordinates: [[[x0, y0], [x1, y1]...]]. It seems like it would be possible to fail fast on such unrecoverable structural errors without much overhead.

Please consider at the very least adding documentation on the fact that many forms of invalid GeoJSON will fail silently, and warning that the first thing to do is validate the data even if no errors are thrown.

abyrd avatar May 09 '25 13:05 abyrd