Rectangles along a line
HTML
<script src=" https://npmcdn.com/@turf/turf/turf.min.js"></script>
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.38.0/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.38.0/mapbox-gl.css">
<div id="map"></div>
CSS
#map {
height: 500px;
}
JavaScript
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',
},
});
turfCT_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);
});