mapbox-gl 实现绘制图形吸附功能


一、前言

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>

有疑问可以关注下,相互交流探讨~
在这里插入图片描述

  • 19
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gis分享者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值