-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
368 lines (281 loc) · 12.8 KB
/
index.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
<!DOCTYPE html>
<html lang="en" class="has-navbar-fixed-top">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>GeoLocation Experiment</title>
<link rel="stylesheet" href="bulma.min.css">
<link rel="stylesheet" href="css/style.css">
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin="" />
</head>
<body>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"
integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
crossorigin=""></script>
<nav class="navbar is-fixed-top">
<div class="navbar-brand">
<a class="navbar-item" href="#">
<img src="./favicon.ico">
</a>
<a role="button" class="navbar-burger" aria-label="menu" aria-expanded="false"
data-target="navbarBasicExample">
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
</a>
</div>
<div id="navbarBasicExample" class="navbar-menu">
<div class="navbar-start">
<a class="navbar-item" href="./data-viewer.html">Mapa</a>
</div>
<div class="navbar-end">
</div>
</div>
</nav>
<section class="hero is-info is-medium">
<div class="hero-body">
<div class="container has-text-centered-mobile">
<div class="level">
<div class="block">
<h1 class="title is-1">Mapping Data Demo</h1>
<h1 class="subtitle is-3">Press button to begin</h1>
</div>
<div class="level-right ">
<a href="#" id="start" onclick="doIt()" class="button m-3 is-large is-warning">Start
Geo-Location</a>
<a href="#" id="downloadAnchor" onclick="downloadData()"
class="button m-3 is-large is-warning">Download
Data</a>
</div>
</div>
</div>
</div>
</section>
<section class="section has-text-centered">
<div class="container">
<div class="columns ">
<div class="column">
<div class="notification is-primary">
<h2 id="lat" class="title has-text-light">Latitude</h2>
</div>
</div>
<div class="column">
<div class="notification is-info">
<h2 id="long" class="title has-text-light">Longitude</h2>
</div>
</div>
</div>
<div class="columns has-text-weight-semibold">
<div class="column">
<div id="neighbourhood" class="notification">
Your General Location
</div>
</div>
</div>
<div class="columns has-text-weight-semibold">
<div class="column">
<div id="street" class="notification">
More Specifically
</div>
</div>
</div>
<div class="columns has-text-weight-semibold">
<div class="column is-danger">
<div id="distance_total" class="notification is-danger">
Distance will go here
</div>
</div>
</div>
<button onclick="mapToggle()" class='button is-success'>Map Toggle</button>
<div class="data-holder container">
<div class="" id="map"></div>
<div id="location-holder" class="columns not-visible has-text-weight-semibold"></div>
</div>
</div>
</section>
<script>
var lastPos = {
lat: 0,
lon: 0
}
var running
var currentController
var watchId
var dataStore = []
function doIt() {
if (running) {
stopGeo(watchId)
clearText()
running = false
return
}
clearRenderedDataPoints()
dataStore = []
watchId = navigator.geolocation.watchPosition((position) => {
let storeIndex = dataStore.length
let lat = position.coords.latitude
let lon = position.coords.longitude
let accuracy = position.coords.accuracy
let speed = position.coords.speed
if (running) {
if (lat == lastPos.lat && lon == lastPos.lon) return
}
lastPos.lat = lat
lastPos.lon = lon
console.log(`${lat},${lon}`)
let dataPoint = {
lat,
lon,
accuracy,
speed,
date: Date.now(),
distance: !dataStore.length ? 0 : getDistanceFromLatLonInKm(
dataStore[dataStore.length - 1].lat,
dataStore[dataStore.length - 1].lon,
lat,
lon
)
}
document.querySelector('#lat').innerHTML = lat.toString()
document.querySelector('#long').innerHTML = lon.toString()
document.querySelector('#start').innerHTML = 'Stop Geo-Location'
document.querySelector('#start').classList.add('is-danger')
getAddress(lat, lon).then(response => {
if (response != undefined) {
if (response.error) {
document.querySelector('#neighbourhood').innerHTML =
`<div class="notification is-danger" style="transition:.2s ease all!important">⚠ Waiting for signal. Unable to geolocate.</div>`
document.querySelector('#street').innerText = `🚧👷♂️`
} else {
document.querySelector('#neighbourhood').innerText = response.address
.neighbourhood || response.address.suburb || response.address
.city ||
response.address.country
document.querySelector('#street').innerText = response.address.road ||
response.address.state_district || response.address.municipality ||
response.address.region || response.address.state
}
dataPoint.address = [
document.querySelector('#street').innerText,
document.querySelector('#neighbourhood').innerText
]
//update Address lazily
renderAddress(dataPoint, storeIndex)
}
})
dataStore.push(dataPoint)
window.map.polyline.addCoord([dataPoint.lat, dataPoint.lon])
updateHTML(dataPoint, dataStore)
running = true
}, error, {
enableHighAccuracy: true
})
}
function error(err) {
console.warn('ERRO(' + err.code + '): ' + err.message);
}
function stopGeo(geo) {
navigator.geolocation.clearWatch(geo)
currentController.abort()
}
function clearText() {
document.querySelector('#lat').innerHTML = 'Latitude'
document.querySelector('#long').innerHTML = 'Longitude'
document.querySelector('#start').innerHTML = 'Start Geo-Location'
document.querySelector('#start').classList.remove('is-danger')
document.querySelector('#neighbourhood').innerText = 'Your General Location'
document.querySelector('#street').innerText = 'More Specifically'
}
function clearRenderedDataPoints() {
window.map.polyline.clearCoords()
document.querySelector('#location-holder').innerHTML = ''
}
async function getAddress(lat, lon) {
let params = new URLSearchParams({
format: 'json',
lat: lat,
lon: lon,
zoom: 18,
addressdetails: 1
})
let controller = new AbortController();
//SOS BOAS PRÁTICAS !!! 😢
currentController = controller
const response = await fetch('https://nominatim.openstreetmap.org/reverse?' + params, {
signal: controller.signal
}).then(x => x.json()).then(data => data).catch(err => console.log(err))
return response
}
function updateHTML(dataPoint, store) {
let distance_html = document.querySelector('#distance_total')
let locations = document.querySelector('#location-holder')
let total_distance = store.map(x => x.distance).reduce((a, b) => a + b, 0)
distance_html.innerHTML = `<h2>distância total:</h2><p>${total_distance.toFixed(2)} km</p>`
let new_dataPoint = document.createElement('div')
new_dataPoint.className = 'column'
let dataPoint_start = '<div class="notification">'
let body = `
<p>x: ${dataPoint.lat}</p>
<p>y: ${dataPoint.lon}</p>
<p>date: ${new Date(dataPoint.date).toLocaleTimeString()}</p>
<p class="address">address: ${dataPoint.address?.[0]},${dataPoint.address?.[1]}</p>
<p>distance: ${dataPoint.distance.toFixed(2)} km</p>
`
let dataPoint_end = '</div>'
new_dataPoint.innerHTML = dataPoint_start + body + dataPoint_end
locations.appendChild(new_dataPoint)
}
function renderAddress(dataPoint, storeIndex) {
console.log(storeIndex)
let renderedPoint = document.querySelectorAll('#location-holder>.column>.notification>p.address')[
storeIndex]
renderedPoint.innerText = `address: ${dataPoint.address?.[0]},${dataPoint.address?.[1]}`
}
function downloadData() {
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(dataStore));
var dlAnchorElem = document.getElementById('downloadAnchor');
dlAnchorElem.setAttribute("href", dataStr);
dlAnchorElem.setAttribute("download",
`data_coords_${new Date().toDateString().replaceAll(' ','_')}.json`);
dlAnchorElem.click();
}
</script>
<script src="distance.js">
//for posterior inclusion of distance-tracking between users
</script>
<script>
function mapToggle() {
let elements = document.querySelectorAll('.data-holder>*')
elements.forEach(el => el.classList.toggle('not-visible'))
}
document.addEventListener('DOMContentLoaded', () => {
// Get all "navbar-burger" elements
const $navbarBurgers = Array.prototype.slice.call(document.querySelectorAll('.navbar-burger'), 0);
// Check if there are any navbar burgers
if ($navbarBurgers.length > 0) {
// Add a click event on each of them
$navbarBurgers.forEach(el => {
el.addEventListener('click', () => {
// Get the target from the "data-target" attribute
const target = el.dataset.target;
const $target = document.getElementById(target);
// Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu"
el.classList.toggle('is-active');
$target.classList.toggle('is-active');
});
});
}
});
</script>
<script type="module">
import leaflet from './leaflet-fns.js'
let map = window.map = leaflet.createMap('map')
map.centerMap(0,0)
navigator.geolocation.getCurrentPosition(success => map.centerMap(success.coords.latitude,success.coords.longitude))
</script>
</body>
</html>