MapBoxGL.JS 画圆 (半径以米或千米为单位) 实现跟随地图缩放而缩放

您所在的位置:网站首页 圆画的画 MapBoxGL.JS 画圆 (半径以米或千米为单位) 实现跟随地图缩放而缩放

MapBoxGL.JS 画圆 (半径以米或千米为单位) 实现跟随地图缩放而缩放

2024-06-03 17:39| 来源: 网络整理| 查看: 265

MapBoxGL.JS 画固定大小的圆 方法一: 使用 turf.circle 实现 (推荐)方法二: 利用 circle-radius 的 stops 属性保持缩放 (可能有问题)方法三: 使用自定义方法切割圆 (与一实现相同)

遇到一个需求要在地图上画一个半径以米为单位的圆,本以为很简单没想到 官网给的例子中 只有以像素为单位的圆(圆的大小不会因为地图缩放而改变) 在网上找的了几个可以实现的方法分享一下

方法一: 使用 turf.circle 实现 (推荐)

先安装 @turf/circle

npm install @turf/circle

代码中使用 @turf/circle 生成 圆的Geojson

import turf_circle from "@turf/circle"; ... let center = [ 121.47343598230209,31.317850323998645]; // 中心点 圆心 let radius = 8477.70727135986 / 1000; // 半径 let options = { steps: 64, //分割数量 数量越多圆越精细 默认值:64(如果圆比较大推荐类似 Math.floor(radius) * 10 这样根据半径可变的切割) units: "kilometers", //单位 可选值:degrees, radians, miles, kilometers }; let circle = turf_circle(center, radius, options); // 添加 map.addSource("circle", { type: "geojson", data: circle, }); //样式 map.addLayer({ id: "circleLine", type: "line", source: "circle", paint: { "line-color": "#000", "line-width": 3, }, });

方法一效果 方法一效果

方法二: 利用 circle-radius 的 stops 属性保持缩放 (可能有问题) // 半径(米) 纬度 const metersToPixelsAtMaxZoom = (meters, latitude) =>{ return meters / 0.075 / Math.cos((latitude * Math.PI) / 180); } const geojson = { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Point", "coordinates": [ 121.47343598230209, 31.317850323998645 ] }, "properties": { "subType": "Circle", "radius": 8477.70727135986, } } ] }; map.addSource("circle2", { type: "geojson", data: geojson, }); map.addLayer({ id: "circleLine2", type: "circle", source: "circle2", paint: { "circle-color": "#51bbd6", "circle-radius": { stops: [ // 重点 [0, 0], [ 20, metersToPixelsAtMaxZoom( geojson.features[0].properties.radius, geojson.features[0].geometry.coordinates[1] ), ], ], base: 2, }, }, });

方法二效果 方法二效果

方法三: 使用自定义方法切割圆 (与一实现相同) var 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 "type": "geojson", "data": { "type": "FeatureCollection", "features": [{ "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ret] } }] } }; }; map.addSource("polygon", createGeoJSONCircle([-93.6248586, 41.58527859], 0.5)); map.addLayer({ "id": "polygon", "type": "fill", "source": "polygon", "layout": {}, "paint": { "fill-color": "blue", "fill-opacity": 0.6 } });

如果有不懂的可以留言提问 文章主要参考 https://stackoverflow.com/questions/37599561/drawing-a-circle-with-the-radius-in-miles-meters-with-mapbox-gl-js



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3