首页 > 编程知识 正文

由圆点构成的黑白画,turtle库画圆

时间:2023-05-03 15:43:10 阅读:168354 作者:2763

文章目录要求实现思路预览效果实现代码相关链接

需求

Mapbox的公式样本只实现了点击和框选的空间查询方式,但在实际开发中还需要实现画圆变亮的元素。

实现思路要使用Canvas动态绘制圆,请根据圆心和鼠标位置计算半径,在地图上创建circle图层,然后使用turf工具函数查询与圆相交或圆中的要素预览效果与圆相交的要素。

圆内元素:

实现代码! doctypehtmlhtmlheadmetacharset=' utf-8 '/titlehighlightfeatureswithinacircle/titlemetaname=' viewport ' content=' user-scalable=no '/link href=' https://API.map box.com/map box-GL-js/v2.2.0/map box-GL.CSS ' rel=' stststtttel @ turf/turf @6/turf.min.js '/scriptstyleboom padding :00; } #map { position: absolute; top: 0; bottom: 0; width: 100%; }.box draw { background : rgba (56,135,190,0.1 ); border: 2px solid #3887be; border-radius: 50%; 定位:助手; top: 0; left: 0; width: 0; height: 0; }/style/headbodydivid=' map '/divscriptmapboxgl.access token=' youraccesstoken '; varmap=newmapboxgl.map (container : ' map )、style : ' map box ://styles/map box/streets-v11 '和center //Create a popup,but don ' taddittothemapyet.varpopup=newmapboxgl.popup ({ close button 3360 false } ); map.on('load ',function ) var canvas=map.getcanvascontainer ); //variabletoholdthestartingxycoordinates//when ` mousedown ` occured.varstart; //variabletoholdthecurrentxycoordinates//when ` mousemove ` or ` mouseup ` occurs.var current; //variableforthedrawboxelement.varbox; //addthesourcetoquery.inthisexamplewe ' reusing//countypolygonsuploadedasvectortilesmap.addsource () counties ) ' type': 'fill ',' source': 'counties ',' source-layer'3330 )。

'fill-outline-color': 'rgba(0,0,0,0.1)', 'fill-color': 'rgba(0,0,0,0.1)' } }, 'settlement-label' ); // 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 }, 'filter': ['in', 'FIPS', ''] }, 'settlement-label' ); // Place polygon under these labels. // 圆圈图层 map.addSource('circle', { 'type': 'geojson', // 空的geojson数据 'data': turf.featureCollection([]) }); map.addLayer({ 'id': 'circle', 'type': 'fill', 'source': 'circle', 'paint': { 'fill-outline-color': '#f00', 'fill-color': 'rgba(56, 135, 190, 0.1)', }, }, 'settlement-label' ); // 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); // Return the xy coordinates of the mouse position function mousePos(e) { return new mapboxgl.Point( e.clientX - canvas.clientLeft, e.clientY - canvas.clientTop ); } function mouseDown(e) { if (e.button !== 0) return; // Disable default drag 热情的故事ing when the shift key is held down. map.dragPan.disable(); // Call functions for the following events document.addEventListener('mousemove', onMouseMove); document.addEventListener('mouseup', onMouseUp); // 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'); canvas.appendChild(box); } const r = Math.sqrt(Math.pow(Math.abs(current.x - start.x), 2) + Math.pow(Math.abs(current.y - start.y), 2)); const pitch = map.getPitch(); box.style.transform = 'translate(-50%,-50%) rotateX(' + pitch + 'deg)'; box.style.left = start.x + 'px'; box.style.top = start.y + 'px'; box.style.width = r * 2 + 'px'; box.style.height = r * 2 + 'px'; } function onMouseUp(e) { // Capture xy coordinates finish(start, mousePos(e)); } function finish(from, to) { // Remove these events now that finish has been called. document.removeEventListener('mousemove', onMouseMove); document.removeEventListener('mouseup', onMouseUp); if (box) { box.parentNode.removeChild(box); box = null; } // 屏幕坐标转换 const fromCoord = map.unproject([from.x, from.y]), toCoord = map.unproject([to.x, to.y]); const fromPoint = turf.point([fromCoord.lng, fromCoord.lat]), toPoint = turf.point([toCoord.lng, toCoord.lat]); const distance = turf.distance(fromPoint, toPoint); // 将数据渲染到圆圈图层 const circle = turf.circle(fromPoint, distance); map.getSource('circle').setData(turf.featureCollection([circle])); // If bbox exists. use this value as the argument for `queryRenderedFeatures` if (circle) { const bbox = turf.bbox(circle); // 从source中获取features数据 var features = map.querySourceFeatures('counties', { sourceLayer: 'original', }); var intersectFeatures = []; features.forEach(f => { // 判断是否相交 if (turf.intersect(f, circle)) { intersectFeatures.push(f); } // if (turf.booleanOverlap(f, circle)) { // intersectFeatures.push(f); // } // 判断是否在圆圈内 // var inCircle = false; // var explode = turf.explode(f); // for (let p of explode.features) { // if (turf.booleanPointInPolygon(p, circle)) { // inCircle = true; // } else { // inCircle = false // break; // } // } // if (inCircle) { // intersectFeatures.push(f); // } }); // Run through the selected features and set a filter // to match features with unique FIPS codes to activate // the `counties-highlighted` layer. var filter = intersectFeatures.reduce( function (memo, feature) { memo.push(feature.properties.FIPS); return memo; }, ['in', 'FIPS'] ); map.setFilter('counties-highlighted', 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(); return; } var feature = features[0]; popup .setLngLat(e.lngLat) .setText(feature.properties.COUNTY) .addTo(map); }); });</script></body></html> 相关链接

Mapbox官方高亮框选范围内要素示例

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。