-
Notifications
You must be signed in to change notification settings - Fork 0
/
scenic_plot.html
457 lines (428 loc) · 17.3 KB
/
scenic_plot.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
<!DOCTYPE html>
<html>
<head>
<title>Scenic Ratings of London</title>
<meta charset="utf-8" />
<link
href="https://fonts.googleapis.com/css?family=Lora:400,700italic"
rel="stylesheet"
type="text/css"
/>
<link
rel="stylesheet"
href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css"
/>
<link rel="stylesheet" type="text/css" href="scenic_plot.css" />
<script type="text/javascript" src="scenic_plot.js"></script>
<script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"></script>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"
></script>
</head>
<body>
<div id="map"></div>
<script>
/**
* Load the csv data containing scenic ratings for particular points across london.
* These values are the average rating of ~four viewpoints across 360 degrees per point.
* The data is converted to geojson so we can easily extract the coordinates of points,
* and the library d3 is used to help display the (~130000) points
**/
var now_showing = 0;
d3.csv(
"mean_scenic_rating_per_locid_30_10_19.csv",
function (error, scenic) {
var geoData = {
type: "FeatureCollection",
features: reformat(scenic)
};
var leafletMap = L.map("map").setView([51.505, -0.09], 13);
var base = L.tileLayer(
"http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png",
{
attribution:
'© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> ' +
'contributors, © <a href="http://cartodb.com/attributions">CartoDB</a>'
}
);
leafletMap.addLayer(base);
var svg = d3.select(leafletMap.getPanes().overlayPane).append("svg"); // svg appends a d3 layer for rendering svg to the leaflet map
var g = svg.append("g").attr("class", "leaflet-zoom-hide"); // g keeps SVGs grouped together
function projectPoint(x, y) {
var point = leafletMap.latLngToLayerPoint(new L.LatLng(y, x));
this.stream.point(point.x, point.y);
}
/**
* Path and transform take regular coords and turn them into svg coords, and
* those coords are applied back to the leaflet map layer using the current stream (above)
**/
var transform = d3.geo.transform({
point: projectPoint
});
var path = d3.geo.path().projection(transform);
function redrawSubset(subset) {
path.pointRadius(2);
var bounds = path.bounds({
type: "FeatureCollection",
features: subset
});
var topLeft = bounds[0];
var bottomRight = bounds[1];
svg
.attr("width", bottomRight[0] - topLeft[0])
.attr("height", bottomRight[1] - topLeft[1])
.style("left", topLeft[0] + "px")
.style("top", topLeft[1] + "px");
g.attr(
"transform",
"translate(" + -topLeft[0] + "," + -topLeft[1] + ")"
);
var points = g
.selectAll("path")
.data(subset, function (d) {
return d.geometry.coordinates;
})
.enter()
.append("path")
.attr("d", path)
.attr("class", "point")
.style("fill", function (d) {
return percToColour(d.properties.scenic_rating, 1.5, 6.3);
})
.style("fillOpacity", 0.8);
}
function mapmove(e) {
d3.selectAll(".point").remove();
redrawSubset(geoData.features);
}
/**
* Next load data containing values for multiple variables per LSOA, so this info can be
* displayed as we rollover and click on an LSOA. These layers have far fewer points
* (1 per LSOA), and so are implemented purely in leaflet
**/
function highlightFeature(e) {
var layer = e.target;
layer.setStyle({
weight: 1,
opacity: 1,
color: "#acadc1",
dashArray: "",
fillOpacity: 0.2
});
if (!L.Browser.ie && !L.Browser.opera) {
layer.bringToFront();
}
info.update(layer.feature.properties);
}
var lsoaBoundaries;
function resetHighlight(e) {
lsoaBoundaries.resetStyle(e.target);
info.update();
}
function displayInfo(e) {
var layer = e.target;
now_showing = layer.feature.properties;
info.update(layer.feature.properties);
}
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: displayInfo
});
}
$.getJSON(
"lsoa_boundary_and_crime_data_11_11_19.geojson",
function (json) {
lsoaBoundaries = L.geoJson(json, {
// boundary data as well as income, health data etc. info to display
style: function (feature) {
return {
fillColor: "#acadc1",
weight: 1,
opacity: 0,
color: "white",
fillOpacity: 0
};
},
onEachFeature: onEachFeature
}).addTo(leafletMap);
var sceneryLayer = L.geoJson(json, {
// scenery layer displaying mean scenic ratings per LSOA
style: function (feature) {
return {
fillColor: percToColour(
feature.properties.scenic_rating,
2.16,
4.84
),
weight: 1,
opacity: 0,
color: "white",
dashArray: "1",
fillOpacity: 0.6
};
}
});
var crimeLayer = L.geoJson(json, {
// crime layer displaying mean monthly crime counts per LSOA
style: function (feature) {
return {
fillColor: getCrimeColour(
feature.properties.mean_monthly_crime_count
),
weight: 1,
opacity: 0,
color: "white",
dashArray: "1",
fillOpacity: 0.4
};
}
});
var d3Layer = L.Class.extend({
// extend leaflet class to toggle on/off d3 layer w/ other leaflet layers
initialize: function () {
return;
},
onAdd: function () {
leafletMap.on("viewreset", mapmove); // remove points and redraw relevant subset as we move around map
redrawSubset(geoData.features); // draw initial susbet in starting position
scenicPointsLegend.addTo(leafletMap);
},
onRemove: function () {
leafletMap.off("viewreset", mapmove);
d3.selectAll(".point").remove();
leafletMap.removeControl(scenicPointsLegend);
}
});
var baseMaps = {
// switch between scenic rating per points vs mean per LSOA vs crime counts
"Average Scenic Ratings per LSOA": sceneryLayer,
"Average Crime Count per Month": crimeLayer,
"Scenic Points": new d3Layer()
};
L.control
.layers(baseMaps, null, {
position: "bottomright",
collapsed: false
})
.addTo(leafletMap);
leafletMap.attributionControl.addAttribution(
'Scenic Data © <a href="http://scenicornot.datasciencelab.co.uk/">Scenic-Or-Not</a>'
);
}
);
/**
* Then, add and scale info bars (scenic rating and indices of health, income and employment deprivation)
* to show when particular LSOA is clicked on. Each variable has been scaled between 1 and 10.
**/
// custom info control
var info = L.control();
info.onAdd = function (map) {
this._div = L.DomUtil.create("div", "info"); // create a div with a class "info"
this.update();
return this._div;
};
// method to update the control based on feature properties passed
info.update = function (props) {
var rollover_html = ``;
if (!props && !now_showing) {
rollover_html = `<h4>Click on any LSOA <br />to see region data</h4>`;
} else if (props && !now_showing) {
rollover_html +=
`<h4>Show data for ` +
props.lsoa11cd +
` (` +
props.lsoa11nm +
`)</h4>`;
} else {
var showingCode = now_showing.lsoa11cd;
var showingName = now_showing.lsoa11nm;
var scenicness = getScenicBar(now_showing.scenic_rating);
var health = getHealthBar(
now_showing.deprivation_health_deprivation_and_disability_score
);
var income = getIncomeBar(
now_showing.deprivation_income_score_rate
);
var employ = getEmploymentBar(
now_showing.deprivation_employment_score_rate
);
var education = getEducationBar(
now_showing.deprivation_education_skills_and_training_score
);
var livingEnv = getLivingEnvBar(
now_showing.deprivation_living_environment_score
);
var crime = getCrimeColour(
now_showing.mean_monthly_crime_count,
(return_integer = true)
);
rollover_html += `<b>LSOA: ${showingCode} (${showingName})</b>
<br/>Scenicness<br/><div class="band" style="width:${
160 - scenicness * 10 * 1.6
}px; border-left:${
scenicness * 10 * 1.6
}px solid #a42e3d"> </div>
Health<br/><div class="band" style="width:${
160 - health * 10 * 1.6
}px; border-left:${
health * 10 * 1.6
}px solid #a42e3d"> </div>
Income<br/><div class="band" style="width:${
160 - income * 10 * 1.6
}px; border-left:${
income * 10 * 1.6
}px solid #a42e3d"> </div>
Employment<br/><div class="band" style="width:${
160 - employ * 10 * 1.6
}px; border-left:${
employ * 10 * 1.6
}px solid #a42e3d"> </div>
Education<br/><div class="band" style="width:${
160 - education * 10 * 1.6
}px; border-left:${
education * 10 * 1.6
}px solid #a42e3d"> </div>
Living Environ.<br/><div class="band" style="width:${
160 - livingEnv * 10 * 1.6
}px; border-left:${
livingEnv * 10 * 1.6
}px solid #a42e3d"> </div>
Crime<br/><div class="band" style="width:${
160 - crime * 10 * 1.6
}px; border-left:${
crime * 10 * 1.6
}px solid #a42e3d"> </div>`;
if (props) {
// currently hovering over
rollover_html +=
`<br/><h4>Show data for ` +
props.lsoa11cd +
` (` +
props.lsoa11nm +
`) next?</h4>`;
}
}
this._div.innerHTML = rollover_html;
};
info.addTo(leafletMap);
var continuousScaleLegend = L.Control.extend({
initialize: function (min, max) {
/**
* @param {Number} min Min value in data (low end of colour scale)
* @param {Number} max Max value in data (high end of colour scale)
**/
this._min = min;
this._max = max;
return;
},
options: { position: "bottomleft" },
onAdd: function (map) {
var div = L.DomUtil.create("div", "info legend");
div.innerHTML = `Scenicness Rating<br>Min (${this._min})   Max (${this._max})`;
var legend_svg = d3.select(div).append("svg");
var defs = legend_svg.append("defs");
var linearGradient = defs
.append("linearGradient")
.attr("id", "linear-gradient");
linearGradient
.append("stop")
.attr("offset", "0%")
.attr(
"stop-color",
percToColour(this._min, this._min, this._max)
);
linearGradient
.append("stop")
.attr("offset", "100%")
.attr(
"stop-color",
percToColour(this._max, this._min, this._max)
);
legend_svg
.append("rect")
.attr("width", 200)
.attr("height", 35)
.style("fill", "url(#linear-gradient)")
.style("opacity", 0.8);
return div;
}
});
var scenicPointsLegend = new continuousScaleLegend(1.5, 6.3);
var scenicLsoaLegend = new continuousScaleLegend(2.1, 4.8);
var crimeLegend = L.control({ position: "bottomleft" });
crimeLegend.onAdd = function (map) {
var div = L.DomUtil.create("div", "info legend crime");
var grades = [55, 25, 15, 7, 2];
var label_text = ["> 50", "20 - 50", "10 - 20", "5 - 10", "< 5"];
var labels = ["Av. Monthly Crimes"];
for (var i = 0; i < grades.length; i++) {
labels.push(
'<i style="background:' +
getCrimeColour(grades[i]) +
'"></i> ' +
label_text[i]
);
}
div.innerHTML = labels.join("<br>");
return div;
};
leafletMap.on("baselayerchange", function (event) {
// display appropriate legend as baselayer changes
lsoaBoundaries.bringToFront(); // keep lsoa boundary info (health, income scores etc.) at the front
if (event.name === "Average Crime Count per Month") {
if (scenicLsoaLegend._map) {
leafletMap.removeControl(scenicLsoaLegend);
}
crimeLegend.addTo(leafletMap);
} else {
if (crimeLegend._map) {
leafletMap.removeControl(crimeLegend);
}
if (event.name === "Average Scenic Ratings per LSOA") {
scenicLsoaLegend.addTo(leafletMap);
} else {
// layer change to scenic points
if (scenicLsoaLegend._map) {
leafletMap.removeControl(scenicLsoaLegend);
}
}
}
});
function viewPostcode() {
var pcode = document.getElementById("enter-pcode").value;
if (pcode != "") {
var pcode_url_req = "https://api.postcodes.io/postcodes/" + pcode;
$.get(pcode_url_req, function (data, status) {
var long = data["result"]["longitude"];
var lat = data["result"]["latitude"];
leafletMap.setView([lat, long], 15);
}).fail(function () {
document.getElementById("enter-pcode").value = "";
alert("Please enter a valid postcode. For example, NW1 2DB");
});
}
}
L.Control.textbox = L.Control.extend({
onAdd: function (map) {
var text = L.DomUtil.create("div", "search-pcode");
text.innerHTML =
'<input class="pcode" id="enter-pcode" placeholder="Enter postcode...">' +
'<button class="pcode" id="search">Search</button>';
text.addEventListener("click", viewPostcode);
return text;
}
});
L.control.textbox = function (opts) {
return new L.Control.textbox(opts);
};
L.control.textbox({ position: "topleft" }).addTo(leafletMap);
}
);
</script>
</body>
</html>