2017-09-29 39 views
2

我有一個矩形,需要用正方形填充它。 我找到了中心線,並希望沿着該線放置方塊。 但是有沒有簡單的方法來繪製mapboxgl中的任何其他庫像turfjs的方塊? 像設置廣場的中心和邊長,並獲得廣場的座標? 任何想法? 由於使用geojson放置圓圈不是問題,但對於我來說正方形看起來像是一個問題,因爲我必須計算4個座標。如何在線上放置方塊? (Geojson + mapbox)

enter image description here

回答

2

草皮你有手頭上有合適的工具來解決這個任務。這樣做的

一種方法是這樣的:

  1. 獲取直線距離

  2. 鴻溝與矩形的量的直線距離你想

  3. 使用草皮。沿着()沿着你的線獲得一個點

  4. 使用turf.buffer,turf.bbox和turf.bboxPolygon得到矩形上的點位置

  5. 經由mapbox-GL-JS

下面是一個代碼示例畫出一切到地圖上。你可以點擊「run code snippet」來顯示結果。

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/[email protected]/turf.min.js"></script> 
 

 
<div id="map"></div>

+0

謝謝!這很棒。但是這對於「const BUFFER_STEPS = 32;」是什麼 – SERG

+1

查看草地文檔http://turfjs.org/docs/#buffer。 turf.buffer()創建一個給定半徑的圓。它用來建立這個圓的點的數量是由一個數字定義的。我拿了32(標準是64),因爲這個圈子本身並不是真的需要。也許你甚至可以少用。 –