-
Notifications
You must be signed in to change notification settings - Fork 5
/
mapfornextbutton.html
388 lines (326 loc) · 13.1 KB
/
mapfornextbutton.html
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
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Locate the user</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<link href="https://api.mapbox.com/mapbox-gl-js/v2.14.1/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.14.1/mapbox-gl.js"></script>
<script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v4.1.1/mapbox-gl-directions.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
.mapboxgl-ctrl-directions { /*to make direction text on white background for clarity */
background-color: white;
border-radius: 10px;
padding: 10px;
}
.button {
position: absolute;
bottom: 40px;
padding: 20px;
font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
font-size: 20px;
cursor: pointer;
border-radius: 150px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.exit-button {
right: 150px;
background-color: red;
color: white;
}
.finish-button {
right: 20px;
background-color: deepskyblue;
color: white;
}
@media (max-width: 600px){
.mapboxgl-ctrl-directions.mapboxgl-ctrl {
background-color: #fefefe;
line-height: 140%;
font-size: 60%;
}
.button {
position: absolute;
bottom: 20px;
font-size: 18px;
border-radius: 100px;
}
.exit-button {
left: 20px;
right: unset;
}
}
</style>
</head>
<body>
<div id="map"></div>
<div id="exitButton" class="button exit-button">Leave</div>
<div id="finishButton" class="button finish-button">Arrived</div>
<script>
mapboxgl.accessToken = 'pk.eyJ1Ijoib3N3ZWdvdG91cnN3ZWJhcHAiLCJhIjoiY2xuZTU0eTdxMGFlbzJrc2UyNGQ0eXJnNSJ9.1bNTRWmRobVRG96ohJEeOg';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v12', // style URL
center: [-76.54379514160124, 43.45085042301986], // starting position
zoom: 3 // starting zoom
});
// set the bounds for the map
const bounds = [
[-78, 41],
[-74, 45]
];
// data for all nine sites
const sites = [
{
name: "Oswego Town Hall with Dr. Mary Walker Statue",
confirmationText: "You should see the Oswego Town Hall with Dr. Mary Walker's Statue in front of it.",
color: 'purple',
lngLat: [-76.53323681368194, 43.415413142383535],
redirectLink: 'site-data/site1.html'
},
{
name: "Town of Oswego Historical Society Museum",
confirmationText: "The Oswego Town Historical Society Museum should be in sight.",
color: 'purple',
lngLat: [-76.53340110021806, 43.415141546532695],
redirectLink: 'site-data/site2.html'
},
{
name: "Birthplace Marker for Dr. Mary Walker's Home (Destroyed)",
confirmationText: "Mary Walker's Birth home is no longer there, but you should see the marker.",
color: 'purple',
lngLat: [-76.5532980, 43.4053885],
redirectLink: 'site-data/site3.html'
},
{
name: "Oswego Town Rural Cemetery",
color: 'purple',
confirmationText: "Mary Walker's tombstone is in the old section in the back. You can't see it from the road; no worries, we will give you directions.",
lngLat: [-76.55065542947133, 43.425349995889405],
redirectLink: 'site-data/site4.html'
},
{
name: "Mary Walker Health Center",
color: 'purple',
confirmationText: "You should see Mary Walker Health Center on the SUNY Oswego campus. Find a good parking spot and view the site information.",
lngLat: [-76.54294833267187, 43.4556889142642],
redirectLink: 'site-data/site5.html'
},
{
name: "Mural of Dr. Mary Walker on Downtown Bookstore Building",
color: 'purple',
confirmationText: "You should see a mural of Dr. Mary Walker's on the bookstore building. Remember to park in the provided spaces before clicking 'ok'.",
lngLat: [-76.51169746190004, 43.45668452411192],
redirectLink: 'site-data/site6.html'
},
{
name: "City Hall",
color: 'purple',
confirmationText: "You should see the Oswego City Hall. Town members are friendly 😉, feel free to ask around if unsure.",
lngLat: [-76.51116790993515, 43.45532517841785],
redirectLink: 'site-data/site7.html'
},
{
name: "Fort Ontario",
color: 'purple',
confirmationText: "Fort Ontario is iconic! You wouldn't miss it if you tried.",
lngLat: [-76.506997, 43.463550],
redirectLink: 'site-data/site8.html'
},
{
name: "Oswego County Historical Society at the Richardson-Bates House Museum",
color: 'purple',
confirmationText: "If you see a light-pink mansion, you are definitely in the right spot. You can go say 'Hi' if its open!",
lngLat: [-76.503723418059, 43.4555358800825],
redirectLink: 'site-data/site9.html'
}
]
sites.forEach(({ name, color, lngLat }) => {
// create the popup
const popup = new mapboxgl.Popup({offset: 25}).setText(name);
// add marker (testing for now)
const marker = new mapboxgl.Marker({
color,
scale: 0.8
})
.setLngLat(lngLat)
.setPopup(popup)
.addTo(map);
});
// Initialize the geolocate control.
const geolocate = new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true,
showUserHeading: true
});
// Add the control to the map.
map.addControl(geolocate);
map.on('load', () => {
geolocate.trigger();
});
// when an error event occurs.
geolocate.on('error', () => {
alert('Could not retrieve your location :(');
});
// when an outofmaxbounds event occurs.
geolocate.on('outofmaxbounds', () => {
alert.log('You are out of bounds!');
window.location.href = "index.html";
});
// Create a new Directions object
const directions = new MapboxDirections({
accessToken: mapboxgl.accessToken,
profile: 'mapbox/driving',
interactive: false,
controls: {
inputs: false,
instructions: true,
profileSwitcher: true,
attributionControl: false
}
});
// Add the directions control to the map (top-left)
map.addControl(directions, 'top-left');
let efficientRoute;
if (localStorage.getItem('efficientRoute') === null){ // if null, populate with efficientRoute array
function success(e) {
const userLocation = [e.coords.longitude, e.coords.latitude];
let startingIndex = 0;
// Calculate the closest destination
let closestDestination = sites[0];
let closestDistance = getDistance(userLocation, sites[0].lngLat);
for (let i = 1; i < sites.length; i++) {
const distance = getDistance(userLocation, sites[i].lngLat);
if (distance < closestDistance) {
closestDestination = sites[i];
closestDistance = distance;
startingIndex = i;
}
}
// user will be at the first location already, so remove the first element
efficientRoute = getEfficientRoute(sites, startingIndex).slice(1);
localStorage.setItem('efficientRoute', JSON.stringify(efficientRoute));
runMap(efficientRoute[0]);
}
function error(error) {
console.error('Could not retrieve location', error);
window.location.href = 'freeexploration.html'
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
console.error('Geolocation is not supported by this browser/device.');
window.location.href = 'freeexploration.html'
}
}else {
efficientRoute = JSON.parse(localStorage.getItem('efficientRoute'));
runMap(efficientRoute[0]);
}
function runMap(nextSiteIndex){
let siteIndex = nextSiteIndex;
// Set the origin and destination (origin updates)
geolocate.on('geolocate', function(e) {
const userLocation = [e.coords.longitude, e.coords.latitude];
directions.setOrigin(userLocation);
map.flyTo({
center: userLocation,
zoom: 12,
essential: true
});
map.setMaxBounds(bounds);
directions.setDestination(sites[siteIndex].lngLat);
});
}
// Haversine formula (inspired by the function @geekforgeeks)
function getDistance(coord1, coord2) {
const lng1 = coord1[0];
const lat1 = coord1[1];
const lng2 = coord2[0];
const lat2 = coord2[1];
const earthRadiusInKm = 6371;
const latitudeInRadians = deg2rad(lat2 - lat1);
const longitudeInRadians = deg2rad(lng2 - lng1);
const chordLenBtwnCoords =
Math.sin(latitudeInRadians / 2) * Math.sin(latitudeInRadians / 2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(longitudeInRadians / 2) * Math.sin(longitudeInRadians / 2);
const angularDistBtwnCoords = 2 * Math.atan2(Math.sqrt(chordLenBtwnCoords), Math.sqrt(1 - chordLenBtwnCoords));
return earthRadiusInKm * angularDistBtwnCoords; // distance
}
function deg2rad(deg) {
return deg * (Math.PI / 180.0);
}
function getEfficientRoute(sites, startingPointIndex) {
const n = sites.length;
const visited = new Array(n).fill(false);
const path = [startingPointIndex];
visited[startingPointIndex] = true;
while (path.length < n) {
let nearestIndex = -1;
let minDistance = Infinity;
const lastPoint = sites[path[path.length - 1]].lngLat;
for (let i = 0; i < n; i++) {
if (!visited[i]) {
const distance = getDistance(lastPoint, sites[i].lngLat);
if (distance < minDistance) {
minDistance = distance;
nearestIndex = i;
}
}
}
path.push(nearestIndex);
visited[nearestIndex] = true;
}
path.push(startingPointIndex);
return path;
}
// Redirect when user exit map
const exitButton = document.getElementById('exitButton');
exitButton.addEventListener('click', () => {
window.location.href = 'freeexploration.html';
localStorage.clear();
});
// Confirm if user has arrived at destination
const finishButton = document.getElementById('finishButton');
finishButton.addEventListener('click', () => {
let address;
const url = "https://api.mapbox.com/geocoding/v5/mapbox.places/" + sites[efficientRoute[0]].lngLat[0]
+ "," + sites[efficientRoute[0]].lngLat[1] + ".json?access_token=" +
mapboxgl.accessToken + "&types=address";
fetch(url)
.then(response => response.json())
.then(data => {
address = data.features[0].place_name;
let confirmationText = sites[efficientRoute[0]].confirmationText;
const userConfirmation = confirm(`Are you at ${address}? \n${confirmationText}`);
if (userConfirmation) {
window.location.href = sites[efficientRoute[0]].redirectLink;
if(efficientRoute.length === 1){
localStorage.clear();
}else{
efficientRoute = efficientRoute.slice(1);
localStorage.setItem('efficientRoute', JSON.stringify(efficientRoute));
}
}
})
.catch(error => console.error('Error:', error));
});
</script>
</body>
</html>