使用mapbox自定义绘制工具(point,line,polygon,circle,rectangle)

如何使用mapbox绘制常用的工具

许多小伙伴刚接触map的时候,都不知道怎么下手,都是一味埋头网上一顿搜。然后发现别人写的东西自己发现拿过来放在自己的代码中不合适。有些怎么实例化地图都不知道,所以看官网API是非常重要的,一来让你对mapbox一些属性,方法以及事件有一个初步的了解,然后在结合别人写的功能自己才会容易上手。操作地图不外乎就是一些事件,其实mapbox有一些关于绘制工具的一些插件,也可以自己定义绘制工具。
我这里的demo,就是一个很简单的实现。实现(point,line,polygon,circle,rectangle)我用到的事件就三种(click(鼠标单击),mousemove(鼠标移动),dblclick(双击结束),就根据这三个事件做这几个绘制工具。希望对你在网上找关于mapbox绘制工具在逻辑上有一个直观的了解,为了方便参考者一看就懂。所以我把各个功能的代码分开展示。如果想要看本实例效果的自己创建一个html文件把一下代码顺序复制到你所创建的html文件中。直接打开即可,当然这里面的demo可能不完美,参考者可以根据需要自行修改。

需要引入的资源

<script src='https://api.mapbox.com/mapbox-gl-js/v2.0.0/mapbox-gl.js'></script>
    <script src="https://cdn.bootcss.com/Turf.js/5.1.6/turf.js"></script>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

Turf.js用于计算面积,距离使用,

创建div

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>mapbox测量工具</title>
    <link href='https://api.mapbox.com/mapbox-gl-js/v2.0.0/mapbox-gl.css' rel='stylesheet' />
    
    <style>
        body {
   
    margin:0; padding:0; }
        #map {
   
    position:absolute; top:0; bottom:0; width:100%; }
        .map-legend{
   
   
            position:absolute;
            z-index: 5;
        }
        .measure-result {
   
   
            background-color: white;
            border-radius: 3px;
            height: 16px;
            line-height: 16px;
            padding: 0 3px;
            font-size: 12px;
            box-shadow: 0 0 0 1px #ccc;
            position: absolute;
        }
        .measure-result .close {
   
   
            cursor: pointer;
            width: 14px;
            height: 14px;
            line-height: 16px;
            text-align: center;
            padding: 0;
        }
    </style>
</head>
<body>
    <div id='map'>
        <div class="map-legend">
        <button id="circle"></button>
        <button id="point"></button>
        <button id="line">线</button>
        <button id="polygon">多边形</button>
        <button id="rectangle">矩形</button>
    </div>
    </div>
</body>

引入mapbox实例

  mapboxgl.accessToken = 'pk.eyJ1IjoibGlhbmJvIiwiYSI6ImNrYWRqeXN5ZzAwenYycm9nZ2M5ZDIzMzMifQ.jTm1afxWBB-OxKGp57wjaw';

        var map = new mapboxgl.Map({
   
   
            container: 'map',
            maxZoom: 18,
            minZoom: 0,
            zoom: 10,
            center: [109.1699, 45.9719],
            style: 'mapbox://styles/mapbox/streets-v11',
            attributionControl: false
        });

设置circle工具

  //绘制圆形区域的函数
    let createGeoJSONCircle = function(center, radiusInKm, points) {
   
   
        if(!points) points = 64;
        var coords = {
   
   
            latitude: center[1],
            longitude: center[0]
        };
        var km = radiusInKm;
        var ret = [];
        var distanceX = km/(111.320*Math.cos(coords.latitude*Math.PI/180));
        var distanceY = km/110.574;

        var theta, x, y;
        for(var i=0; i<points; i++) {
   
   
            theta = (i/points)*(2*Math.PI);
            x = distanceX*Math.cos(theta);
            y = distanceY*Math.sin(theta);

            ret.push([coords.longitude+x, coords.latitude+y]);
        }
        ret.push(ret[0]);
        // {
   
   
        //     "type": "geojson",
        //     "data": {
   
   
        //     "type": "FeatureCollection",
        //         "features": [{
   
   
        //         "type": "Feature",
        //         "geometry": {
   
   
        //             "type": "Polygon",
        //             "coordinates": [ret]
        //         }
        //     }]
        // }
        // };

        return {
   
   
            "type": "Feature",
            "geometry": {
   
   
                "type": "Polygon",
                "coordinates": [ret]
            }
        };
    };
 
    $("#circle").click(function (e) {
   
   
	debugger
        map.getCanvas().style.cursor = 'crosshair';
        e.stopPropagation();
        clearLayerAndSource();
        var isDraws = true;
        // 禁止双击缩放
        map.doubleClickZoom.disable();
        var radius=0;
        var jsonCircle = {
   
   
            'type': 'FeatureCollection',
            'features': []
        };
		let _pixelRadius=0;
        var source = map.getSource('circle');
        if(source){
   
   
            //map.getSource('circle').setData(jsonCircle);
        }else{
   
   
            map.addSource('circle', {
   
   
                type: 'geojson',
                data: jsonCircle
            });
            map.addLayer({
   
   
                "id": "circle",
                "type": "fill",
                "source": "circle",
                "layout": {
   
   
				 },
                "paint": {
   
   
				     
                    "fill-color": "#e6205e",
                    "fill-opacity": 0.6,
					//"circle-radius": {
   
   
			         //    stops: [
                    //    [0, 0],
			         //    [20, _pixelRadius]],
			         //    base: 2
			         //   },
				    //  "circle-opacity": 0.5,
					// "circle-stroke-width": 1,
					// "circle-color": "#00f",
					// "circle-pitch-alignment": "map"
	            
                }

            });
        }
        var points = [];
        var starCoords=[];
		let isMousemove=false;
		
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

AuroraDawns

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

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

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

打赏作者

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

抵扣说明:

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

余额充值