-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathmap.js
625 lines (502 loc) · 18.5 KB
/
map.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
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
var map; // Global variable to store the Leaflet map
var towns; // GeoJSON layer for town boundaries
var townActive; // Selected town name
var dataLayer; // GeoJSON layer with district data
var overlays = {}; // An object to contain overlay layer groups, eg `transit`
var zone2color = {
'R': '#645097', // primarily residential, satisfied
'M': '#815196', // mixed with residential, satisfied
'N': '#BA6CA4', // nonresidential, satisfied
'NS': '#d0d0d0', // not satisfied
}
// Columns in the original spreadsheet
var zName = 'Z';
var zTown = 'T';
var zType = 'Ty';
var zAcres = 'MA'; // municipal area
var style = function(filters, feature) {
var opacity = $('input[name="opacity"]').val() / 100;
return {
fillOpacity: opacity,
fillColor: satisfiesFilters(filters, feature) ? zone2color[feature.properties[zType]] : zone2color['NS'],
weight: 0
}
}
var updateUrl = function() {
var mapLocationHash = location.hash.split('/').slice(0,3).join('/');
// Update URL
location.replace(mapLocationHash + '/' + $('#form').serialize() );
}
/**
* Loads the main GeoJSON data file
*/
var loadZones = function(geojson) {
var filters = getFilters();
dataLayer = L.geoJSON(geojson, {
attribution: 'data by <a href="https://www.desegregatect.org/">Desegregate CT</a>,\
map development by <a href="https://ctdata.org">CTData Collaborative</a>',
style: function(feature) { return style(filters, feature) },
onEachFeature: function(feature, layer) {
var pp = feature.properties;
// On layer click, select town
layer.on('click', function() {
var townClicked = pp[zTown];
townActive = townClicked === townActive ? '' : townClicked;
// Select a town which contains the clicked district
$('input[name="townActive"]').val(townActive);
// Draw active boundary
towns.setStyle( townStyle );
// Recalculate area
calculateActiveArea();
if (townActive) {
// Fit town to center
towns.eachLayer(function(l) {
if (l.feature.properties.NAME10 === townActive) {
map.fitBounds( l.getBounds() );
setTimeout(updateUrl, 500);
}
});
} else {
// Deactivate
updateUrl();
}
});
// Add tooltip
layer.bindTooltip(!pp[zName] || pp[zName] === 'Not Zoned' || pp[zName] === 'NULL'
? '<strong>Not Zoned</strong><br>' + pp[zTown]
: '<h6 class="t-t ttu">' + pp[zName] + '</h6><strong class="black-50">' + pp[zTown] + '</strong><br>'
+ ( pp['AHD'] == 'Yes' ? 'Affordable Housing Only<br>' : '' )
+ ( pp['EHD'] == 'Yes' ? 'Elderly Housing Only<br>' : '' )
+ ( pp['MUS'] == '1' ? 'Requires a Minimum Home Size<br>' : '' )
+ ( pp['TN'] ? '<strong>Note:</strong> ' + pp['TN']: '' ),
{ sticky: true } );
}
}).addTo(map);
// Turn on federal/state land by default
$('input[name="Overlay"][value="fs"]').prop('checked', true);
// Add selected overlays to the map
$('input[name="Overlay"]:checked').each(function(i, el) {
if (overlays[el.value]) {
overlays[el.value].addTo(map);
}
});
var form = document.getElementById('form');
form.addEventListener('change', function() {
updateUrl();
var filters = getFilters();
dataLayer.setStyle(function(feature) { return style(filters, feature) });
// Make sure groups of checkboxes where at least one is expected to be checked
// turns red if none are checked (and vice-versa)
$('.at-least-one-checked:has( input:checked )').removeClass('bg-light-red');
$('.at-least-one-checked:not(:has( input:checked ))').addClass('bg-light-red');
calculateActiveArea();
$('input[name="Overlay"]').each(function(i, el) {
var value = el.value;
if (filters['Overlay'] && filters['Overlay'].indexOf( value ) >= 0) {
overlays[value].addTo(map);
} else {
if (map.hasLayer(overlays[value])) {
map.removeLayer(overlays[value])
}
}
});
if ( $('.main-in-group:checked').length > 0 ) {
$('#resetFilters').show();
} else {
$('#resetFilters').hide();
}
});
// When main checkbox in filters group is clicked, open up subgroup
$('.main-in-group').change(function() {
var subgroup = $(this).parent().siblings('.subgroup').first();
if (this.checked) {
subgroup.removeClass('dn');
subgroup.find('input.checked-by-default').prop('checked', true);
} else {
subgroup.find('input[type="checkbox"]').prop('checked', false);
subgroup.addClass('dn');
}
});
calculateActiveArea();
}
/*
* On page loads, sets filters based on the URL
*/
var setFilters = function() {
var filters = $.unserialize(
location.hash.split('/').slice(3).join('/')
);
if (filters['townActive']) {
townActive = filters['townActive'];
$('input[name="townActive"').val(townActive);
}
for (var filter in filters) {
var value = filters[filter];
if (filter === 'opacity') {
$('input[name="' + filter + '"]').val(value);
} else if (typeof value === 'string') {
$('input[name="' + filter + '"][value="' + value + '"]' ).prop('checked', true);
} else {
for (var i in value) {
$('input[name="' + filter + '"][value="' + value[i] + '"]' ).prop('checked', true);
}
}
}
$('input.main-in-group:checked').parents().siblings('.subgroup').removeClass('dn');
$('.at-least-one-checked:has( input:checked )').removeClass('bg-light-red');
$('.at-least-one-checked:not(:has( input:checked ))').addClass('bg-light-red');
if ( $('.main-in-group:checked').length > 0 ) {
$('#resetFilters').show();
} else {
$('#resetFilters').hide();
}
// Add event listener to the clear filters button
$('#resetFilters').on('click', function() {
// Clear town selection
townActive = '';
towns.setStyle( townStyle );
// Clear filters
$('.main-in-group:checked').click();
// Hide button
$(this).hide();
});
}
/*
* Constructs and returns a `filters` object based on the form in the sidebar
*/
var getFilters = function() {
var filters = {};
var checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
for (var i = 0; i < checkboxes.length; i++) {
var name = checkboxes[i].name;
var value = checkboxes[i].value;
if (!name || !value) continue;
if ( !filters[name] ) { filters[name] = []; }
filters[name].push(value);
}
return filters;
}
/*
* Given a `filters` object, returns true if all residential property
* checkboxes are satisfied by the `feature` (zone), `false` otherwise.
*/
var satisfiesFilters = function(filters, feature) {
for (var name in filters) {
if (name === 'Overlay') continue;
if ( filters[name].indexOf( feature.properties[name] ) < 0 ) {
return false;
}
}
return true;
}
/*
* Adds zone type box colors to the legend
*/
var addColorPolygonsToLegend = function() {
$('#legend .square').each(function() {
$(this).css('background-color', zone2color[$(this).attr('title')] );
});
}
/*
* Defines style for 169 town outlines: yellow if selected,
* semi-transparent white if not
*/
var townStyle = function(feature) {
return {
stroke: feature.properties.NAME10 === townActive ? 5 : 2,
color: feature.properties.NAME10 === townActive ? 'yellow' : 'white',
opacity: feature.properties.NAME10 === townActive ? 1 : 0.4,
fillOpacity: 0,
fillColor: 'rgba(0,0,0,0)'
}
}
/*
* Given towns GeoJSON file in `bounds`, adds non-interactivve town boundaries
* layer to the map
*/
var loadTowns = function(bounds) {
towns = L.geoJSON(bounds, {
pane: 'overlays',
interactive: false,
style: townStyle
});
towns.addTo(map);
}
/*
* Calculates what % of a selected town satisfies filtering criteria,
* and updates the message in the sidebar
*/
var calculateActiveArea = function() {
if (!townActive) {
$('#activeAreaCalculator').html('').addClass('dn');
return;
}
var filters = getFilters();
var totalAcres = 0;
var satisfiesAcres = 0;
dataLayer.eachLayer(function(l) {
if (l.feature.properties[zTown] === townActive) {
totalAcres += l.feature.properties[zAcres] || 0;
if (satisfiesFilters(filters, l.feature)) {
satisfiesAcres += l.feature.properties[zAcres] || 0;
}
}
});
var satisfiesPerc = (satisfiesAcres / totalAcres * 100).toFixed(1);
satisfiesAcres = parseInt(satisfiesAcres).toLocaleString();
totalAcres = parseInt(totalAcres).toLocaleString();
$('#activeAreaCalculator').html('<p class="ma0 mb2">' + satisfiesAcres + ' acres, or ' + satisfiesPerc
+ '% of <span class="bb-dotted" title="Excludes state- and federal-owned land, and unzoned parts of town">zoned municipal area</span> in <strong>' + townActive + '</strong> (' + totalAcres
+ ' acres) satisfies your filtering criteria.</p><div style="font-size: 13px"><span class="black-50 dib w-third fl tl" title="Median Household Income">'
+ '<span class="material-icons v-top" style="font-size:16px">payments</span> $' + demographics[townActive].income.toLocaleString()
+ '<br>HH Income</span><span class="black-50 dib w-third fl tc" title="Black, Indigenous, People of Color">'
+ '<span class="material-icons v-top" style="font-size:16px">people_alt</span> ' + demographics[townActive].bipoc
+ '%<br>BIPOC</span><span class="black-50 dib fl ml2 tr" title="Cost-Burdened Households">'
+ '<span class="material-icons v-top" style="font-size:16px">toll</span> ' + demographics[townActive].burdened + '%<br>Cost-Burdened</span>'
+ '</div>');
$('#activeAreaCalculator').removeClass('dn');
}
/*
* Creates a layer group of rail/fastrak markers from `transit.js` data.
*/
var loadTransit = function() {
var transitMarkers = transit.map(function(o) {
return L.marker([o.Latitude, o.Longitude], {
icon: L.icon({
iconUrl: 'img/' + o.Mode + '.png',
iconSize: o.Mode === 'rail' ? [24, 24] : [16, 16],
iconAnchor: o.Mode === 'rail' ? [12, 12] : [8, 8],
})
}).bindTooltip(o.Name + '<br> <em class="ttc">' + o.Mode + '</em>')
});
var transitCircles = transit.map(function(o) {
return L.circle([o.Latitude, o.Longitude], {
radius: 804.5, // half a mile, in meters
weight: 1,
color: 'white',
fillColor: 'white',
opacity: 0.9,
fillOpacity: 0.2,
interactive: false
});
});
overlays['transit'] = L.layerGroup( transitCircles.concat(transitMarkers) );
}
var loadHydro = function() {
$.getJSON('./data/hydro.min.geojson', function(geojson) {
var stripes = new L.StripePattern({
height: 2,
width: 2,
weight: 1,
spaceWeight: 1,
angle: -45,
color: '#C6DDFF',
});
stripes.addTo(map);
overlays['hydro'] = L.geoJSON(geojson, {
interactive: false,
stroke: false,
pane: 'overlays',
style: {
fillOpacity: 1,
fillPattern: stripes
}
})
});
}
var loadSewer = function() {
$.getJSON('./data/sewer.min.geojson', function(geojson) {
var stripes = new L.StripePattern({
height: 4,
width: 4,
weight: 1,
spaceWeight: 3,
angle: 45,
color: '#e8f99d',
});
stripes.addTo(map);
overlays['sewer'] = L.geoJSON(geojson, {
interactive: false,
stroke: false,
pane: 'overlays',
style: {
fillOpacity: 1,
fillPattern: stripes
}
})
});
}
var loadFederalState = function() {
$.getJSON('./data/federal-state.min.geojson', function(geojson) {
var stripes = new L.StripePattern({
height: 2,
width: 2,
weight: 1,
spaceWeight: 1,
angle: 30,
color: '#5cc649',
});
stripes.addTo(map);
overlays['fs'] = L.geoJSON(geojson, {
interactive: false,
stroke: false,
pane: 'overlays',
style: {
fillOpacity: 1,
fillPattern: stripes
}
})
});
}
/**
* This function initializes the map. It should be called as soon as
* DOM is loaded.
*/
var initMap = function() {
map = L.map('map', {
zoomControl: false,
tap: false,
maxZoom: 15,
}).setView([41.5744, -72.67], 10);
L.control.zoom({ position: 'topright' }).addTo(map);
// CartoDB Positron baselayer, no labels
var cartoTiles = L.tileLayer('https://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}{r}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors © <a href="https://carto.com/attributions">CARTO</a>',
subdomains: 'abcd',
maxZoom: 19
}).addTo(map);
var esriTiles = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
});
// Add base layer switch
L.control.layers({
'Map': cartoTiles,
'Satellite': esriTiles
}, {}, {
position: 'bottomright',
collapsed: false
}).addTo(map);
// CartoDB Positron baselayer, no labels
L.tileLayer('https://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}{r}.png', {
attribution: '',
subdomains: 'abcd',
maxZoom: 19,
pane: 'shadowPane'
}).addTo(map);
setFilters();
// Load town boundaries
$.getJSON('./data/towns.min.geojson', loadTowns);
// Load main data GeoJSON with zones
$.getJSON('./data/final.20220427.geojson', loadZones);
// Add hash
var hash = new L.Hash(map);
// Add color polygons to legend
addColorPolygonsToLegend();
// Create overlays pane
map.createPane('overlays');
map.getPane('overlays').style.zIndex = 501;
// Add overlays
loadTransit();
loadHydro();
loadSewer();
loadFederalState();
// Add Esri geocoder
var searchControl = L.esri.Geocoding.geosearch({
position: 'topright',
allowMultipleResults: false,
searchBounds: [[40.98, -73.74], [42.04, -71.78]]
}).addTo(map);
var results = L.layerGroup().addTo(map);
searchControl.on('results', function (data) {
results.clearLayers();
for (var i = data.results.length - 1; i >= 0; i--) {
results.addLayer(L.marker(data.results[i].latlng));
}
});
// Start tour
var driver = new Driver({
animate: false,
allowClose: false,
});
// Define the steps for introduction
driver.defineSteps([
/*{
element: '#CtZoningAtlas',
popover: {
title: 'Connecticut Zoning Atlas',
description: 'Zoning laws covering nearly every inch of Connecticut tell us what can be built, where. They say whether we can have single-family housing in one neighborhood, or apartment buildings in another. This interactive map was drawn from our survey of all 2,616 zoning districts in 178 zoning jurisdictions in the state, as well as 2 subdivision-only jurisdictions in the 2 towns without zoning. We think it shows how outdated zoning laws make it hard to build diverse, affordable housing.',
position: 'right'
}
},*/
{
element: '#TypeOfZoningDistrict',
popover: {
title: 'What are the Zoning Districts?',
description: 'We have put the zoning districts in each town into one of three categories: \
<ul><li><strong>Primarily Residential</strong>: Districts where housing is the main use. They may also include things you might find in residential neighborhoods, like schools and churches. We included farming-residential districts in rural towns in this category.</li>\
<li> <strong>Mixed with Residential</strong>: Districts where housing and retail, office, or other commercial uses mix together. They are typically districts around our “main streets” or in areas meant to be developed flexibly.</li>\
<li> <strong>Nonresidential</strong>: Districts where housing is not allowed to be an independent use. However, some nonresidential districts allow accessory dwelling units, like an apartment for a night watchman in a factory setting.</li></ul>',
position: 'right'
}
},
{
element: '#PermittedResidentialUses',
popover: {
title: 'Select Permitted Residential Uses',
description: '<p>Select one or more of the <strong>Permitted Residential Uses</strong> from the menu on the left-hand side of this screen. The purple and pink hues on the map will show you what kind of zoning district the chosen residential use appears in.</p>\
<p>Explore the specific conditions under which your selected Permitted Residential Use is allowed, like <strong>minimum lot size</strong> requirements, <strong>public hearing</strong> requirements, or restrictions for <strong>elderly housing</strong>.</p>',
position: 'right'
},
onNext: function() {
// Make sure calculator displays on top of map in the next step
driver.preventMove();
$('#activeAreaCalculator').css('z-index', '110000');
driver.moveNext();
}
},
{
element: '#map',
popover: {
title: 'Click the Map to Learn About Your Town',
description: 'Click the map for the popup to appear on top of the map. It will tell you what percent of land satisfies your selection criteria, as well as\
median household income, the percent of people cost-burdened (spending 30% or more of their income on housing), and what percent of the population identifies as Black, Indigenous, or as a person of color (BIPOC).',
position: 'mid-center',
},
onNext: function() {
driver.preventMove();
$('#activeAreaCalculator').css('z-index', '999');
driver.moveNext();
}
},
{
element: '#Overlays',
popover: {
title: 'Explore the Overlays',
description: 'You can toggle between the <strong>Transit and Waterways \
Overlays</strong> to visualize areas within a half mile of passenger rail and \
CT<i>fastrak</i>, as well as bodies of water within the state.',
position: 'right'
}
},
{
element: '.leaflet-control-layers-list',
popover: {
title: 'Change the Basemap',
description: 'Would you prefer to view the Atlas from a bird\'s eye view? Click "Satellite" at the bottom right in the map.',
position: 'top-right'
}
},
{
element: '#ZoneOpacity',
popover: {
title: 'Adjust Zone Opacity',
description: 'Move the slider to adjust zoning layer transparency.',
position: 'right'
}
}
]);
// Start the introduction
driver.start();
}
// Initialize the map when DOM is loaded
document.addEventListener('DOMContentLoaded', initMap);