mapbox-gl-draw
mapbox-gl-draw copied to clipboard
After entering draw_point mode with no features, getAll() returns a Point with no coordinates
mapbox-gl-js version: 0.44.2 mapbox-gl-draw version: 1.0.7
Steps to Trigger Behavior
Do something like this:
map.addControl(draw);
draw.set({type: 'FeatureCollection', features: []});
draw.changeMode('draw_point');
console.log(draw.getAll());
jsbin: https://jsbin.com/hecipexiju/1/edit?html,output
Expected Behavior
I would have expected draw.getAll() to return an empty FeatureCollection.
Actual Behavior
I get a FeatureCollection with one feature, which is a Point with an empty array as coordinates, which is invalid GeoJSON. I have to manually filter such points out of the object before passing them downstream, otherwise calculations fail.
I see this same behavior with draw_polygon:

It actually explicitly adds null to the coordinates there, which is invalid in mapbox-gl.
Happy to take a look at this unless there's a good reason this should be happening. It is unfortunate because it causes some issues downstream.
Just ran into this.
- Click the polygon tool (try it in the docs example)
draw.getAll()will return an invalid polygon:
{
"type": "FeatureCollection",
"features": [
{
"id": "3e67c3496932bf89b27b1ce74d604c61",
"type": "Feature",
"properties": {},
"geometry": {
"coordinates": [
[
[
-91.85288565063648,
42.7185207838487
],
[
-91.85288565063648,
42.7185207838487
]
]
],
"type": "Polygon"
}
}
]
}
Errors (identified by GeoJSONLint):
- Line 10: a LinearRing of coordinates needs to have four or more positions
- Line 8: Polygons and MultiPolygons should follow the right-hand rule
A similar thing happens with the Point and LineString tools. I imagine mapbox-gl-draw is populating some kind of internal state with partial Features as soon as a tool is clicked. OP's expected behavior is also what I expected (for draw.getAll() to return an empty FeatureCollection).
I came up with a workaround:
- checking the draw_mode and then unshifting the first element:
- seems like the partially drawn object is always in the front of the list
const allDrawn = draw.getAll();
const features = allDrawn.features;
if (draw.getMode() === 'draw_polygon') {
features.shift();
}
EDIT: nevermind. the partially drawn object isn't always at the front...
maybe this will work for some people
const prevMode = draw.getMode()
draw.changeMode('simple_select');
const allDrawn = draw.getAll();
const features = allDrawn.features;
draw.changeMode(prevMode);
I was just dealing with this; if you run draw.getAll() when a drawing is "incomplete" (polygon not closed or not started), you'll get some extra invalid features (like a polygon with too few coordinates).
It looks like those features get cleaned out of the FeatureCollection if you switch the mode to simple_select before running .getAll().
Good thinking, @nerdynucleon ! You saved me having to manually filter out invalid features from the FeatureCollection :relieved: