如何沿线放置方块? (以GeoJSON + mapbox)

时间:2017-09-29 11:16:26

标签: mapbox geojson mapbox-gl-js turfjs

我有一个矩形,需要用方块填充它。 我找到了中心线,并希望沿着该线放置方块。 但是有没有简单的方法在mapboxgl中绘制一个正方形与任何其他libs如turfjs? 比如设置正方形的中心和边长,得到正方形的坐标? 有任何想法吗? 因为使用geojson放置圆圈不是问题,但对于正方形看起来像是一个问题,因为我必须计算4个坐标。

enter image description here

1 个答案:

答案 0 :(得分:3)

使用草皮,您可以使用正确的工具来解决此任务。

这样做的一种方式是:

  1. 获取行距离

  2. 将行距离除以您想要的矩形数量

  3. 使用turf.along()在您的线上获得一个点

  4. 使用turf.buffer,turf.bbox和turf.bboxPolygon在点位置获取一个矩形

  5. 通过mapbox-gl-js

  6. 将所有内容绘制到地图上

    这是一个代码示例。您可以点击“运行代码段”来显示结果。

    https://jsfiddle.net/andi_lo/3rc6vca3/

    mapboxgl.accessToken = 'pk.eyJ1IjoiZmFyYWRheTIiLCJhIjoiTUVHbDl5OCJ9.buFaqIdaIM3iXr1BOYKpsQ';
    
    var map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/streets-v9',
      center: [-74.10931699675322, 4.61336863727521],
      zoom: 11,
    });
    
    map.on('load', () => {
      map.addSource('line', {
        'type': 'geojson',
        'data': {
          'type': 'FeatureCollection',
          'features': [],
        },
      });
    
      map.addSource('rect', {
        'type': 'geojson',
        'data': {
          'type': 'FeatureCollection',
          'features': [],
        },
      });
    
      map.addLayer({
        id: 'line_layer',
        source: 'line',
        type: 'line',
        paint: {
          'line-width': 3,
          'line-color': '#333',
        },
      });
    
      map.addLayer({
        id: 'rect_layer',
        source: 'rect',
        type: 'fill',
        paint: {
          'fill-color': '#00b7bf',
        },
      });
    
      const line = turf.lineString([[-74.07, 4.66], [-74.17, 4.56]]);
      const lineCollection = turf.featureCollection([line]);
      const lineDistance = turf.lineDistance(line);
      const rectCollection = turf.featureCollection([]);
    
      const RECT_COUNT = 7;
      const RECT_SIZE = 0.6;
      const BUFFER_STEPS = 32;
      const SEGMENTS = lineDistance / RECT_COUNT;
      const UNITS = 'kilometers';
      for(let i = 0; i <= RECT_COUNT; i++) {
        const point = turf.along(line, (SEGMENTS * i), UNITS);
        const buffered = turf.buffer(point, RECT_SIZE, UNITS, BUFFER_STEPS);
        const bbox = turf.bbox(buffered);
        const bboxPolygon = turf.bboxPolygon(bbox);
        rectCollection.features.push(bboxPolygon);
      }
    
      map.getSource('line').setData(lineCollection);
      map.getSource('rect').setData(rectCollection);
    });
    #map {
      height: 500px;
    }
    <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.38.0/mapbox-gl.css" rel="stylesheet"/>
    <script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.38.0/mapbox-gl.js"></script>
    <script src="https://npmcdn.com/@turf/turf@4.7.3/turf.min.js"></script>
    
    <div id="map"></div>