0
点赞
收藏
分享

微信扫一扫

mapbox-gl实现框选操作

单调先生 2022-09-27 阅读 183

--mapbox-gl是一个开源、基于webgl技术的前端地图类库--

地图上的框选操作,是在选择一个位置,按下鼠标坐标,同时进行鼠标的拖拽,从而形成一个长方形的选择区域。

在mapbox-gl实现此功能的具体代码如下:

<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8"/>
<title>mapbox-gl框选功能</title>
<metaname="viewport"content="initial-scale=1,maximum-scale=1,user-scalable=no"/>
<scriptsrc="js/mapbox-gl.js"></script>
<linkhref="js/mapbox-gl.css"rel="stylesheet"/>
<scriptsrc="js/turf.min.js"></script>
<style>
body {
margin: 0;
padding: 0;
}

#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}

#controlbtn {
display: flex;
position: absolute;
z-index: 99;
top: 0;
left: 0;
}
</style>
</head>

<body>

<divid="map"></div>
<divid="controlbtn">
<buttononclick="startc()">开始</button>
</div>
<script>
var map = new mapboxgl.Map({
container: 'map',
zoom: 10,
center: [116, 37],
pitch: 30,
style: {
"version": 8,
"sources": {
"mapsource": {
"type": "raster",
"tiles": ['https://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=<your token>'
],
"tileSize": 256,
},

"annotationsource": {
"type": "raster",
"tiles": ['https://t0.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=<your token>'
],
"tileSize": 256,
}
},

"layers": [{
"id": "mapsource",
"type": "raster",
"source": "mapsource",
"maxzoom": 18
}, {
"id": "annotationsource",
"type": "raster",
"source": "annotationsource",
"maxzoom": 22
}]
}
});
map.on('load', function () {
map.addSource('polysource', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
"features": []
}
});
map.addLayer({
'id': 'polysource',
'type': 'fill',
'source': 'polysource',
'paint': {
'fill-color': '#0080ff',
'fill-opacity': 0.8,
'fill-outline-color': '#fff'
}
});
});

function coordToPolygon(coord1, coord2) {
return {
"type": "Feature", "geometry": {
"type": "Polygon",
"coordinates": [
[
[
coord1.lng,
coord1.lat
],
[
coord1.lng,
coord2.lat
],
[
coord2.lng,
coord2.lat
],
[
coord2.lng,
coord1.lat
],
[
coord1.lng,
coord1.lat
]
]
]
}
};
}
function updatelayer(coord1, coord2) {
const _feature = coordToPolygon(coord1, coord2);
if (map.getSource('polysource') != undefined) {
map.getSource('polysource')
.setData({
'type': 'FeatureCollection',
"features": [_feature]
});
}
}

function startc() {
let point1;
let point2;

function mousedown(e) {
point1 = e.lngLat;
point2 = e.lngLat;
updatelayer(point1, point2);
e.preventDefault();
}
function mousemove(e) {
if (point2) {
point2 = e.lngLat;
updatelayer(point1, point2);
}
}
function mouseup(e) {
if (point2) {
point2 = e.lngLat;
updatelayer(point1, point2);
}
map.off('mousedown', mousedown);
map.off('mousemove', mousemove);
map.off('mouseup', mouseup);

}
map.on('mousedown', mousedown);
map.on('mousemove', mousemove);
map.on('mouseup', mouseup);
}
</script>
</body>
</html>


mapbox-gl实现框选操作_鼠标坐标



mapbox-gl官网地址:https://docs.mapbox.com/mapbox-gl-js/guides/

“原创不易,赞赏是对作者的最好支持!”



举报

相关推荐

0 条评论