-
Notifications
You must be signed in to change notification settings - Fork 0
/
map-turf-nearest.html
523 lines (457 loc) · 19.2 KB
/
map-turf-nearest.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
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Isochrone Map - Singapore MacDonalds coverage based on travel time (walking)</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<!--import bulma-->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<!-- Import Mapbox GL JS -->
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.10.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.10.0/mapbox-gl.css' rel='stylesheet' />
<!-- Import Assembly -->
<link href='https://api.mapbox.com/mapbox-assembly/v0.23.2/assembly.min.css' rel='stylesheet'>
<script src='https://api.mapbox.com/mapbox-assembly/v0.23.2/assembly.js'></script>
<!-- Import jQuery -->
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<!-- Import style for map with sidebar-->
<link href="sidebar-responsive.css" rel="stylesheet" type="text/css" />
<!--Import custom control-->
<script src='custom-control.js' type="text/javascript"></script>
<!--import turf-->
<script src="https://cdn.jsdelivr.net/npm/@turf/turf@5/turf.min.js"></script>
<style>
html {
background-color: #323432;
}
.custom {
height: 100%;
overflow: auto;
padding-bottom: 1em;
background: #323432;
}
.custom .toggle-option {
display: block;
border-bottom: 1px solid #eee;
padding: 1em;
text-decoration: none;
color: #c2e2c2;
text-align: center;
}
.columns.is-fullheight {
min-height: calc(100vh - .25rem);
max-height: calc(100vh - .25rem);
height: calc(100vh - .25rem);
display: flex;
flex-direction: row;
justify-content: stretch;
}
.columns.is-fullheight .column {
overflow-y: auto;
}
.menu-label {
text-align: center;
}
</style>
</head>
<body>
<!--Import geocoder styles and script-->
<script
src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.5.1/mapbox-gl-geocoder.min.js"></script>
<link rel="stylesheet"
href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.5.1/mapbox-gl-geocoder.css"
type="text/css" />
<!-- Promise polyfill script required to use Mapbox GL Geocoder in IE 11 -->
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js"></script>
<div class='columns is-fullheight is-gapless'>
<div class='column is-2 is-sidebar-menu is-hidden-mobile'>
<div class='sidebar'>
<!--Create a sidebar for store listing-->
<div class='menu-label'>
<h1>MacDonald's locations</h1>
</div>
<div id='listings' class='listings'></div>
</div>
</div>
<!-- Create a container for the map -->
<div id='map' class="map column"></div>
</div>
<script>
// Add your Mapbox access token
mapboxgl.accessToken = 'pk.eyJ1IjoiY2FwdG1vbW8iLCJhIjoiY2thMnBtZTBhMGNteTNucG53Y3g2Y3gyNyJ9.Z4_j43zWekpkn2lX9gmoxQ';
// Basic map instance (zoomed to Austin, TX)
const map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/dark-v10?optimize=true",
center: [103.8163, 1.3426],
zoom: 13
});
const geocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
countries: 'sg',
mapboxgl: mapboxgl
});
map.addControl(geocoder, "top-right");
map.addControl(new toggleControl());
</script>
<script>
// Set up an object to track app state and data
const isoAppData = {
params: {
urlBase: "https://api.mapbox.com/isochrone/v1/mapbox/",
profile: "walking/",
minutes: 10,
category: "cafe"
},
origins: {
a: [103.8163, 1.3426]
},
isos: {
a: {}
},
features: {
a: {}
}
};
// Get a single isochrone for a given position and return the GeoJSON
const getIso = function (position) {
// Build the URL for the isochrone API
const isoUrl = isoAppData.params.urlBase + isoAppData.params.profile + position.join(",") + "?contours_minutes=" +
isoAppData.params.minutes + "&polygons=true&access_token=" + mapboxgl.accessToken;
// Return the GeoJSON
return fetch(isoUrl).then(res => res.json());
};
//update draggable iso;
const updateDraggableIso = function (position) {
getIso(position)
.then(result => {
isoAppData.isos.a = result;
map.getSource('draggable').setData(isoAppData.isos.a);
})
}
// Update the map sources so the isochrones draw on the map
const setIsos = function (isos, store) {
map.addSource(store, {
type: "geojson",
data: {
type: "FeatureCollection",
features: [
]
}
});
map.addLayer({
"id": "isoLayer" + store,
"type": "fill",
"source": store,
"layout": {},
"paint": {
"fill-color": "yellow",
"fill-opacity": 0.2
}
}, "poi-label");
// Update the map
map.getSource(store).setData(isos);
//geoJsonArray.features.push({ geo : isos, name: store.name })
};
const updateIsos = function (isos, store) {
map.getSource(store).setData(isos);
//geoJsonArray.features.push({ geo: isos, name: store.name });
}
// Get the isochrone data from the API, then update the map
const getSetIsos = function (store) {
// Once the isochrones are received, update the map
let point = [store.long, store.lat]
getIso(point).then(values => {
setIsos(values, store);
});
};
// Get the isochrone data from the API, then update the map
const getUpdateIsos = function (store) {
// Once the isochrones are received, update the map
let point = [store.long, store.lat]
getIso(point).then(values => {
updateIsos(values, store.name);
});
};
// Get isochrone data from saved Javascript to
// to save on API calls then update the map
const addSavedCronuts = function (url) {
fetchJson(url)
.then(result => {
result.features.forEach(element => {
updateIsos(element.geo, element.name);
})
})
}
//iterate through json list and call update iso function
const addDynamicCronuts = function () {
fetchJson(macJson)
.then(result => {
result.forEach(element => {
getUpdateIsos(element);
})
});
}
//initial call to set up source and layers
const addCronuts = function (stores) {
stores.forEach(element => {
//console.log(element.geo, element.name);
setIsos(element.geo, element.name);
//getSetIsos(element);
});
}
const addListing = function buildLocationList(jsonData, geojsonData) {
jsonData.forEach(function (store, i) {
/**
* Create a shortcut for `store.properties`,
* which will be used several times below.
**/
var prop = store;
/* Add a new listing section to the sidebar. */
var listings = document.getElementById('listings');
var listing = listings.appendChild(document.createElement('div'));
/* Assign a unique `id` to the listing. */
listing.id = "listing-" + prop.id;
/* Assign the `item` class to each listing for styling. */
listing.className = 'item';
/* Add the link to the individual listing created above. */
var link = listing.appendChild(document.createElement('a'));
link.href = '#';
link.className = 'listingTitle';
link.id = "link-" + prop.id;
link.innerHTML = prop.address;
//add data
link.setAttribute("data-name", `${prop.name}`);
/* Add details to the individual listing. */
var details = listing.appendChild(document.createElement('div'));
details.innerHTML = prop.city;
if (prop.phone) {
details.innerHTML += ' · ' + `${prop.phone ? prop.phone : 'N/A'}`;
}
link.addEventListener('click', function (e) {
for (let i = 0; i < geojsonData.features.length; i++) {
if (this.dataset.name == geojsonData.features[i].properties.name) {
let clickedListing = geojsonData.features[i];
console.log(clickedListing);
flyToStore(clickedListing);
createPopUp(clickedListing);
}
}
var activeItem = document.getElementsByClassName('active');
if (activeItem[0]) {
activeItem[0].classList.remove('active');
}
this.parentNode.classList.add('active');
});
});
}
function flyToStore(currentFeature) {
map.flyTo({
center: currentFeature.geometry.coordinates,
zoom: 15
});
}
function createPopUp(currentFeature) {
var popUps = document.getElementsByClassName('mapboxgl-popup');
/** Check if there is already a popup on the map and if so, remove it */
if (popUps[0]) popUps[0].remove();
var popup = new mapboxgl.Popup({ closeOnClick: false })
.setLngLat(currentFeature.geometry.coordinates)
.setHTML(`<h3>${currentFeature.properties.name}</h3>` +
'<h4>' + currentFeature.properties.address + '</h4>')
.addTo(map);
}
const macJson = 'https://raw.githubusercontent.com/captmomo/macdonalds-isochrone-map/master/macdonalds.json';
const macGeoJson = 'https://gist.githubusercontent.com/captmomo/b19136360712e691c0898c4b34842965/raw/d5e420345edd4fea8555856ca1977be9e5765bf7/mcdonalds.geojson';
const macIso = 'https://raw.githubusercontent.com/captmomo/macdonalds-isochrone-map/master/mcdisochrone.json';
const macIso20 = 'https://raw.githubusercontent.com/captmomo/macdonalds-isochrone-map/master/mcdisochrone20.json'
const macIso30 = 'https://raw.githubusercontent.com/captmomo/macdonalds-isochrone-map/master/mcdisochrone30.json'
//set up for draggables
// turf.featureCollection([]); <<- creates empty feature collection
// turf.featureCollection([turf.point(warehouseLocation)]); <<- initialize feature collection with single point
const setUpDraggables = function () {
map.addSource("draggable", {
type: "geojson",
data: {
type: "FeatureCollection",
features: [
]
}
});
map.addLayer({
"id": "draggable",
"type": "fill",
"source": "draggable",
"layout": {},
"paint": {
"fill-color": "lightblue",
"fill-opacity": 0.3
}
}, "poi-label");
updateDraggableIso(isoAppData.origins.a);
};
const originA = new mapboxgl.Marker({
draggable: true
})
.setLngLat(isoAppData.origins.a)
.addTo(map);
const setUpDraggableMarker = function () {
function onDragEndA() {
const lngLat = originA.getLngLat();
isoAppData.origins.a = [lngLat.lng, lngLat.lat];
updateDraggableIso(isoAppData.origins.a);
highlightNearest(isoAppData.origins.a)
}
highlightNearest(isoAppData.origins.a)
originA.on("dragend", onDragEndA);
}
//adding markers
const addMarkers = function (jsonData, parsedGeo) {
parsedGeo.features.forEach(function (store, i) {
let geoProp = store.properties;
for (let i = 0; i < parsedGeo.features.length; i++) {
if (geoProp.name == jsonData[i].name) {
geoProp.address = jsonData[i].address;
geoProp.id = jsonData[i].id;
//alert(clickedListing);
}
};
});
map.addSource("stores", { type: "geojson", data: parsedGeo });
map.addLayer({
id: "stores",
type: "symbol",
source: "stores",
layout:{
'icon-image':'fast-food-15'
}
});
map.on("click", "stores", function (e) {
let clickedPoint = e.features[0];
flyToStore(clickedPoint);
createPopUp(clickedPoint);
let activeListing = document.getElementsByClassName('active');
if (activeListing[0]) {
activeListing.classList.remove('active');
}
console.log(clickedPoint.properties);
let listing = document.getElementById('listing-' + clickedPoint.properties.id);;
listing.classList.add('active');
});
}
const geoJsonArray = { features: [] };
const setUpNearest = function () {
map.addSource('nearest-macs', {
type: 'geojson',
data: {
type: 'FeatureCollection',
features: [
]
}
})
}
const highlightNearest = function (origins) {
//create a feature using passed in point
var point = turf.point([origins[0], origins[1]]);
console.log(point);
//get all rendered features from stores
fetchJson(macGeoJson)
.then(result => {
let nearestMacs = turf.nearestPoint(point, result);
// If a nearest library is found
if (nearestMacs !== null) {
// Update the 'nearest-library' data source to include
// the nearest library
map.getSource('nearest-macs').setData({
type: 'FeatureCollection',
features: [
nearestMacs
]
});
// Create a new circle layer from the 'nearest-library' data source
map.addLayer({
id: 'nearest-macs',
type: 'circle',
source: 'nearest-macs',
paint: {
'circle-radius': 12,
'circle-color': '#ff0003'
}
}, 'stores');
}
})
//get nearest
}
const fetchJson = function getJson(url) {
return fetch(url)
.then(res => res.json());
};
const getListingData = function () {
let plain = fetchJson(macJson);
let geoInfo = fetchJson(macGeoJson);
Promise.all([plain, geoInfo]).then(values => {
addListing(values[0], values[1]);
addMarkers(values[0], values[1]);
});
};
const toggleElement = function toggleActiveElement(element, className) {
var activeItem = document.getElementsByClassName(className);
if (activeItem[0]) {
activeItem[0].classList.remove(className);
}
element.classList.add(className);
}
map.on('load', function () {
// When the map loads, add the source and layer
fetchJson(macIso)
.then(result => {
addCronuts(result.features);
//addMarkers();
});
//sets up store listing
getListingData();
//sets up nearest
setUpNearest();
//set up draggables
setUpDraggables();
setUpDraggableMarker();
//set up draggable to respond to geocoder search
geocoder.on("result", ev => {
const resultLon = ev.result.geometry.coordinates[0];
const resultLat = ev.result.geometry.coordinates[1];
isoAppData.origins.a = [resultLon, resultLat];
// eslint-disable-next-line no-use-before-define
originA.setLngLat(isoAppData.origins.a);
// eslint-disable-next-line no-use-before-define
updateDraggableIso(isoAppData.origins.a);
highlightNearest(isoAppData.origins.a);
});
//set up custom control
let toggleOptions = document.getElementsByClassName("toggle-option");
for (let element of toggleOptions) {
element.addEventListener('click', function (e) {
let mins = element.dataset.value ? parseInt(element.dataset.value) : 10;
isoAppData.params.minutes = mins;
switch (mins) {
case 10:
addSavedCronuts(macIso);
break;
case 20:
addSavedCronuts(macIso20);
break;
case 30:
addSavedCronuts(macIso30);
break;
default:
console.log("uh oh");
}
toggleElement(e.target, 'selected');
updateDraggableIso(isoAppData.origins.a)
});
};
});
</script>
</body>
</html>