Skip to content

Instantly share code, notes, and snippets.

@wazolab
Created March 8, 2024 10:23
Multipoint support Maplibre JS
<html>
<head>
<script src='https://unpkg.com/maplibre-gl@latest/dist/maplibre-gl.js'></script>
<link href='https://unpkg.com/maplibre-gl@latest/dist/maplibre-gl.css' rel='stylesheet' />
</head>
<body>
<div id='map' style='width: 400px; height: 300px;'></div>
<button id="switch">switch</button>
<script>
function setLayerSource(layerId, source, sourceLayer) {
const oldLayers = map.getStyle().layers;
const layerIndex = oldLayers.findIndex(l => l.id === layerId);
const layerDef = oldLayers[layerIndex];
const before = oldLayers[layerIndex + 1] && oldLayers[layerIndex + 1].id;
layerDef.source = source;
if (sourceLayer) {
layerDef['source-layer'] = sourceLayer;
}
map.removeLayer(layerId);
map.addLayer(layerDef, before);
}
const flattenMultipoint = features => {
const explodedPointFeatures = []
features = features.map(f => {
if (f.geometry.type === 'MultiPoint') {
const { coordinates } = f.geometry
coordinates.forEach(coords => {
explodedPointFeatures.push({
...f,
geometry: {
type: 'Point',
coordinates: coords,
},
})
})
}
return f
}).filter(f => f.geometry.type !== 'MultiPoint')
return [...features, ...explodedPointFeatures]
}
const features = flattenMultipoint([
{
type: "Feature",
geometry: {
type: "MultiPoint",
coordinates: [[0, 0], [1, 1], [2, 2], [3, 3]]
}
},
{
type: "Feature",
geometry: {
type: "Point",
coordinates: [-3, -3]
}
}
])
var map = new maplibregl.Map({
container: 'map',
style: {
version: 8,
sources: {
carto: {
type: 'raster',
tiles: ['https://tile.openstreetmap.org/{z}/{x}/{y}.png'],
tileSize: 256,
maxzoom: 19,
},
multipoints: {
type: 'geojson',
cluster: true,
data: {
type: "FeatureCollection",
features
}
},
},
layers: [
{
id: 'background',
type: 'raster',
source: 'carto',
},
{
id: 'cluster',
type: 'point',
source: 'multipoints',
type: 'circle'
}
]
},
center: [0, 0],
zoom: 5
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment