mapbox / mapbox/mapbox-gl-draw
Snap to point and line
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 1.1k
- Forks
- 612
- Avg merge
- 8d 9h
- Merged PRs (30d)
- 5
Description
I'm working on a snapping mode for line and polygon drawing that supports snapping moved or created vertices to edges in existing lines/polygons or existing points. (Haven't decided about snapping to vertices in existing lines/polygons yet).
I'm looking for feedback on my design to see if it would be accepted as a PR.
When instantiating the mapbox-gl-draw object, you can pass through `snapLayers: ['mylayer']` to indicate that features in `mylayer` should be snapped to. The default is no snap layers. For that reason, my thinking is towards making this an improvement to the standard `draw_line_string` and `draw_polygon` modes (since it's completely backwardly compatible) rather than new custom modes, as suggested in #865.
On the implementation side:
* when the gl-draw object is connected, a new layer, `_mylayer_buffer` is created for each provided `mylayer`. It has the same source and filter, but is invisible, and 40 (configurable) pixels wide (either a `line` or `circle` layer type).
* `mouseover` and `mouseout` events are attached to the buffer layers, so that when the mouse enters, the point can be snapped.
* Snapping is achieved by using turf's `nearestPointOnLine`, or just the centre of the circle for point features.
* A `snap-hover` feature state is temporarily set on the hovered feature, so that the user can provide their own styling to show when a feature will be snapped to.
* Also, a visual indicator of the exact snapping point is shown with a little `circle` layer.
My implementation isn't complete, but it seems to work pretty solidly so far.
Thoughts?

Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing the standard draw_line_string and draw_polygon modes and how the mapbox-gl-draw object connects layers and events. Compare the proposed snapLayers behavior with the discussion in issue #865, including Turf's nearestPointOnLine approach. Done would require an agreed design and a complete, tested snapping implementation.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- frontend, web-dev
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100