-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmap.js
More file actions
402 lines (351 loc) · 12 KB
/
map.js
File metadata and controls
402 lines (351 loc) · 12 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import { centroid } from '@turf/centroid'
// @ts-expect-error - no types
import OsGridRef, { LatLon } from 'geodesy/osgridref.js'
import { processGeospatial } from '~/src/client/javascripts/geospatial-map.js'
import { processLocation } from '~/src/client/javascripts/location-map.js'
// Center of UK
const DEFAULT_LAT = 53.825564
const DEFAULT_LONG = -2.421975
const COMPANY_SYMBOL_CODE = 169
const defaultData = {
VTS_OUTDOOR_URL: '/api/maps/vts/OS_VTS_3857_Outdoor.json',
VTS_DARK_URL: '/api/maps/vts/OS_VTS_3857_Dark.json',
VTS_BLACK_AND_WHITE_URL: '/api/maps/vts/OS_VTS_3857_Black_and_White.json'
}
/**
* Converts lat long to easting and northing
* @param {object} param
* @param {number} param.lat
* @param {number} param.long
* @returns {{ easting: number, northing: number }}
*/
export function latLongToEastingNorthing({ lat, long }) {
const point = new LatLon(lat, long)
return point.toOsGrid()
}
/**
* Converts easting and northing to lat long
* @param {object} param
* @param {number} param.easting
* @param {number} param.northing
* @returns {{ lat: number, long: number }}
*/
export function eastingNorthingToLatLong({ easting, northing }) {
const point = new OsGridRef(easting, northing)
const latLong = point.toLatLon()
return { lat: latLong.latitude, long: latLong.longitude }
}
/**
* Converts lat long to an ordnance survey grid reference
* @param {object} param
* @param {number} param.lat
* @param {number} param.long
* @returns {string}
*/
export function latLongToOsGridRef({ lat, long }) {
const point = new LatLon(lat, long)
return point.toOsGrid().toString()
}
/**
* Converts an ordnance survey grid reference to lat long
* @param {string} osGridRef
* @returns {{ lat: number, long: number }}
*/
export function osGridRefToLatLong(osGridRef) {
const point = OsGridRef.parse(osGridRef)
const latLong = point.toLatLon()
return { lat: latLong.latitude, long: latLong.longitude }
}
/**
* Get the grid ref from the first coordinate of a long/lat feature
* @param {Feature} feature
*/
export function getCoordinateGridRef(feature) {
if (feature.geometry.type === 'Point') {
const [long, lat] = feature.geometry.coordinates
const point = new LatLon(lat, long)
return point.toOsGrid().toString()
} else if (feature.geometry.type === 'LineString') {
const [long, lat] = feature.geometry.coordinates[0]
const point = new LatLon(lat, long)
return point.toOsGrid().toString()
} else {
const [long, lat] = feature.geometry.coordinates[0][0]
const point = new LatLon(lat, long)
return point.toOsGrid().toString()
}
}
/**
* Get the centroid grid ref from a long/lat feature
* @param {Feature} feature
*/
export function getCentroidGridRef(feature) {
if (feature.geometry.type === 'Point') {
const [long, lat] = feature.geometry.coordinates
const point = new LatLon(lat, long)
return point.toOsGrid().toString()
} else {
const centre = centroid(feature)
const [long, lat] = centre.geometry.coordinates
const point = new LatLon(lat, long)
return point.toOsGrid().toString()
}
}
/** @type {InteractiveMapInitConfig} */
export const defaultConfig = {
zoom: '6',
center: [DEFAULT_LONG, DEFAULT_LAT]
}
export const EVENTS = {
mapReady: 'map:ready',
interactMarkerChange: 'interact:markerchange',
drawReady: 'draw:ready',
drawCreated: 'draw:created',
drawEdited: 'draw:edited',
drawCancelled: 'draw:cancelled'
}
/**
* Make a form submit handler that only allows submissions from allowed buttons
* @param {HTMLButtonElement[]} buttons - the form buttons to allow submissions
*/
export function formSubmitFactory(buttons) {
/**
* The submit handler
* @param {SubmitEvent} e
*/
const onFormSubmit = function (e) {
if (
!(e.submitter instanceof HTMLButtonElement) ||
!buttons.includes(e.submitter)
) {
e.preventDefault()
}
}
return onFormSubmit
}
/**
* Initialise location maps
* @param {Partial<MapsEnvironmentConfig>} config - the map configuration
*/
export function initMaps(config = {}) {
const {
assetPath = '/assets',
apiPath = '/form/api',
data = defaultData
} = config
const locations = document.querySelectorAll('.app-location-field')
const geospatials = document.querySelectorAll('.app-geospatial-field')
// TODO: Fix this in `interactive-map`
// If there are location components on the page fix up the main form submit
// handler so it doesn't fire when using the integrated map search feature
if (locations.length) {
const form = locations[0].closest('form')
if (form === null) {
return
}
const buttons = Array.from(form.querySelectorAll('button'))
form.addEventListener('submit', formSubmitFactory(buttons), false)
}
if (geospatials.length) {
const form = geospatials[0].closest('form')
if (form === null) {
return
}
const buttons = Array.from(form.querySelectorAll('button'))
form.addEventListener('submit', formSubmitFactory(buttons), false)
}
locations.forEach((location, index) => {
processLocation({ assetPath, apiPath, data }, location, index)
})
geospatials.forEach((geospatial, index) => {
processGeospatial({ assetPath, apiPath, data }, geospatial, index)
})
}
/**
* OS API request proxy factory
* @param {string} apiPath - the root API path
*/
export function makeTileRequestTransformer(apiPath) {
/**
* Proxy OS API requests via our server
* @param {string} url - the request URL
* @param {string} resourceType - the resource type
*/
return function transformTileRequest(url, resourceType) {
if (url.startsWith('https://api.os.uk')) {
if (resourceType === 'Tile') {
return {
url: url.replace(
'https://api.os.uk/maps/vector/v1/vts',
`${window.location.origin}${apiPath}`
),
headers: {}
}
}
if (resourceType !== 'Style') {
return {
url: `${apiPath}/map-proxy?url=${encodeURIComponent(url)}`,
headers: {}
}
}
}
const spritesPath =
'https://raw.githubusercontent.com/OrdnanceSurvey/OS-Vector-Tile-API-Stylesheets/main'
// Proxy sprite requests
if (url.startsWith(spritesPath)) {
const path = url.substring(spritesPath.length)
return {
url: `${apiPath}/maps/vts${path}`,
headers: {}
}
}
return { url, headers: {} }
}
}
/**
* Temporary transform request function to transform geocode requests. Fixed in v0.0.18 of interactive map so this is not needed when we upgrade.
* @param {object} request
* @param {string} request.url
* @param {{ method: 'get' }} request.options
* @returns {Request}
*/
export const transformGeocodeRequest = (request) => {
const url = new URL(request.url, window.location.origin)
return new Request(url.toString(), request.options)
}
/**
* Create a Defra map instance
* @param {string} mapId - the map id
* @param {InteractiveMapInitConfig} initConfig - the map initial configuration
* @param {MapsEnvironmentConfig} mapsConfig - the map environment params
*/
export function createMap(mapId, initConfig, mapsConfig) {
const { assetPath, apiPath, data = defaultData } = mapsConfig
const logoAltText = 'Ordnance survey logo'
// @ts-expect-error - Defra namespace currently comes from UMD support files
const defra = window.defra
const interactPlugin = defra.interactPlugin({
markerColor: { outdoor: '#ff0000', dark: '#00ff00' },
interactionMode: 'marker',
multiSelect: false
})
/** @type {InteractiveMap} */
const map = new defra.InteractiveMap(mapId, {
enableFullscreen: true,
autoColorScheme: false,
mapProvider: defra.maplibreProvider(),
reverseGeocodeProvider: defra.openNamesProvider({
url: `${apiPath}/reverse-geocode-proxy?easting={easting}&northing={northing}`
}),
behaviour: 'inline',
minZoom: 6,
maxZoom: 18,
containerHeight: '400px',
enableZoomControls: true,
transformRequest: makeTileRequestTransformer(apiPath),
...initConfig,
plugins: [
defra.mapStylesPlugin({
mapStyles: [
{
id: 'outdoor',
label: 'Outdoor',
url: data.VTS_OUTDOOR_URL,
thumbnail: `${assetPath}/interactive-map/assets/images/outdoor-map-thumb.jpg`,
logo: `${assetPath}/interactive-map/assets/images/os-logo.svg`,
logoAltText,
attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`,
backgroundColor: '#f5f5f0'
},
{
id: 'dark',
label: 'Dark',
url: data.VTS_DARK_URL,
mapColorScheme: 'dark',
appColorScheme: 'dark',
thumbnail: `${assetPath}/interactive-map/assets/images/dark-map-thumb.jpg`,
logo: `${assetPath}/interactive-map/assets/images/os-logo-white.svg`,
logoAltText,
attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`
},
{
id: 'black-and-white',
label: 'Black/White',
url: data.VTS_BLACK_AND_WHITE_URL,
thumbnail: `${assetPath}/interactive-map/assets/images/black-and-white-map-thumb.jpg`,
logo: `${assetPath}/interactive-map/assets/images/os-logo-black.svg`,
logoAltText,
attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`
}
]
}),
interactPlugin,
defra.searchPlugin({
transformRequest: transformGeocodeRequest,
osNamesURL: `${apiPath}/geocode-proxy?query={query}`,
width: '300px',
showMarker: false
}),
defra.scaleBarPlugin({
units: 'metric'
}),
...(initConfig.plugins ?? [])
]
})
return { map, interactPlugin }
}
/**
* Updates the marker position and moves the map view port the new location
* @param {InteractiveMap} map - the map component instance (of InteractiveMap)
* @param {MapLibreMap} mapProvider - the map provider instance (of MapLibreMap)
* @param {MapCenter} center - the point
*/
export function centerMap(map, mapProvider, center) {
// Move the 'location' marker to the new point
map.addMarker('location', center)
// Pan & zoom the map to the new valid location
mapProvider.flyTo({
center,
zoom: 14,
essential: true
})
}
/**
* @typedef {object} InteractiveMap - an instance of a InteractiveMap
* @property {Function} on - register callback listeners to map events
* @property {Function} addPanel - adds a new panel to the map
* @property {Function} addMarker - adds/updates a marker
* @property {Function} removeMarker - removes a marker
* @property {Function} addButton - adds/updates a button
* @property {Function} toggleButtonState - toggle the state of a button
*/
/**
* @typedef {object} MapLibreMap
* @property {Function} flyTo - pans/zooms to a new location
* @property {Function} fitBounds - fits the my to the new bounds
*/
/**
* @typedef {[number, number]} MapCenter - Map center point as [long, lat]
*/
/**
* @typedef {object} InteractiveMapInitConfig - additional config that can be provided to InteractiveMap
* @property {string} zoom - the zoom level of the map
* @property {MapCenter} center - the center point of the map
* @property {{ id: string, coords: MapCenter }[]} [markers] - the markers to add to the map
* @property {any[]} [plugins] - additional plugins
*/
/**
* @typedef {object} TileData
* @property {string} VTS_OUTDOOR_URL - the outdoor tile URL
* @property {string} VTS_DARK_URL - the dark tile URL
* @property {string} VTS_BLACK_AND_WHITE_URL - the black and white tile URL
*/
/**
* @typedef {object} MapsEnvironmentConfig
* @property {string} assetPath - the root asset path
* @property {string} apiPath - the root API path
* @property {TileData} data - the tile data config
*/
/**
* @import { Feature } from '~/src/server/plugins/engine/types.js'
*/