-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlabels.js
90 lines (81 loc) · 2.43 KB
/
labels.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import area from '@turf/area'
import polylabel from 'polylabel'
import { featureCollection } from './geometry'
import defaults from './style'
// Default fonts
const fonts = {
'normal-normal': 'Open Sans Regular',
'normal-bold': 'Open Sans Bold',
'italic-normal': 'Open Sans Italic',
'italic-bold': 'Open Sans Bold Italic',
}
// Returns offset in ems
const getOffsetEms = (type, radius = 5, fontSize = 11) =>
type === 'Point' ? radius / parseInt(fontSize, 10) + 0.4 : 0
export const labelSource = (features, { fontSize }, isBoundary) => ({
type: 'geojson',
data: featureCollection(
features.map(({ geometry, properties }) => ({
type: 'Feature',
geometry: {
type: 'Point',
coordinates: getLabelPosition(geometry),
},
properties: {
name: properties.name,
anchor: geometry.type === 'Point' ? 'top' : 'center',
offset: [
0,
getOffsetEms(geometry.type, properties.radius, fontSize),
],
color: isBoundary ? properties.color : '#333',
value: properties.value,
},
}))
),
})
export const labelLayer = ({
id,
label,
fontSize,
fontStyle,
fontWeight,
color,
opacity,
}) => {
const font = `${fontStyle || 'normal'}-${fontWeight || 'normal'}`
const size = fontSize ? parseInt(fontSize, 10) : 12
return {
type: 'symbol',
id: `${id}-label`,
source: `${id}-label`,
layout: {
'text-field': label || '{name}',
'text-font': [fonts[font]],
'text-size': size,
'text-anchor': ['get', 'anchor'],
'text-offset': ['get', 'offset'],
},
paint: {
'text-color': color ? color : ['get', 'color'],
'text-opacity': opacity ?? defaults.opacity,
},
}
}
export const getLabelPosition = ({ type, coordinates }) => {
if (type === 'Point') {
return coordinates
}
let polygon = coordinates
if (type === 'MultiPolygon') {
const areas = coordinates.map(coords =>
area({
type: 'Polygon',
coordinates: coords,
})
)
const maxIndex = areas.indexOf(Math.max.apply(null, areas))
polygon = coordinates[maxIndex]
}
return polylabel(polygon, 0.1)
}