文章目录
- 一、前言
- 二、实现代码
一、前言
mapbox-gl 为地图前端框架,以优美的地图样式著称。mapbox-gl-draw 插件可以实现绘制图形,编辑图形的功能,但是编辑图形时无法吸附点位,导致相邻面无法相接。使用mapbox-gl-draw-snap-mode 扩展插件可以解决问题
二、实现代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>mapbox_draw_吸附</title>
<script src="lib/jquery-3.4.1.js"></script>
<link href="lib/mapbox-gl/mapbox-gl.css" rel="stylesheet">
<script src="lib/mapbox-gl/mapbox-gl.js"></script>
<script src="lib/lodash/lodash.min.js"></script>
<script src="lib/plugins/mapbox-gl-utils/0.39.0/mapbox-gl-utils.js"></script>
<script src='lib/plugins/turf/6.3.0/turf.min.js'></script>
<script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.4.1/mapbox-gl-draw.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-draw/v1.4.1/mapbox-gl-draw.css" type="text/css">
<!--<script src="https://unpkg.com/mapbox-gl-draw-pinning-mode"></script>-->
<script src="https://unpkg.com/mapbox-gl-draw-snap-mode"></script>
</head>
<style>
html, body {
height: 100%;
margin: 0px;
}
li, ul {
list-style: none;
}
#map {
width: 100%;
height: 100%;
}
</style>
<body>
<div id="map">
</div>
</body>
<script type="module">
// https://github.com/mhsattarian/mapbox-gl-draw-snap-mode 吸附
mapboxgl.accessToken = '****';
var map = new mapboxgl.Map({
container: 'map',
zoom: 12,
minZoom: 4,
center: [113.53033743016164, 34.81470384732482],
style: 'mapbox://styles/mapbox/light-v11',
antialias: true
})
U.init(map)
const draw = new MapboxDraw({
modes: {
...MapboxDraw.modes,
direct_select: mapboxGlDrawSnapMode.SnapDirectSelect,
draw_point: mapboxGlDrawSnapMode.SnapPointMode,
draw_polygon: mapboxGlDrawSnapMode.SnapPolygonMode,
draw_line_string: mapboxGlDrawSnapMode.SnapLineMode,
},
// Styling guides
styles: mapboxGlDrawSnapMode.SnapModeDrawStyles,
userProperties: true,
// Config snapping features
snap: true,
snapOptions: {
snapPx: 15, // defaults to 15
snapToMidPoints: false, // defaults to false
snapVertexPriorityDistance: 0.0025, // defaults to 1.25
},
guides: true, // 网格线
})
map.addControl(draw)
map.on('load', () => {
})
</script>
</html>
有疑问可以关注下,相互交流探讨~