forked from pulsejet/InstiMapWeb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
469 lines (408 loc) · 11.8 KB
/
index.ts
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
import OlMap from 'ol/map';
import OlLayerImage from 'ol/layer/image';
import OlView from 'ol/view';
import OlExtent from 'ol/extent';
import OlOverlay from 'ol/overlay';
import OlLayerVector from 'ol/layer/vector';
import OlSourceImageStatic from 'ol/source/imagestatic';
import OlSourceVector from 'ol/source/vector';
import OlProjProjection from 'ol/proj/projection';
import OlFeature from 'ol/feature';
import OlGeomPoint from 'ol/geom/point';
import OlGeomPolygon from 'ol/geom/polygon';
import OlStyleStyle from 'ol/style/style';
import OlStyleIcon from 'ol/style/icon';
import OlStyleText from 'ol/style/text';
import OlStyleStroke from 'ol/style/stroke';
import OlStyleFill from 'ol/style/fill';
import OlInteraction from 'ol/interaction';
/** Model for location */
export interface ILocation {
id: string;
name: string;
short_name: string;
description: string;
parent: string;
parent_relation: string;
group_id: number;
pixel_x: number;
pixel_y: number;
lat: number;
lng: number;
reusable: boolean;
}
/** Configuration */
export interface InstiMapConfig {
mapPath: string;
mapMinPath: string;
markersBase: string;
attributions: string;
map_id: string;
marker_id: string;
user_marker_id: string;
}
let _config: InstiMapConfig;
/** Internal map obects */
let map: OlMap;
let view: OlView;
let vectorLayer: OlLayerVector<OlSourceVector>;
let imlayer: OlLayerImage<OlSourceImageStatic>;
let imExtent: any;
let imProjection: OlProjProjection;
/** Attributions to show on map */
let attributions: string;
/** GPS following */
let followingUser = false;
let followingUserCallback: any = null;
/** Geolocation id of watch */
let geoLocationId: number;
/** Last known geolocation */
let geoLocationLast: { pixel_x: number, pixel_y: number };
/** Whether to show residences on map */
let showResidences = false;
/** Model to convert lat-lng to pixel coords */
const MAP_Xn = 19.133691;
const MAP_Yn = 72.916984;
const MAP_Zn = 4189;
const MAP_Zyn = 1655;
const MAP_WEIGHTS_X: number[] = [
-7.769917472065843,
159.26978694839946,
244.46989575495544,
-6.003894110679995,
-0.28864271213341297,
0.010398324019718075,
4.215508849724247,
-0.6078830146963545,
-7.0400449629241395
];
const MAP_WEIGHTS_Y = [
14.199431377059842,
-158.80601990819815,
68.9630034040724,
5.796703402034644,
1.1348242200568706,
0.11891051684489184,
-0.2930832938484276,
0.1448231125788526,
-5.282895700923075
];
/** Make and get the map. Call only once. */
export function getMap(
config: InstiMapConfig,
locations: ILocation[],
locationSelectCallback: (location?: ILocation) => void,
mapLoadedCallback: () => void
): OlMap {
_config = config;
/* Make features array */
const features = [];
for (const loc of locations) {
/* Change coordinate sysetm */
const pos: [number, number] = [loc.pixel_x, 3575 - loc.pixel_y];
/* Ignore inner locations */
if (loc.parent === null) {
/* Make the Feature */
const iconFeature = new OlFeature({
geometry: new OlGeomPoint(pos),
loc: loc
});
/* Push into array */
features.push(iconFeature);
}
}
/* Make vector source and layer from features */
const vectorSource = new OlSourceVector({
features: features
});
/* Style the vector layer */
const vectorLayerStyle = (feature: any): any => {
const zoom = map.getView().getZoom();
const loc = feature.get('loc');
if (zoom === undefined)
return;
/* Hide residences */
if (loc.group_id === 3 && !showResidences) {
return;
}
/* Increase font size with zoom */
const font_size = zoom * 3;
/* Choose short name if present */
let loc_name = loc.name;
if (loc.short_name !== '0') {
loc_name = loc.short_name;
}
/* Choose icon color based on group id */
let icon_color;
if (loc.group_id === 1 || loc.group_id === 4 || loc.group_id === 12) {
icon_color = 'blue';
} else if (loc.group_id === 3) {
icon_color = 'green';
} else if (loc.group_id === 2) {
icon_color = 'yellow';
} else {
icon_color = 'gray';
}
/* Make text object */
const text = new OlStyleText({
offsetY: 20,
padding: [20, 20, 20, 20],
font: `${font_size}px Roboto`,
text: loc_name,
fill: new OlStyleFill({
color: '#ffffff'
}),
stroke: new OlStyleStroke({
color: '#444', width: 3
})
});
/* Icon image*/
const icon = new OlStyleIcon({
src: `${_config.markersBase}marker_dot_${icon_color}.png`,
scale: 0.2
});
/* Make style */
const style = new OlStyleStyle({
image: (zoom >= 3) ? icon : undefined,
text: (zoom >= 4) ? text : undefined,
});
return [style];
};
vectorLayer = new OlLayerVector({
source: vectorSource,
style: vectorLayerStyle
});
/* Configure map */
imExtent = [0, 0, 5430, 3575];
imProjection = new OlProjProjection({
code: 'instiMAP',
units: 'pixels',
extent: imExtent
});
const staticSource = new OlSourceImageStatic({
url: config.mapMinPath,
attributions: attributions,
projection: imProjection,
imageExtent: imExtent,
imageLoadFunction: (image: any, src: string) => {
/* For showing loading spinner */
const img: any = image.getImage();
img.src = src;
img.onload = () => {
loadHighRes();
mapLoadedCallback();
};
}
});
/* Make image layer */
imlayer = new OlLayerImage({
source: staticSource
});
/* Disable tilting */
const interactions = OlInteraction.defaults({ altShiftDragRotate: false, pinchRotate: false });
/* Make view */
view = new OlView({
projection: imProjection,
center: OlExtent.getCenter(imExtent),
zoom: 3.4,
minZoom: 2,
maxZoom: 5.5,
extent: [300, 300, 5000, 3000]
});
/* Generate map */
map = new OlMap({
interactions: interactions,
layers: [
imlayer,
vectorLayer
],
target: _config.map_id,
view: view,
controls: []
});
/* Handle click */
map.on('click', (evt: any) => {
/* Create extent of acceptable click */
const pixel = evt.pixel;
const pixelOffSet = 30;
const pixelWithOffsetMin: [number, number] = [pixel[0] - pixelOffSet, pixel[1] + pixelOffSet];
const pixelWithOffsetMax: [number, number] = [pixel[0] + pixelOffSet, pixel[1] - pixelOffSet];
const XYMin = map.getCoordinateFromPixel(pixelWithOffsetMin);
const XYMax = map.getCoordinateFromPixel(pixelWithOffsetMax);
const ext = XYMax.concat(XYMin);
const extentFeat = new OlFeature(new OlGeomPolygon([[
[ext[0], ext[1]],
[ext[0], ext[3]],
[ext[2], ext[3]],
[ext[2], ext[1]],
[ext[0], ext[1]]
]]));
/* Get first nearby feature */
const feature = vectorLayer.getSource()?.forEachFeatureIntersectingExtent(
extentFeat.getGeometry()?.getExtent()!, (f: any) => f
);
/* Zoom in */
if (feature) {
const location: ILocation = feature.get('loc')
moveToLocation(location);
locationSelectCallback(location);
} else {
moveMarker(-50, -50, false);
locationSelectCallback();
}
});
/* Change mouse cursor on features */
map.on('pointermove', (e: any) => {
const pixel = map.getEventPixel(e.originalEvent);
const hit = map.hasFeatureAtPixel(pixel);
const nativeElem = document.getElementById(_config.map_id);
if (nativeElem != null) {
nativeElem.style.cursor = hit ? 'pointer' : 'move';
}
});
/* Stop following the user on drag */
map.on('pointerdrag', () => {
setFollowingUser(false);
});
return map;
}
/** Move marker to a location */
export function moveToLocation(loc: ILocation) {
moveMarker(loc.pixel_x, loc.pixel_y, true);
}
/** Move the marker to location */
export function moveMarker(x: number, y: number, center = true, markerid = _config.marker_id) {
const pos: [number, number] = [Number(x), 3575 - Number(y)];
/* Check for existing overlay */
const overlay = map.getOverlayById(markerid);
/* Check for invalid coordinates */
if (overlay !== null) {
/* Overlay exists */
overlay.setPosition(pos);
} else {
/* Create a new overlay */
const element: any = document.getElementById(markerid);
const marker = new OlOverlay({
id: markerid,
position: pos,
positioning: 'bottom-center',
element: element,
stopEvent: false,
offset: [0, 0]
});
map.addOverlay(marker);
}
/* Animate */
if (center) {
view.animate({ center: pos });
view.animate({ zoom: 4.5 });
}
}
/** Show/hide residence buildings on map */
export function setResidencesVisible(visible: boolean) {
showResidences = visible;
vectorLayer.getSource()?.changed();
}
/** Load the high resolution map */
function loadHighRes(): void {
/* High res source */
const highResSource = new OlSourceImageStatic({
url: _config.mapPath,
attributions: attributions,
projection: imProjection,
imageExtent: imExtent,
});
/* Load high resolution image */
const highRes = new Image();
highRes.src = _config.mapPath;
highRes.onload = () => {
imlayer.setSource(highResSource);
};
}
/** Determine if we support geolocation */
export function hasGeolocation(): boolean {
return navigator.geolocation ? true : false;
}
/** Setup a location watch */
export function getGPS(failedCallback?: () => void): void {
if (hasGeolocation()) {
/* Start following the user */
setFollowingUser(true);
/* If we already have permission */
if (geoLocationId != null) {
moveGPS(true);
return;
}
/* Get permission and setup a watch */
geoLocationId = navigator.geolocation.watchPosition((position: GeolocationPosition) => {
const follow = followingUser || geoLocationLast == null;
const l = getMapXY(position);
if (l.pixel_x > 0 && l.pixel_y > 0 && l.pixel_x < 5430 && l.pixel_y < 5375) {
geoLocationLast = l;
moveGPS(follow);
}
}, () => { }, {
enableHighAccuracy: true
});
} else {
if (failedCallback) {
failedCallback();
}
}
}
/** Center the user marker to last known location */
function moveGPS(center: boolean) {
if (geoLocationLast == null) { return; }
moveMarker(
geoLocationLast.pixel_x,
geoLocationLast.pixel_y,
center,
_config.user_marker_id
);
}
/** Apply regression to get pixel coordinates on InstiMap */
export function getMapXY(position: GeolocationPosition): { pixel_x: number, pixel_y: number } {
/* Set the origin */
const x = (position.coords.latitude - MAP_Xn) * 1000;
const y = (position.coords.longitude - MAP_Yn) * 1000;
/* Apply the model */
let A = MAP_WEIGHTS_X;
const px = Math.round(
MAP_Zn + A[0] + A[1] * x + A[2] * y +
A[3] * x * x + A[4] * x * x * y +
A[5] * x * x * y * y + A[6] * y * y +
A[7] * x * y * y + A[8] * x * y);
A = MAP_WEIGHTS_Y;
const py = Math.round(
MAP_Zyn + A[0] + A[1] * x + A[2] * y +
A[3] * x * x + A[4] * x * x * y +
A[5] * x * x * y * y + A[6] * y * y +
A[7] * x * y * y + A[8] * x * y);
return { pixel_x: px, pixel_y: py };
}
/** True if the user is being followed around the map */
export function isFollowingUser(): boolean {
return followingUser;
}
/** Setter for followingUser */
export function setFollowingUser(val: boolean): void {
if (followingUser === val) { return; }
followingUser = val;
if (followingUserCallback != undefined && followingUserCallback != null) {
followingUserCallback(followingUser);
}
}
/** Last known geolocation */
export function getGeolocationLast(): any {
return geoLocationLast;
}
/** Call this to remove watches */
export function cleanup() {
if (geoLocationId != null && geoLocationId != undefined) {
navigator.geolocation.clearWatch(geoLocationId);
}
}
/** Add event listener for followinguser change */
export function addOnUserFollowingChangeListener(callback: (val: boolean) => void) {
followingUserCallback = callback;
}