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,
},
},
});
方法二效果 ![方法二效果](https://img-blog.csdnimg.cn/5deb980a8d9542e299ca6c4a853384f2.png#pic_center)
方法三: 使用自定义方法切割圆 (与一实现相同)
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
|