首页 > 解决方案 > 如何使用半径和纬度过滤 mapbox 特征

问题描述

我在 mapbox studio 上有一个图层,其中包含绘制在地图上的所有邮政编码,我正在使用 access key 和 layer id 访问它,

我只想过滤掉半径内的邮政编码(标记)

标签: mapbox-gl-js

解决方案


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>


推荐阅读