-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpartitionguessr.html
More file actions
382 lines (323 loc) · 12.1 KB
/
partitionguessr.html
File metadata and controls
382 lines (323 loc) · 12.1 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
<!DOCTYPE html>
<html>
<head>
<title>partitionguessr</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
<style>
/* We want to keep styling as minimal as possible. We want a "raw"
HTML aesthetic */
#map {
width: 100%;
height: 600px;
}
#query-meta {
margin: 0.5rem 0;
font-family: monospace;
}
#query-status {
margin: 0.5rem 0;
}
#char-count.over {
color: #b00020;
font-weight: bold;
}
</style>
</head>
<body>
<h1>partitionguessr</h1>
<p>
In partitionguessr, you create an
<a href="https://www.openstreetmap.org/" target="_blank" rel="noopener noreferrer">OpenStreetMap</a>
<a href="https://overpass-turbo.eu/" target="_blank" rel="noopener noreferrer">Overpass Turbo</a> query.
The returned points are joined into a short path and plotted as your partition line.
With a long enough query you could effectively
<a href="https://en.wikipedia.org/wiki/Gerrymandering" target="_blank" rel="noopener noreferrer">gerrymander</a>
anything, so the query is limited to 256 characters.
</p>
<p>
Aim for a 50% / 50% split of points on each side of your line (0% difference).
If your split is 55% / 45%, your score is 5% difference.
</p>
<p>
Skill grades:
<br>< 5% GOLD
<br>< 10% SILVER
<br>< 15% BRONZE
</p>
<a href="https://honisoit.com/2017/09/food-fault-lines-mapping-class-division-through-food-chains/">https://honisoit.com/2017/09/food-fault-lines-mapping-class-division-through-food-chains/</a>
<br>
<a href="https://x.com/SardineTruther/status/1924725005675593970?t=23LKn0gjnV0FRQWZ7a3f5A&s=19">https://x.com/SardineTruther/status/1924725005675593970?t=23LKn0gjnV0FRQWZ7a3f5A&s=19</a>
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@turf/turf@7.0.0/turf.min.js"></script>
<div>
<form id="overpass-form">
<textarea id="overpass-query" rows="10" cols="60" placeholder="Enter your Overpass Turbo query here...">[out:json][timeout:25];
(
node["name"~"Red Rooster", i]({{bbox}});
way["name"~"Red Rooster", i]({{bbox}});
relation["name"~"Red Rooster", i]({{bbox}});
);
out geom;</textarea>
<div id="query-meta">
Query length: <span id="char-count">0 / 256</span>
</div>
<br>
<button type="submit">Run query</button>
</form>
<div id="query-status"></div>
</div>
<div id="map"></div>
<pre id="geojson-out"></pre>
<script type="module">
const MAX_QUERY_CHARS = 256;
const BBOX = [-34.02136404964111, 150.77362060546875, -33.67978264318627, 151.5220642089844];
const SA2_DATA_URL = 'data/partitionguessr/sa2_nsw_2021_income_joined.geojson';
const osmtogeojson = await import('https://cdn.skypack.dev/osmtogeojson@3.0.0-beta.5?min');
const map = L.map('map').setView([-33.8688, 151.2093], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
}).addTo(map);
const overpassForm = document.getElementById('overpass-form');
const queryInput = document.getElementById('overpass-query');
const statusElement = document.getElementById('query-status');
const geoJSONOutElement = document.getElementById('geojson-out');
const charCountElement = document.getElementById('char-count');
let activeDataLayer = null;
let activePathLayer = null;
let activeSa2Layer = null;
let sa2IncomeFeatures = [];
function updateCharCount() {
const length = queryInput.value.length;
charCountElement.textContent = `${length} / ${MAX_QUERY_CHARS}`;
charCountElement.classList.toggle('over', length > MAX_QUERY_CHARS);
}
function toPointList(featureCollection) {
const points = [];
for (const feature of featureCollection.features) {
if (!feature.geometry) {
continue;
}
if (feature.geometry.type === 'Point') {
points.push(feature.geometry.coordinates);
} else if (feature.geometry.type === 'MultiPoint') {
points.push(...feature.geometry.coordinates);
}
}
return points;
}
function nearestNeighborPath(points) {
if (points.length <= 1) {
return points;
}
const remaining = points.slice(1);
const ordered = [points[0]];
while (remaining.length > 0) {
const last = ordered[ordered.length - 1];
let bestIndex = 0;
let bestDistance = Infinity;
for (let i = 0; i < remaining.length; i++) {
const candidate = remaining[i];
const dx = candidate[0] - last[0];
const dy = candidate[1] - last[1];
const distanceSquared = dx * dx + dy * dy;
if (distanceSquared < bestDistance) {
bestDistance = distanceSquared;
bestIndex = i;
}
}
ordered.push(remaining.splice(bestIndex, 1)[0]);
}
return ordered;
}
function getColorForIncome(income) {
if (!Number.isFinite(income)) {
return '#cccccc';
}
if (income < 900) return '#f7fbff';
if (income < 1100) return '#deebf7';
if (income < 1300) return '#c6dbef';
if (income < 1500) return '#9ecae1';
if (income < 1800) return '#6baed6';
if (income < 2200) return '#4292c6';
return '#2171b5';
}
function extractSa2IncomeFeatures(sa2Geojson) {
const out = [];
for (const feature of sa2Geojson.features) {
if (!feature.geometry || !feature.properties) {
continue;
}
const income = Number(feature.properties.median_equivalised_household_income_weekly_2021);
if (!Number.isFinite(income)) {
continue;
}
const centroid = turf.centroid(feature);
out.push({
sa2Code: feature.properties.sa2_code_2021,
sa2Name: feature.properties.sa2_name_2021,
income,
coordinates: centroid.geometry.coordinates,
});
}
return out;
}
function getIncomeSplit(pathCoords, weightedPoints) {
if (pathCoords.length < 2 || weightedPoints.length === 0) {
return null;
}
let leftIncome = 0;
let rightIncome = 0;
for (const point of weightedPoints) {
const p = point.coordinates;
let nearestSegmentIndex = 0;
let nearestDistance = Infinity;
for (let i = 0; i < pathCoords.length - 1; i++) {
const segment = turf.lineString([pathCoords[i], pathCoords[i + 1]]);
const distance = turf.pointToLineDistance(turf.point(p), segment, { units: 'kilometers' });
if (distance < nearestDistance) {
nearestDistance = distance;
nearestSegmentIndex = i;
}
}
const [x1, y1] = pathCoords[nearestSegmentIndex];
const [x2, y2] = pathCoords[nearestSegmentIndex + 1];
const [px, py] = p;
const cross = (x2 - x1) * (py - y1) - (y2 - y1) * (px - x1);
if (cross >= 0) {
leftIncome += point.income;
} else {
rightIncome += point.income;
}
}
const total = leftIncome + rightIncome;
if (!total) {
return null;
}
const leftPercent = (leftIncome / total) * 100;
const rightPercent = (rightIncome / total) * 100;
return {
leftIncome,
rightIncome,
leftPercent,
rightPercent,
difference: Math.abs(leftPercent - 50),
};
}
async function loadSa2IncomeData() {
const response = await fetch(SA2_DATA_URL);
if (!response.ok) {
throw new Error(`Failed to load SA2 income data (${response.status})`);
}
const sa2Geojson = await response.json();
sa2IncomeFeatures = extractSa2IncomeFeatures(sa2Geojson);
if (activeSa2Layer) {
map.removeLayer(activeSa2Layer);
}
activeSa2Layer = L.geoJSON(sa2Geojson, {
style: function (feature) {
const income = Number(feature.properties?.median_equivalised_household_income_weekly_2021);
return {
color: '#555',
weight: 0.5,
fillOpacity: 0.35,
fillColor: getColorForIncome(income),
};
},
onEachFeature: function (feature, layer) {
const props = feature.properties || {};
const income = Number(props.median_equivalised_household_income_weekly_2021);
const incomeText = Number.isFinite(income) ? `$${income.toLocaleString()}` : 'N/A';
layer.bindPopup(
`<strong>${props.sa2_name_2021 || 'Unknown SA2'}</strong><br>` +
`Median equivalised household income (weekly): ${incomeText}`
);
}
}).addTo(map);
}
queryInput.addEventListener('input', updateCharCount);
updateCharCount();
try {
await loadSa2IncomeData();
statusElement.textContent = `Loaded ${sa2IncomeFeatures.length} SA2 income areas.`;
} catch (error) {
statusElement.textContent = `Could not load SA2 income data: ${error.message}`;
}
overpassForm.addEventListener('submit', async function(e) {
e.preventDefault();
const rawQuery = queryInput.value;
if (rawQuery.length > MAX_QUERY_CHARS) {
statusElement.textContent = `Query is too long (${rawQuery.length} chars). Limit is ${MAX_QUERY_CHARS}.`;
return;
}
statusElement.textContent = 'Running query...';
geoJSONOutElement.textContent = '';
const query = rawQuery.replace(/{{bbox}}/g, BBOX.join(','));
try {
if (activeDataLayer) {
map.removeLayer(activeDataLayer);
activeDataLayer = null;
}
if (activePathLayer) {
map.removeLayer(activePathLayer);
activePathLayer = null;
}
const response = await fetch('https://overpass-api.de/api/interpreter', {
method: 'POST',
body: 'data=' + encodeURIComponent(query),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
if (!response.ok) {
throw new Error(`Overpass request failed (${response.status})`);
}
const data = await response.json();
const geojson = osmtogeojson.default(data || { elements: [] });
const points = toPointList(geojson);
const orderedPoints = nearestNeighborPath(points);
const lineCollection = {
type: 'FeatureCollection',
features: []
};
if (orderedPoints.length >= 2) {
for (let i = 0; i < orderedPoints.length - 1; i++) {
const line = turf.lineString([orderedPoints[i], orderedPoints[i + 1]], {
name: `Line ${i + 1}`,
source: 'Generated nearest-neighbor path'
});
lineCollection.features.push(line);
}
activePathLayer = L.geoJSON(lineCollection, {
style: {
color: '#ff7800',
weight: 4,
opacity: 0.65
}
}).addTo(map);
}
activeDataLayer = L.geoJSON(geojson, {
onEachFeature: function (feature, layer) {
if (feature.properties) {
layer.bindPopup(`<strong>${feature.properties.name || 'Unnamed'}</strong><br>ID: ${feature.properties.id || 'N/A'}`);
}
}
}).addTo(map);
if (activeDataLayer.getLayers().length > 0) {
map.fitBounds(activeDataLayer.getBounds(), { padding: [20, 20] });
}
let scoreText = '';
const split = getIncomeSplit(orderedPoints, sa2IncomeFeatures);
if (split) {
scoreText = ` Income split: ${split.leftPercent.toFixed(1)}% / ${split.rightPercent.toFixed(1)}% (${split.difference.toFixed(1)}% difference from 50/50).`;
}
statusElement.textContent = `Query completed successfully. ${geojson.features.length} features loaded.${scoreText}`;
geoJSONOutElement.textContent = JSON.stringify(geojson, null, 2);
} catch (error) {
statusElement.textContent = 'Error running query: ' + error.message;
}
});
</script>
</body>
</html>