[Mapbox GL]高亮有限区域特性

        使用queryRenderedFeatures,按住shift并拖拽地图查询特性


<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title></title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.29.0/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.29.0/mapbox-gl.css' rel='stylesheet' />
    <style>
        body { margin:0; padding:0; }
        #map { position:absolute; top:0; bottom:0; width:100%; }
    </style>
</head>
<body>

<style>
.boxdraw {
    background: rgba(56,135,190,0.1);
    border: 2px solid #3887be;
    position: absolute;
    top: 0;
    left: 0;
    width: 0;
    height: 0;
}
</style>

<div id='map'></div>

<script>
mapboxgl.accessToken = '<your access token here>';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v9',
    center: [-98, 38.88],
    minZoom: 2,
    zoom: 3
});

// Disable default box zooming.
map.boxZoom.disable();   /* 去使能BoxZoomHandler */

// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({   /* new Popup(options: [Object]) 创建新的Popup*/
    closeButton: false
});

map.on('load', function() {
    var canvas = map.getCanvasContainer(); /* getCanvasContainer()获取包含地图上<canvas>元素的HTML元素,如果你打算添加non-GL的overlay时,需要附加到这个元素上 */

    // Variable to hold the starting xy coordinates
    // when `mousedown` occured.
    var start;

    // Variable to hold the current xy coordinates
    // when `mousemove` or `mouseup` occurs.
    var current;

    // Variable for the draw box element.
    var box;

    // Add the source to query. In this example we're using
    // county polygons uploaded as vector tiles
    map.addSource('counties', {
        "type": "vector",
        "url": "mapbox://mapbox.82pkq93d"
    });

    map.addLayer({
        "id": "counties",
        "type": "fill",
        "source": "counties",
        "source-layer": "original",
        "paint": {
            "fill-outline-color": "rgba(0,0,0,0.1)",  /* fill的轮廓颜色 */
            "fill-color": "rgba(0,0,0,0.1)"           /* fill填充的颜色 */
        } 
    }, 'place-city-sm'); // Place polygon under these labels.

    map.addLayer({
        "id": "counties-highlighted",
        "type": "fill",
        "source": "counties",
        "source-layer": "original",
        "paint": {
            "fill-outline-color": "#484896",
            "fill-color": "#6e599f",
            "fill-opacity": 0.75                /* fill填充的透明度 */
        },
        "filter": ["in", "FIPS", ""]
    }, 'place-city-sm'); // Place polygon under these labels.

    // Set `true` to dispatch the event before other functions
    // call it. This is necessary for disabling the default map
    // dragging behaviour.
    canvas.addEventListener('mousedown', mouseDown, true);  /*mousedown:当用户在这个元素上按下鼠标键的时候触发 */

    // Return the xy coordinates of the mouse position
    function mousePos(e) {
        var rect = canvas.getBoundingClientRect();  /* getBoundingClientRect():这个方法返回一个矩形对象,包含四个属性:left、top、right和bottom。分别表示元素各边与页面上边和左边的距离。 */
        return new mapboxgl.Point(
            e.clientX - rect.left - canvas.clientLeft, /* clientX 事件属性返回当事件被触发时鼠标指针向对于浏览器页面(或客户区)的水平坐标, */
            e.clientY - rect.top - canvas.clientTop
        );
    }

    function mouseDown(e) {
        // Continue the rest of the function if the shiftkey is pressed.
        if (!(e.shiftKey && e.button === 0)) return;

        // Disable default drag zooming when the shift key is held down.
        map.dragPan.disable();  /* 去使能DragPanHandler */

        // Call functions for the following events
        document.addEventListener('mousemove', onMouseMove);
        document.addEventListener('mouseup', onMouseUp);
        document.addEventListener('keydown', onKeyDown);

        // Capture the first xy coordinates
        start = mousePos(e);
    }

    function onMouseMove(e) {
        // Capture the ongoing xy coordinates
        current = mousePos(e);

        // Append the box element if it doesnt exist
        if (!box) {
            box = document.createElement('div');
            box.classList.add('boxdraw'); /* classList 属性返回元素的类名,作为 DOMTokenList 对象。该属性用于在元素中添加,移除及切换 CSS 类。classList 属性是只读的,但你可以使用 add() 和 remove() 方法修改它。 */
            canvas.appendChild(box);  /* appendChild() 方法向节点添加最后一个子节点 */
        }

        var minX = Math.min(start.x, current.x),
            maxX = Math.max(start.x, current.x),
            minY = Math.min(start.y, current.y),
            maxY = Math.max(start.y, current.y);

        // Adjust width and xy position of the box element ongoing
        var pos = 'translate(' + minX + 'px,' + minY + 'px)';
        box.style.transform = pos;  /* element.style.transform:transform 属性向元素应用 2D 或 3D 转换。该属性允许您对元素进行旋转、缩放、移动或倾斜。 */
        box.style.WebkitTransform = pos;
        box.style.width = maxX - minX + 'px'; /* element.style.width:设置宽度 */
        box.style.height = maxY - minY + 'px'; /* element.style.height:设置高度 */
    }

    function onMouseUp(e) {
        // Capture xy coordinates
        finish([start, mousePos(e)]);
    }

    function onKeyDown(e) {
        // If the ESC key is pressed
        if (e.keyCode === 27) finish();
    }

    function finish(bbox) {
        // Remove these events now that finish has been called.
        document.removeEventListener('mousemove', onMouseMove);
        document.removeEventListener('keydown', onKeyDown);
        document.removeEventListener('mouseup', onMouseUp);

        if (box) {
            box.parentNode.removeChild(box); /* removeChild() 方法用来删除父节点的一个子节点。 */
            box = null;
        }

        // If bbox exists. use this value as the argument for `queryRenderedFeatures`
        if (bbox) {
            var features = map.queryRenderedFeatures(bbox, { layers: ['counties'] });

            if (features.length >= 1000) {
                return window.alert('Select a smaller number of features');
            }

            // Run through the selected features and set a filter
            // to match features with unique FIPS codes to activate
            // the `counties-highlighted` layer.
            var filter = features.reduce(function(memo, feature) { 
                memo.push(feature.properties.FIPS);
                return memo;
            }, ['in', 'FIPS']); /* array1.reduce(callbackfn[, initialValue])对数组中的所有元素调用指定的回调函数。该回调函数的返回值为累积结果,并且此返回值在下一次调用该回调函数时作为参数提供。callbackfn,必需。一个接受最多四个参数的函数。对于数组中的每个元素,reduce 方法都会调用 callbackfn 函数一次。initialValue,可选。如果指定 initialValue,则它将用作初始值来启动累积。第一次调用 callbackfn 函数会将此值作为参数而非数组值提供。回调函数的语法如下所示:
function callbackfn(previousValue, currentValue, currentIndex, array1),previousValue通过上一次调用回调函数获得的值。如果向 reduce 方法提供 initialValue,则在首次调用函数时,previousValue 为 initialValue。currentValue当前数组元素的值。currentIndex当前数组元素的数字索引。array1包含该元素的数组对象。(具体见https://msdn.microsoft.com/library/ff679975(v=vs.94).aspx) */

            map.setFilter("counties-highlighted", filter); /* 设置map上layer的filter */
        }

        map.dragPan.enable();
    }

    map.on('mousemove', function(e) {
        var features = map.queryRenderedFeatures(e.point, { layers: ['counties-highlighted'] }); /* 查询对应位置满足条件的数据 */
        // Change the cursor style as a UI indicator.
        map.getCanvas().style.cursor = (features.length) ? 'pointer' : '';  /* 指定光标样式 */

        if (!features.length) {
            popup.remove();  /* remove():移除overlay */
            return;
        }

        var feature = features[0];

        popup.setLngLat(e.lngLat)           /* setLngLat():设置位置 */
            .setText(feature.properties.COUNTY) /* setText():设置文本内容 */
            .addTo(map);                    /* addTo():将popup添加到map */
    });
});
</script>

</body>
</html>



原文:https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/

Mapbox的popup是用于在地图上显示弹窗的功能。根据官方示例,首先需要引入mapbox的样式文件,可以使用以下代码导入样式文件: import "mapbox-gl/dist/mapbox-gl.css" 然后,可以创建一个popup对象并将其添加到地图上,示例代码如下: var popup = new mapboxgl.Popup().addTo(map); 接下来,可以使用popup对象的相关方法来操作弹窗,比如移除弹窗可以使用popup.remove()方法。 要注意的是,这只是mapbox popup的简单使用示例,实际使用中可以根据需要设置弹窗的内容、样式和交互行为等。可以参考mapbox官方文档和示例来了解更多关于popup的详细用法。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Mapbox 添加弹窗 点击标记点出现弹窗 vue](https://blog.csdn.net/Windyluna/article/details/120658613)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Mapbox 移除弹窗、监听弹窗打开、关闭事件、去除Mapbox的logo](https://blog.csdn.net/Windyluna/article/details/120827636)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值