-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
347 lines (299 loc) · 11.8 KB
/
index.js
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
/* eslint-disable no-undef */
import data from "./gb.js";
const runMap = () => {
if (!mapboxgl.supported()) {
// eslint-disable-next-line no-console
console.log("Your browser does not support Mapbox GL");
}
mapboxgl.accessToken =
"pk.eyJ1IjoicmF5b3JpYW5mYWMyMyIsImEiOiJjbHNodDBna2ExMmFuMmxvdWI2MTkyN25oIn0.Lg5ggPjT5EUhMMBe7J-0eg";
const { geolocation } = navigator;
if (geolocation) {
geolocation.getCurrentPosition((position) => {
// User coordinates
const { latitude: lat } = position.coords,
{ longitude: lon } = position.coords,
// Crime data container
container = document.querySelector("#text-container"),
// Select elemet
select = document.getElementById("crimes");
const currentMarkers = [];
const map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/streets-v11",
center: [`${lon}`, `${lat}`],
zoom: 13,
scrollZoom: true,
}),
fetchData = async () => {
try {
// Get map data and police api data using promise all to return each result as element in an array
const resultData = await Promise.all([
fetch(
`https://api.mapbox.com/geocoding/v5/mapbox.places/${lon},${lat}.json?&access_token=${mapboxgl.accessToken}`
),
fetch(
`https://data.police.uk/api/crimes-street/all-crime?lat=${lat}&lng=${lon}&date=2023-10`
),
]);
// Return pending map data and police api data as json
const result = await Promise.all(
resultData.map((ele) => ele.json())
);
const [mapData, policeData] = [...result];
// Hide loader notice
const loader = document.querySelector("#loader");
loader.classList.add("fade-out");
// Find crime in area header
const area = document.querySelector("#area-header");
// Deconstrcut map object to get information
const { features } = { ...mapData };
const [dataObj] = [...features];
const { context } = { ...dataObj };
const [postcode, locality, place, district, ,] = [...context];
// Find crime in area header text
area.textContent = `${locality.text}, ${place.text}, ${district.text}, ${postcode.text} `;
// Find selected crime committed by category
select.addEventListener("change", (event) => {
event.preventDefault();
const list = document.getElementsByClassName("crime-panel");
// If elements exists remove them to make space for new elements.
if (list) {
Array.from(list).forEach((element) => element.remove());
}
// If markers exist remove markers from array to make space for new markers
if (currentMarkers !== null) {
for (let i = currentMarkers.length - 1; i >= 0; i -= 1) {
currentMarkers[i].remove();
}
}
// Iterate over police data
for (let i = 0; i < policeData.length; i += 1) {
// If selected value matches police crime data category, create section
// To show details
if (event.target.value === policeData[i].category) {
const panel = document.createElement("SECTION");
panel.setAttribute("class", "crime-panel");
const title = document.createElement("H2");
title.setAttribute("class", "title");
// If any crime data found in crime category
if (policeData[i].outcome_status) {
// Capitalise first letter of crime category
title.textContent =
policeData[i].category.charAt(0).toUpperCase() +
policeData[i].category.slice(1).replace(/-+/gu, " ");
// Date of crime container
const crimeDate = document.createElement("P");
// Date of crime
crimeDate.textContent = new Date(
policeData[i].month
).toDateString();
// Crime location container
const crimeLocation = document.createElement("P");
// Crime location details
crimeLocation.textContent =
policeData[i].location.street.name;
// Crime Outcome container
const crimeOutcome = document.createElement("P");
// Crime outcome details
crimeOutcome.textContent =
policeData[i].outcome_status.category;
// Append elements
panel.appendChild(title);
panel.appendChild(crimeDate);
panel.appendChild(crimeLocation);
panel.appendChild(crimeOutcome);
container.appendChild(panel);
// Set a fixed height to text container and set overflow to scroll to hide overflow
// Large amount of text returned from api - vertical scroll bar added to enable scrolling.
container.style.height = "100vh";
container.style.overflow = "scroll";
// Add markers and pop ups showing crime details
const marker = new mapboxgl.Marker()
.setLngLat([
`${policeData[i].location.longitude}`,
`${policeData[i].location.latitude}`,
])
.setPopup(
new mapboxgl.Popup({ offset: 25 }) // Add Popups
.setHTML(
`<h3>${policeData[i].category.replace(
/-/gu,
" "
)}</h3><p>${policeData[i].location.street.name}</p>`
)
)
.addTo(map);
// Save tmp marker into currentMarkers array
currentMarkers.push(marker);
} else {
// Crime date not found
title.textContent = "No Crime Data Available";
panel.appendChild(title);
container.appendChild(panel);
}
}
}
});
// Add zoom and rotation controls to the map.
map.addControl(new mapboxgl.NavigationControl());
} catch {
throw Error("Promise failed");
}
};
fetchData();
//Select element for choosing city
const citySelect = document.getElementById("cities");
// sort objects alphabetically by city name
const sortedObjects = data.sort((a, b) => a.city.localeCompare(b.city));
// Add city names and coordinates to options element for select element.
sortedObjects.forEach((city) => {
const options = document.createElement("OPTION");
options.setAttribute("value", `${city.lat},${city.lng}`);
options.textContent = `${city.city}`;
citySelect.appendChild(options);
});
// Add evemt listener
citySelect.addEventListener("change", (e) => {
e.preventDefault();
// Retreive lon and lat values as an array
const result = e.target.value.trim().split(",");
// Assign values to variables to use in map object and fetch urls
const lat1 = `${result[0]}`;
const lon1 = `${result[1]}`;
const currentMarkers1 = [];
// New map object
const map1 = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/streets-v11",
center: [`${lon1}`, `${lat1}`],
zoom: 13,
scrollZoom: true,
});
const fetchDataOne = async () => {
try {
// Get map data and police api data using promise all to return each result as element in an array
const resultData1 = await Promise.all([
fetch(
`https://api.mapbox.com/geocoding/v5/mapbox.places/${lon1},${lat1}.json?&access_token=${mapboxgl.accessToken}`
),
fetch(
`https://data.police.uk/api/crimes-street/all-crime?lat=${lat1}&lng=${lon1}&date=2023-10`
),
]);
// Return pending map data and police api data as json
const data1 = await Promise.all(
resultData1.map((ele) => ele.json())
);
const [mapData1, policeData1] = [...data1];
// Hide loader notice
const loader = document.querySelector("#loader");
loader.classList.add("fade-out");
// Find crime in area header
const area = document.querySelector("#area-header");
// Deconstrcut map object to get information
const { features } = { ...mapData1 };
const [dataObj] = [...features];
const { context } = { ...dataObj };
const [postcode, locality, place, district, ,] = [...context];
// Find crime in area header text
area.textContent = `${locality.text}, ${place.text}, ${district.text}, ${postcode.text} `;
// Find selected crime committed by category
select.addEventListener("change", (event) => {
event.preventDefault();
const list = document.getElementsByClassName("crime-panel");
// If elements exists remove them to make space for new elements.
if (list) {
Array.from(list).forEach((element) => element.remove());
}
// If markers exist remove markers from array to make space for new markers
if (currentMarkers1 !== null) {
for (let i = currentMarkers1.length - 1; i >= 0; i -= 1) {
currentMarkers1[i].remove();
}
}
// Iterate over police data
for (let i = 0; i < policeData1.length; i += 1) {
// If selected value matches police crime data category, create section
// To show details
if (event.target.value === policeData1[i].category) {
const panel = document.createElement("SECTION");
panel.setAttribute("class", "crime-panel");
const title = document.createElement("H2");
title.setAttribute("class", "title");
// If any crime data found in crime category
if (policeData1[i].outcome_status) {
// Capitalise first letter of crime category
title.textContent =
policeData1[i].category.charAt(0).toUpperCase() +
policeData1[i].category.slice(1).replace(/-+/gu, " ");
// Date of crime container
const crimeDate = document.createElement("P");
// Date of crime
crimeDate.textContent = new Date(
policeData1[i].month
).toDateString();
// Crime location container
const crimeLocation = document.createElement("P");
// Crime location details
crimeLocation.textContent =
policeData1[i].location.street.name;
// Crime Outcome container
const crimeOutcome = document.createElement("P");
// Crime outcome details
crimeOutcome.textContent =
policeData1[i].outcome_status.category;
// Append elements
panel.appendChild(title);
panel.appendChild(crimeDate);
panel.appendChild(crimeLocation);
panel.appendChild(crimeOutcome);
container.appendChild(panel);
// Set a fixed height to text container and set overflow to scroll to hide overflow
// Large amount of text returned from api - vertical scroll bar added to enable scrolling.
container.style.height = "100vh";
container.style.overflow = "scroll";
// Add markers and pop ups showing crime details
const marker1 = new mapboxgl.Marker()
.setLngLat([
`${policeData1[i].location.longitude}`,
`${policeData1[i].location.latitude}`,
])
.setPopup(
new mapboxgl.Popup({ offset: 25 }) // Add Popups
.setHTML(
`<h3>${policeData1[i].category.replace(
/-/gu,
" "
)}</h3><p>${
policeData1[i].location.street.name
}</p>`
)
)
.addTo(map1);
// Save tmp marker into currentMarkers array
currentMarkers1.push(marker1);
} else {
// Crime date not found
title.textContent = "No Crime Data Available";
panel.appendChild(title);
container.appendChild(panel);
}
}
}
});
// Add zoom and rotation controls to the map.
map1.addControl(new mapboxgl.NavigationControl());
} catch {
throw Error("Promise failed");
}
};
fetchDataOne();
});
});
} else {
// eslint-disable-next-line no-alert
alert("Geolocation is not supported by this browser.");
}
};
runMap();