Center/centroid/centerOfMass/pointOnFeature
by amay077
HTML
<script src="https://cdn.jsdelivr.net/npm/@turf/turf@5/turf.min.js"></script>
<script src="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css">
<div id="map" style="width:100%; height: 100vh;"></div>
CSS
body {
margin: 0;
padding: 0;
}
JavaScript
const polygon1 = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[ 137.796, 34.940 ],
[ 137.748, 34.882 ],
[ 137.887, 34.888 ],
[ 137.796, 34.940 ]
],
[
[ 137.812, 34.926 ],
[ 137.779, 34.892 ],
[ 137.855, 34.897 ],
[ 137.812, 34.926 ]
]
]
}
};
const polygon2 = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[137.8877,34.9171],
[137.8867,34.8922],
[137.9134,34.8915],
[137.9135,34.8956],
[137.8918,34.8963],
[137.8923,34.9138],
[137.9057,34.9134],
[137.9058,34.9172],
[137.8877,34.9171]
]
]
}
};
const dataSource = {
'type': 'geojson',
'data': {
"type": "FeatureCollection",
"features": [
polygon1,
polygon2,
]
}
};
const lineFeature = {
type: 'FeatureCollection',
features: [
{
"type": "Feature",
"properties": {},
"geometry": {
"type":"LineString",
"coordinates": []
}
}
]
};
let marker;
const bounds = turf.bbox(dataSource.data);
const map = new mapboxgl.Map({
container: 'map',
bounds: bounds,
style: {
version: 8,
sources: {
OSM: {
type: "raster",
tiles: [
"https://a.tile.openstreetmap.org/{z}/{x}/{y}.png",
],
tileSize: 256,
attribution:
"OpenStreetMap",
},
},
layers: [{
id: "BASEMAP",
type: "raster",
source: "OSM",
minzoom: 0,
maxzoom: 18,
}],
},
});
map.once('load', () => {
map.fitBounds(bounds, { padding: { bottom: 50, top: 50, right: 50, left: 50 }});
map.addSource('route', dataSource);
map.addLayer({
'id': 'route',
'type': 'fill',
'source': 'route',
'paint': {
'fill-color': '#088',
'fill-opacity':...