Show labels in a single layer

This commit is contained in:
2024-08-17 22:15:32 +10:00
parent f60b1802d5
commit e1a1ff4af3
2 changed files with 58 additions and 31 deletions

File diff suppressed because one or more lines are too long

View File

@@ -40,6 +40,8 @@ fetch("wards_withboundaries.json")
"north": undefined "north": undefined
} }
var labelFeatures = [];
filteredWardData.forEach(wardData => { filteredWardData.forEach(wardData => {
const featureCollection = { const featureCollection = {
'type': 'FeatureCollection', 'type': 'FeatureCollection',
@@ -89,12 +91,28 @@ fetch("wards_withboundaries.json")
const centrePoint = polylabel(featureCollection.features[0].geometry.coordinates, 0.000001); const centrePoint = polylabel(featureCollection.features[0].geometry.coordinates, 0.000001);
map.addSource('center_'+wardData.electorateId, { if (wardData.electorateName.includes(' ')) {
'type': 'geojson', // Breaking long names into newlines looks better
'data': { const parts = wardData.electorateName.split(' ');
'type': 'FeatureCollection', // Special case if a ward starts with "St" (like "St Albans East")
'features': [ // Join the first two parts
{ if (parts[0] == "St") {
parts[0] = parts[0] + ' ' + parts[1];
parts.splice(1, 1);
}
const wardNameNewLines = parts.join('\n');
labelFeatures.push({
'type': 'Feature',
'properties': {
'description': wardNameNewLines
},
'geometry': {
'type': 'Point',
'coordinates': centrePoint
}
});
} else {
labelFeatures.push({
'type': 'Feature', 'type': 'Feature',
'properties': { 'properties': {
'description': wardData.electorateName 'description': wardData.electorateName
@@ -103,23 +121,32 @@ fetch("wards_withboundaries.json")
'type': 'Point', 'type': 'Point',
'coordinates': centrePoint 'coordinates': centrePoint
} }
});
} }
] });
map.addSource('labels', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': labelFeatures
} }
}); });
map.addLayer({ map.addLayer({
'id': 'label_'+wardData.electorateId, 'id': 'labels',
'type': 'symbol', 'type': 'symbol',
'source': 'center_'+wardData.electorateId, 'source': 'labels',
'layout': { 'layout': {
'text-field': ['get', 'description'], 'text-field': ['get', 'description'],
'text-variable-anchor': ['center', 'top', 'bottom'], 'text-variable-anchor': ['center', 'top', 'bottom'],
'text-radial-offset': 0.5,
'text-padding': 0,
'text-justify': 'auto', 'text-justify': 'auto',
'text-allow-overlap': true 'text-allow-overlap': false,
'text-ignore-placement': false,
} }
}); });
});
map.fitBounds([ map.fitBounds([
[bounds.west, bounds.south], [bounds.west, bounds.south],
@@ -132,5 +159,5 @@ fetch("wards_withboundaries.json")
}).catch(err => { }).catch(err => {
console.log(err); console.log(err);
}); });
}) });