generated from EsriDevEvents/ds-2023-repo-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ol-nav-app.html
467 lines (394 loc) · 15.5 KB
/
ol-nav-app.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
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
<title>OpenLayers: Navigation app</title>
<style>
html, body {
height:100%;
max-height: 100%;
}
html,
body,
#map {
padding: 0;
margin: 0;
width: 100%;
font-family: Arial, Helvetica, Verdana sans-serif;
font-size: 20px;
color: #323232;
line-height: 1.5;
}
#map {
height: calc(100vh - 55px);
z-index:0;
}
input {
font-size:20px;
margin:5px 0px;
padding:5px 0px;
}
#ui-container {
position: absolute;
width: 30%;
max-height:100%;
left: 20px;
top: 75px;
}
#driving-directions {
background: white;
padding: 10px;
border-radius: 5px;
}
h4 {
margin:12px 0px 4px 0px;
}
#directions {
overflow-x: auto;
max-height:52vh;
}
#summary {
background: white;
padding: 10px;
display:none;
border-radius: 5px 0px 0px 5px;
max-height:100%;
height:100%;
}
.geocode-input {
border-radius: 4px;
}
.autocomplete {
/*the container must be positioned relative:*/
position: relative;
display: inline-block;
}
input[type=text] {
background-color: #f1f1f1;
width: 100%;
}
input[type=submit] {
background-color: DodgerBlue;
color: #fff;
}
.autocomplete-items {
position: absolute;
border: 1px solid #d4d4d4;
border-bottom: none;
border-top: none;
z-index: 99;
/*position the autocomplete items to be the same width as the container:*/
top: 100%;
left: 0;
right: 0;
}
.autocomplete-items div {
padding: 10px;
cursor: pointer;
background-color: #fff;
border-bottom: 1px solid #d4d4d4;
}
.autocomplete-items div:hover {
/*when hovering an item:*/
background-color: #e9e9e9;
}
.autocomplete-active {
/*when navigating through the items using the arrow keys:*/
background-color: DodgerBlue !important;
color: #ffffff;
}
.header {
display:flex;
top:0px;
background:#212aea;
width:100%;
height:55px;
z-index:1;
font-size:20px;
color:#f8f8f8;
}
.title {
align-self: flex-start;
flex: 1 1;
margin:15px;
}
</style>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.15.1/css/ol.css" type="text/css" />
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.15.1/build/ol.js"></script>
<script src="https://cdn.jsdelivr.net/npm/ol-mapbox-style@6.1.4/dist/olms.js" type="text/javascript"></script>
<script src="https://unpkg.com/@esri/arcgis-rest-request@4.0.0/dist/bundled/request.umd.js"></script>
<script src="https://unpkg.com/@esri/arcgis-rest-routing@4.0.0/dist/bundled/routing.umd.js"></script>
<script src="https://unpkg.com/@esri/arcgis-rest-geocoding@4.0.0/dist/bundled/geocoding.umd.js"></script>
<script src="https://unpkg.com/ol-popup@4.0.0"></script>
<link rel="stylesheet" href="https://unpkg.com/ol-popup@4.0.0/src/ol-popup.css" />
</head>
<body>
<div class="header">
<div class="title">Navigation app: OpenLayers with the ArcGIS Routing Service & Geocoding Service</div>
</div>
<div id="map"></div>
<div id="ui-container">
<div id="driving-directions">
<input id="start" class="geocode-input" type="text" placeholder="Choose starting point" size="50" />
<input id="end" class="geocode-input" type="text" placeholder="Choose destination" size="50" />
<div id="summary">
<div id="drive-time"></div>
<h4>Driving Directions</h4>
<div id="directions"></div>
</div>
</div>
</div>
<script>
const apiKey = "YOUR_API_KEY";
const authentication = arcgisRest.ApiKeyManager.fromKey(apiKey);
const map = new ol.Map({
target: "map",
controls:[]
});
const view = new ol.View({
center: ol.proj.fromLonLat([-118.48702, 34.03618]), // Los Angeles
zoom: 13
});
map.setView(view);
let startLayer, endLayer, routeLayer;
function addCircleLayers() {
startLayer = new ol.layer.Vector({
style: new ol.style.Style({
image: new ol.style.Circle({
radius: 6,
fill: new ol.style.Fill({ color: "white" }),
stroke: new ol.style.Stroke({ color: "black", width: 2 })
})
})
});
map.addLayer(startLayer);
endLayer = new ol.layer.Vector({
style: new ol.style.Style({
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({ color: "black" }),
stroke: new ol.style.Stroke({ color: "white", width: 2 })
})
})
});
map.addLayer(endLayer);
}
let startCoords, endCoords;
function resetRoute() {
// clear endCoords and route if they were already set
if (endCoords) {
endCoords = null;
endLayer.getSource().clear();
routeLayer.getSource().clear();
//document.getElementById("directions").innerHTML = "";
//document.getElementById("directions").style.display = "none";
}
}
const geojson = new ol.format.GeoJSON({
defaultDataProjection: "EPSG:4326",
featureProjection: "EPSG:3857"
});
async function findAddress(query) {
const center = ol.proj.transform(map.getView().getCenter(), "EPSG:3857", "EPSG:4326");
let response = await arcgisRest.geocode({
singleLine: query,
authentication,
params: {
outFields: "*",
location: center.join(",")
}
})
return response.candidates[0]
}
async function findCandidates(query,inp) {
const center = ol.proj.transform(map.getView().getCenter(), "EPSG:3857", "EPSG:4326");
let response = await arcgisRest.suggest(query,{
authentication,
params:{
location: center.join(",")
}
})
return response.suggestions;
}
function autocomplete(inp) {
/*the autocomplete function takes two arguments,
the text field element and an array of possible autocompleted values:*/
let currentFocus;
/*execute a function when someone writes in the text field:*/
inp.addEventListener("input", function(e) {
resetRoute();
document.getElementById("summary").style.display = "none";
if (inp.id == "start") {
startCoords = null;
startLayer.source = null;
}
else {
endCoords = null;
endLayer.source = null;
}
let a, b, i, val = this.value;
if (!val) { return false;}
currentFocus = -1;
//if (val.length < 4) { return false;}
findCandidates(val,inp).then((candidates) => {
console.log(candidates)
closeAllLists();
// create autocomplete list
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
this.parentNode.appendChild(a);
// populate list with contents
for (i = 0; i < candidates.length; i++) {
const address = candidates[i].text;
b = document.createElement("DIV");
b.innerHTML = `<strong>${address.substr(0, val.length)}</strong>`;
b.innerHTML += address.substr(val.length);
b.innerHTML += `<input type='hidden' value='${address}' id=${i}>`;
// populate field when autocomplete result selected
b.addEventListener("click", function(e) {
let chosenAddress = this.getElementsByTagName("input")[0].value;
inp.value = chosenAddress;
findAddress(chosenAddress).then(spot => {
inp.value = spot.attributes.LongLabel;
if (inp.id == "start") {
startCoords = [spot.location.x, spot.location.y]
startLayer.setSource(
new ol.source.Vector({
features: geojson.readFeatures({
type: "Point",
coordinates: startCoords
})
})
);
}
else {
endCoords = [spot.location.x, spot.location.y]
endLayer.setSource(
new ol.source.Vector({
features: geojson.readFeatures({
type: "Point",
coordinates: endCoords
})
})
);
}
if (startCoords && endCoords) {
updateRoute()
}
closeAllLists();
})
});
a.appendChild(b);
}
})
})
/*execute a function presses a key on the keyboard:*/
inp.addEventListener("keydown", function(e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
/*If the arrow DOWN key is pressed,
increase the currentFocus variable:*/
currentFocus++;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 38) { //up
/*If the arrow UP key is pressed,
decrease the currentFocus variable:*/
currentFocus--;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 13) {
/*If the ENTER key is pressed, prevent the form from being submitted,*/
e.preventDefault();
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
/*a function to classify an item as "active":*/
if (!x) return false;
/*start by removing the "active" class on all items:*/
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
/*add class "autocomplete-active":*/
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
/*a function to remove the "active" class from all autocomplete items:*/
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
/*close all autocomplete lists in the document,
except the one passed as an argument:*/
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
/*execute a function when someone clicks in the document:*/
document.addEventListener("click", function (e) {
closeAllLists(e.target);
});
}
function addRouteLayer() {
routeLayer = new ol.layer.Vector({
style: new ol.style.Style({
stroke: new ol.style.Stroke({ color: "hsl(205, 100%, 50%)", width: 4, opacity: 0.6 })
})
});
map.addLayer(routeLayer);
}
function updateRoute() {
arcgisRest.solveRoute({
stops: [startCoords, endCoords],
authentication
}).then((response) => {
const source = new ol.source.Vector({
features: geojson.readFeatures(response.routes.geoJson)
})
routeLayer.setSource(source);
// ...
// set layer extent
const extent = source.getExtent();
map.getView().fit(extent,{size: map.getSize()});
map.getView().setZoom(map.getView().getZoom() - 0.5)
document.getElementById("summary").style.display = "block";
let timeMinutes = response.routes.features[0].attributes.Total_TravelTime;
let timeHours = 0;
while (timeMinutes >= 60) {
timeMinutes -= 60;
timeHours += 1;
}
timeMinutes = Math.floor(timeMinutes);
let timeString = timeMinutes + " min";
if (timeHours > 0) {timeString = timeHours + " hr " + timeString}
document.getElementById("drive-time").innerHTML = timeString;
const directionsHTML = response.directions[0].features.map((f) => f.attributes.text).join("<br/>");
document.getElementById("directions").innerHTML = directionsHTML;
//document.getElementById("directions").style.display = "block";
//
}).catch((error) => {
alert("There was a problem using the routing service. See the console for details.");
console.error(error);
});
}
autocomplete(document.getElementById("start"))
autocomplete(document.getElementById("end"))
const basemapId = "ArcGIS:Navigation";
const basemapURL = "https://basemaps-api.arcgis.com/arcgis/rest/services/styles/" + basemapId + "?type=style&token=" + apiKey;
olms(map, basemapURL).then(function (map) {
addCircleLayers();
addRouteLayer();
});
</script>
</body>
</html>