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,36 +91,61 @@ 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") {
'type': 'Feature', parts[0] = parts[0] + ' ' + parts[1];
'properties': { parts.splice(1, 1);
'description': wardData.electorateName
},
'geometry': {
'type': 'Point',
'coordinates': centrePoint
}
}
]
} }
}); const wardNameNewLines = parts.join('\n');
labelFeatures.push({
'type': 'Feature',
'properties': {
'description': wardNameNewLines
},
'geometry': {
'type': 'Point',
'coordinates': centrePoint
}
});
} else {
labelFeatures.push({
'type': 'Feature',
'properties': {
'description': wardData.electorateName
},
'geometry': {
'type': 'Point',
'coordinates': centrePoint
}
});
}
});
map.addLayer({ map.addSource('labels', {
'id': 'label_'+wardData.electorateId, 'type': 'geojson',
'type': 'symbol', 'data': {
'source': 'center_'+wardData.electorateId, 'type': 'FeatureCollection',
'layout': { 'features': labelFeatures
'text-field': ['get', 'description'], }
'text-variable-anchor': ['center', 'top', 'bottom'], });
'text-justify': 'auto',
'text-allow-overlap': true map.addLayer({
} 'id': 'labels',
}); 'type': 'symbol',
'source': 'labels',
'layout': {
'text-field': ['get', 'description'],
'text-variable-anchor': ['center', 'top', 'bottom'],
'text-radial-offset': 0.5,
'text-padding': 0,
'text-justify': 'auto',
'text-allow-overlap': false,
'text-ignore-placement': false,
}
}); });
map.fitBounds([ map.fitBounds([
@@ -132,5 +159,5 @@ fetch("wards_withboundaries.json")
}).catch(err => { }).catch(err => {
console.log(err); console.log(err);
}); });
}) });