Repository navigation
Expand file tree
/
Copy pathmap.js
More file actions
390 lines (333 loc) · 13.5 KB
/
Copy pathmap.js
File metadata and controls
390 lines (333 loc) · 13.5 KB
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
"use strict";
const DATA_PATH = "ToPermits.geojson";
const DAY_MS = 24 * 60 * 60 * 1000;
const STATUS_COLOURS = {
active: { fill: "#e8663d", stroke: "#b94929" },
cleared: { fill: "#397dc0", stroke: "#245b91" },
other: { fill: "#858982", stroke: "#5f625d" }
};
const numberFormatter = new Intl.NumberFormat("en-CA");
const displayDateFormatter = new Intl.DateTimeFormat("en-CA", {
year: "numeric",
month: "short",
day: "numeric",
timeZone: "UTC"
});
const elements = {
mapNote: document.querySelector("#map-note"),
permitCount: document.querySelector("#permit-count"),
netUnitCount: document.querySelector("#net-unit-count"),
dwellingUnitCount: document.querySelector("#dwelling-unit-count"),
startDate: document.querySelector("#start-date"),
endDate: document.querySelector("#end-date"),
startRange: document.querySelector("#start-range"),
endRange: document.querySelector("#end-range"),
selectedStart: document.querySelector("#selected-start"),
selectedEnd: document.querySelector("#selected-end"),
minimumDate: document.querySelector("#minimum-date"),
maximumDate: document.querySelector("#maximum-date"),
dataDateRange: document.querySelector("#data-date-range"),
rangeSelection: document.querySelector("#range-selection"),
histogram: document.querySelector("#date-histogram"),
resetDates: document.querySelector("#reset-dates")
};
const map = L.map("map", {
zoomControl: false,
preferCanvas: true
});
L.control.zoom({ position: "topleft" }).addTo(map);
L.tileLayer("https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png", {
subdomains: "abcd",
maxZoom: 20,
attribution: "© OpenStreetMap contributors © CARTO"
}).addTo(map);
// A feature group exposes getBounds(), allowing the initial view to come directly from
// the permit markers rather than from a hard-coded city centre.
const markerLayer = L.featureGroup().addTo(map);
let permits = [];
let datasetStart;
let datasetEnd;
let totalDays = 0;
let histogramBins = [];
let resizeFrame;
// Leaflet records its container size when it initializes. Keep that measurement current
// if the flex/grid layout changes later (for example, at the mobile breakpoint).
const mapPane = document.querySelector(".map-pane");
const mapResizeObserver = new ResizeObserver(() => {
cancelAnimationFrame(resizeFrame);
resizeFrame = requestAnimationFrame(() => map.invalidateSize({ pan: false }));
});
mapResizeObserver.observe(mapPane);
function afterPageLayout(callback) {
let sizeWasInvalidated = false;
let callbackRan = false;
const runCallback = () => {
if (callbackRan) return;
callbackRan = true;
callback();
};
const invalidateAfterLayout = () => {
if (sizeWasInvalidated) return;
sizeWasInvalidated = true;
map.invalidateSize({ pan: false });
// Fit on the following paint. The timer also covers browsers that throttle frames.
requestAnimationFrame(runCallback);
window.setTimeout(runCallback, 32);
};
// map.js is loaded after the stylesheets and markup. Two frames allow the final
// flex/grid dimensions to settle without waiting on unrelated CDN load events.
requestAnimationFrame(() => requestAnimationFrame(invalidateAfterLayout));
window.setTimeout(invalidateAfterLayout, 80);
}
function parseDate(dateString) {
// Adding midnight UTC avoids date shifts when the page runs in another time zone.
return new Date(`${dateString}T00:00:00Z`);
}
function dateToDay(date) {
return Math.round((date.getTime() - datasetStart.getTime()) / DAY_MS);
}
function dayToDate(day) {
return new Date(datasetStart.getTime() + Number(day) * DAY_MS);
}
function toISODate(date) {
return date.toISOString().slice(0, 10);
}
function formatDate(date) {
return displayDateFormatter.format(date);
}
function safeNumber(value) {
const number = Number(value);
return Number.isFinite(number) ? number : 0;
}
// Point size uses square-root scaling. Circle area, rather than radius, therefore grows
// roughly in proportion to net units, while the 4–10 px bounds keep 1-unit points visible.
function radiusForUnits(value) {
const units = Math.max(1, safeNumber(value));
const dataMaximum = 6;
const minimumRadius = 4;
const maximumRadius = 10;
const scaled = (Math.sqrt(units) - 1) / (Math.sqrt(dataMaximum) - 1);
return minimumRadius + scaled * (maximumRadius - minimumRadius);
}
// Status controls colour; the neutral fallback makes unexpected future values legible.
function styleForFeature(properties) {
const palette = STATUS_COLOURS[properties.status] || STATUS_COLOURS.other;
return {
radius: radiusForUnits(properties.net_units_created),
fillColor: palette.fill,
color: palette.stroke,
weight: 1,
opacity: 0.9,
fillOpacity: 0.7
};
}
function makePopup(properties) {
const wrapper = document.createElement("div");
const title = document.createElement("h3");
title.className = "popup-address";
title.textContent = properties.full_address || "Address unavailable";
wrapper.appendChild(title);
const rows = [
["Permit", properties.permit_num],
["Status", properties.status],
["Applied", properties.application_date],
["Net units", properties.net_units_created]
];
rows.forEach(([label, value]) => {
const row = document.createElement("div");
const key = document.createElement("span");
const displayedValue = document.createElement("span");
row.className = "popup-row";
key.className = "popup-key";
displayedValue.className = "popup-value";
key.textContent = label;
displayedValue.textContent = value ?? "—";
row.append(key, displayedValue);
wrapper.appendChild(row);
});
return wrapper;
}
// Recalculate the three cards from only the permits inside the chosen date range.
function updateSummary(filteredPermits) {
const totals = filteredPermits.reduce(
(summary, permit) => {
summary.netUnits += safeNumber(permit.properties.net_units_created);
summary.dwellingUnits += safeNumber(permit.properties.dwelling_units_created);
return summary;
},
{ netUnits: 0, dwellingUnits: 0 }
);
elements.permitCount.textContent = numberFormatter.format(filteredPermits.length);
elements.netUnitCount.textContent = numberFormatter.format(totals.netUnits);
elements.dwellingUnitCount.textContent = numberFormatter.format(totals.dwellingUnits);
}
function updateHistogram(startDate, endDate) {
histogramBins.forEach((bin) => {
const inRange = bin.end >= startDate && bin.start <= endDate;
bin.element.classList.toggle("outside-range", !inRange);
});
}
function updateControlDisplay(startDay, endDay) {
const startDate = dayToDate(startDay);
const endDate = dayToDate(endDay);
const startPercent = totalDays ? (startDay / totalDays) * 100 : 0;
const endPercent = totalDays ? (endDay / totalDays) * 100 : 100;
elements.startDate.value = toISODate(startDate);
elements.endDate.value = toISODate(endDate);
elements.selectedStart.textContent = formatDate(startDate);
elements.selectedEnd.textContent = formatDate(endDate);
elements.rangeSelection.style.left = `${startPercent}%`;
elements.rangeSelection.style.width = `${endPercent - startPercent}%`;
updateHistogram(startDate, endDate);
}
// Date filtering removes out-of-range Leaflet layers, so hidden markers cannot open popups.
// The same filtered array is then used for the summary cards, keeping map and totals aligned.
function applyDateFilter() {
const startDay = Number(elements.startRange.value);
const endDay = Number(elements.endRange.value);
const startTime = dayToDate(startDay).getTime();
const endTime = dayToDate(endDay).getTime();
const visiblePermits = [];
markerLayer.clearLayers();
permits.forEach((permit) => {
if (permit.applicationTime >= startTime && permit.applicationTime <= endTime) {
markerLayer.addLayer(permit.marker);
visiblePermits.push(permit);
}
});
updateControlDisplay(startDay, endDay);
updateSummary(visiblePermits);
}
function handleRangeInput(changedControl) {
let startDay = Number(elements.startRange.value);
let endDay = Number(elements.endRange.value);
if (startDay > endDay) {
if (changedControl === elements.startRange) {
endDay = startDay;
elements.endRange.value = endDay;
} else {
startDay = endDay;
elements.startRange.value = startDay;
}
}
elements.startRange.style.zIndex = startDay >= totalDays - 2 ? "4" : "3";
elements.endRange.style.zIndex = "3";
applyDateFilter();
}
function handleDateInput(changedInput) {
if (!changedInput.value) return;
let startDate = parseDate(elements.startDate.value);
let endDate = parseDate(elements.endDate.value);
if (startDate > endDate) {
if (changedInput === elements.startDate) endDate = startDate;
else startDate = endDate;
}
elements.startRange.value = dateToDay(startDate);
elements.endRange.value = dateToDay(endDate);
handleRangeInput(changedInput === elements.startDate ? elements.startRange : elements.endRange);
}
function buildHistogram() {
const monthlyCounts = new Map();
permits.forEach((permit) => {
const date = new Date(permit.applicationTime);
const key = `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}`;
monthlyCounts.set(key, (monthlyCounts.get(key) || 0) + 1);
});
const maximumCount = Math.max(...monthlyCounts.values());
elements.histogram.replaceChildren();
histogramBins = [];
// The source rows are not date-sorted, so sort the YYYY-MM keys before drawing bars.
[...monthlyCounts.entries()].sort(([a], [b]) => a.localeCompare(b)).forEach(([key, count]) => {
const [year, month] = key.split("-").map(Number);
const element = document.createElement("span");
const start = new Date(Date.UTC(year, month - 1, 1));
const end = new Date(Date.UTC(year, month, 0));
element.className = "histogram-bar";
element.style.height = `${Math.max(8, (count / maximumCount) * 100)}%`;
element.title = `${key}: ${numberFormatter.format(count)} permits`;
elements.histogram.appendChild(element);
histogramBins.push({ start, end, element });
});
}
function configureDateControls() {
totalDays = dateToDay(datasetEnd);
const minimum = toISODate(datasetStart);
const maximum = toISODate(datasetEnd);
[elements.startRange, elements.endRange].forEach((input) => {
input.min = 0;
input.max = totalDays;
input.step = 1;
});
elements.startRange.value = 0;
elements.endRange.value = totalDays;
[elements.startDate, elements.endDate].forEach((input) => {
input.min = minimum;
input.max = maximum;
});
elements.minimumDate.textContent = datasetStart.getUTCFullYear();
elements.maximumDate.textContent = datasetEnd.getUTCFullYear();
elements.dataDateRange.textContent = `${formatDate(datasetStart)} to ${formatDate(datasetEnd)}`;
elements.startRange.addEventListener("input", () => handleRangeInput(elements.startRange));
elements.endRange.addEventListener("input", () => handleRangeInput(elements.endRange));
elements.startDate.addEventListener("input", () => handleDateInput(elements.startDate));
elements.endDate.addEventListener("input", () => handleDateInput(elements.endDate));
elements.resetDates.addEventListener("click", () => {
elements.startRange.value = 0;
elements.endRange.value = totalDays;
applyDateFilter();
});
}
// Load the local GeoJSON file. This requires an HTTP server rather than opening index.html
// directly, because browsers generally block fetch requests from file:// pages.
fetch(DATA_PATH)
.then((response) => {
if (!response.ok) throw new Error(`The data request returned ${response.status}.`);
return response.json();
})
.then((geojson) => {
if (geojson.type !== "FeatureCollection" || !Array.isArray(geojson.features)) {
throw new Error("ToPermits.geojson is not a GeoJSON FeatureCollection.");
}
permits = geojson.features.map((feature) => {
if (feature.geometry?.type !== "Point") {
throw new Error("This map expects every feature geometry to be a Point.");
}
// GeoJSON Point coordinates are stored as [longitude, latitude]. Leaflet expects
// [latitude, longitude], so read and reverse the two values explicitly here.
const [longitude, latitude] = feature.geometry.coordinates;
const latLng = [latitude, longitude];
const properties = feature.properties || {};
// Each permit is a Leaflet circle marker styled from its status and net unit count.
const marker = L.circleMarker(latLng, styleForFeature(properties));
marker.bindPopup(() => makePopup(properties));
return {
properties,
applicationTime: parseDate(properties.application_date).getTime(),
marker
};
});
const applicationTimes = permits.map((permit) => permit.applicationTime);
datasetStart = new Date(Math.min(...applicationTimes));
datasetEnd = new Date(Math.max(...applicationTimes));
configureDateControls();
buildHistogram();
applyDateFilter();
// The first filter pass populates the feature group with every permit. Only fit after
// the complete page layout and Leaflet's refreshed container measurement are painted.
afterPageLayout(() => {
const permitBounds = markerLayer.getBounds();
if (permitBounds.isValid()) {
map.fitBounds(permitBounds, {
padding: [28, 28],
maxZoom: 13,
animate: false
});
}
elements.mapNote.classList.add("is-hidden");
});
})
.catch((error) => {
console.error(error);
elements.mapNote.textContent = "Could not load ToPermits.geojson. Run this folder from a local web server and refresh the page.";
elements.mapNote.classList.add("is-error");
});