mapbox-gl-js - 如何使用半径和纬度过滤 mapbox 特征
问题描述
我在 mapbox studio 上有一个图层,其中包含绘制在地图上的所有邮政编码,我正在使用 access key 和 layer id 访问它,
我只想过滤掉半径内的邮政编码(标记)
解决方案
Turf 提供了一个pointsWithinPolygon()函数,可以帮助您找到圆内的任何点。这是一个例子:
mapboxgl.accessToken = 'pk.eyJ1IjoicGFybmRlcHUiLCJhIjoiY2l6dXZ5OXVkMDByZDMycXI2NGgyOGdyNiJ9.jyTchGQ8N1gjPdra98qRYg';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v10',
center: [-46.6062, -23.5513],
zoom: 11
});
map.on('load', function () {
// List of your marker locations
var points = turf.points([
[-46.6318, -23.5523],
[-46.6246, -23.5325],
[-46.6062, -23.5513],
[-46.663, -23.554],
[-46.643, -23.557]
]);
// Create circle with radius
var center = [-46.6062, -23.5513];
var radius = 3;
var options = {steps: 10, units: 'kilometers', properties: {foo: 'bar'}};
var circle = turf.circle(center, radius, options);
// Find point within circle
var markerWithin = turf.pointsWithinPolygon(points, circle);
console.log("Found: " + markerWithin.features.length + " points");
// Draw circle polygon
map.addLayer({
'id': 'circle',
'type': 'fill',
'source': {
'type': 'geojson',
'data': circle
},
'layout': {},
'paint': {
'fill-color': '#525252',
'fill-opacity': 0.2
}
});
// Draw all points
map.addLayer({
'id': 'points',
'type': 'circle',
'source': {
'type': 'geojson',
'data': points
},
'layout': {},
'paint': {
'circle-radius': 5,
'circle-color': 'red',
'circle-opacity': 1
}
});
// Draw marker with in circle
markerWithin.features.forEach(function(marker) {
// Create marker
new mapboxgl.Marker()
.setLngLat(marker.geometry.coordinates)
.addTo(map);
});
});
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; };
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.5.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.5.0/mapbox-gl.css' rel='stylesheet' />
<script src='https://npmcdn.com/@turf/turf/turf.min.js'></script>
<div id='map'></div>
推荐阅读
- java - 如何在 Java 中获取深度嵌套的 JSON 对象
- nokia - 如何在诺基亚 8110 4G 中切换开发者模式?
- javascript - 在循环内映射数组
- python - Tensorflow:DLL加载失败:动态链接库(DLL)初始化例程失败
- php - 如何合并2个对象laravel
- android - 使用 RecyclerView 时如何解决 NullPointerException?
- mysql - 为什么使用带注释的 OneToMany 单向映射时数据库 MySql 中的 POJO 属性位置发生了变化?
- c++ - Transform a buffer into an istream to work in existing programs
- android - 将 ImageView 转换为具有本机分辨率的位图
- c# - 理解 C# 中的组合