/
index2.html
286 lines (242 loc) · 12 KB
/
index2.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
<DOCTYPE html>
<html>
<head>
<title>The Netherlands</title>
<script src="https://d3js.org/d3.v6.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.3.0/papaparse.min.js"></script>
<style>
.area {
fill:rgb(196, 228, 255);
stroke: lightblue;
stroke-width: 0.75px;
}
.city {
fill:rgb(228, 88, 8);
opacity: 0.9;
stroke: red;
stroke-width: 0.55px;
}
.selectedarea {
stroke: #22c74b;
stroke-width: 1.8px;
}
.legend-box {
position: absolute;
top: 30px;
left: 40px;
opacity: 0.9;
}
.zoom-box {
position: absolute;
top: 500px;
left: 40px;
background-color: antiquewhite;
padding: 10;
}
.zoom-panel {
font-size: 20px;
}
</style>
</head>
<body>
<h1>The Netherlands</h1>
<div id="map-container"></div>
</div>
<div class="zoom-box">
<div id="zoompanel" class="zoom-panel">
<button onclick="zoomIn()" class="zoom-panel" title="Zoom In">+</button>
<button onclick="zoomOut()" class="zoom-panel" title="Zoom Out">-</button>
<button onclick="reset()" class="zoom-panel" title="Reset">Reset</button>
</div>
<br />
<div id="translatepanel" class="zoom-panel">
<button onclick="panMap('left')" class="zoom-panel" title="Translate Left"><- </button>
<button onclick="panMap('up')" class="zoom-panel" title="Translate Up">^</button>
<button onclick="panMap('down')" class="zoom-panel" title="Translate Down">v</button>
<button onclick="panMap('right')" class="zoom-panel" title="Translate Right">-></button>
</div>
</div>
<script>
const mapWidth = 1000, mapHeight = 900
const initialScale = 8500, centerLat = 5.5, centerLong = 52.2;
const titleProperty = "statnaam" // the name of the property in the GeoJSON feature properties to be displayed as hover text
const identifyingProperty = "id" // the name of the property in the GeoJSON feature properties to be used for identifying area
const svg = d3.select("#map-container")
.append("svg")
.attr("width", mapWidth)
.attr("height", mapHeight);
const maxScaleFactor = 7 // how far and zooming in continue? (what is the maximum magnification factor)
const areasGroup = svg.append('g'); // create an SVG group to only contain area shapes; the SVG root can contain other (groups of) elements
// Append a <rect> element with fill and opacity 0 (invisible) to allow every pixel in the area to be zoomable and draggable
areasGroup.append("rect")
.attr("x", 0) // X-coordinate
.attr("y", 0) // Y-coordinate
.attr("width", mapWidth) // Width
.attr("height", mapHeight) // Height
.attr("opacity", 0.0) // Opacity set to 0 (invisible)
.attr("fill", "white")
// Function to handle zooming
// zooming applies to all paths in a specific group - that includes countries but not legend etc
const handleZoom = (event) => {
areasGroup.selectAll('path').attr('transform', event.transform); // Apply the zoom transform to path elements in areasGroup (i.e. the area shapes)
}
const zoomBehavior = d3.zoom()
.scaleExtent([1, maxScaleFactor])
.translateExtent([[0, 0], [mapWidth, mapHeight]])
.on("zoom", handleZoom)
// Attach the zoom behavior to the SVG group that contains all countries (as well as the rectangle that makes sure even every pixel not in a area shape is zoom=enabled)
areasGroup.call(zoomBehavior)
const zoomOut = () => {
areasGroup
.transition()
.call(zoomBehavior.scaleBy, 0.667);
}
const zoomIn = () => {
areasGroup
.transition()
.call(zoomBehavior.scaleBy, 1.5);
}
const panMap = (direction) => {
const panStep = 50
let horizontal = direction == "left" ? panStep : (direction == "right" ? -panStep : 0)
let vertical = direction == "up" ? panStep : (direction == "down" ? -panStep : 0)
areasGroup
.transition()
.call(zoomBehavior.translateBy, horizontal, vertical);
}
const reset = () => {
const transform = d3.zoomIdentity
.translate(0, 0)
.scale(1)
areasGroup.transition().duration(750)
.call(zoomBehavior.transform, transform);
}
// URL of the GeoJSON file
const geojsonUrl = "https://cartomap.github.io/nl/wgs84/provincie_2023.geojson";
const geojsonCitiesUrl = "https://cartomap.github.io/nl/wgs84/grootstedelijke_agglomeratie_2015.geojson";
let geojsonareaData
let selectedAreas = {}
let mostRecentProperty
let geoGenerator // path generator, created from projection
const parseCSV = (csvString) => {
return new Promise((resolve, reject) => {
Papa.parse(csvString, {
complete: results => resolve(results.data),
error: error => reject(error),
header: true // if your CSV has headers; set to false otherwise
});
});
}
Promise.all([
d3.json(geojsonUrl),
d3.json(geojsonCitiesUrl)
])
.then(([geojsonData, geojsonCitiesData]) => {
// merge geojsonCitiesData into geojsonData;l exclude statcode GA00 - it contains all of the Netherlands not in a city area
geojsonData.features = [...geojsonData.features, ...geojsonCitiesData.features.filter((f)=> f.properties.statcode!='GA00')];
geojsonareaData = geojsonData
redrawMap()
})
.catch(error => {
// Handle errors here
console.error('An error occurred:', error);
});
const redrawMap = () => {
areasGroup.selectAll("path").remove();
// Adjust projection based on scale and center of the map
const projection = d3.geoMercator()
.scale(initialScale).translate([mapWidth / 2, mapHeight / 2]).center([centerLat, centerLong]);
geoGenerator = d3.geoPath()
.projection(projection);
areasGroup
.selectAll('path')
.data(geojsonareaData.features)
.join('path')
.attr('d', geoGenerator)
.attr('class', (d)=> d.properties['rubriek']=='provincie'?'area':'city' )
.on('click', handleareaClick)
.append('title')
.text((d) => `${d.properties[titleProperty]}`)
}
const displayProperty = (property) => {
mostRecentProperty = property;
// find the domain for this property
const propertyDomain = d3.extent(geojsonareaData.features, (d) => parseFloat(d.properties[property]))
const colorScale = d3.scaleSequential(d3.interpolateBlues).domain(propertyDomain)
areasGroup
.selectAll('path')
.data(geojsonareaData.features)
.style('fill', (d) => colorScale(parseFloat(d.properties[property])))
.attr('class', 'area')
.select('title')
.text(
(d) => `${d.properties[titleProperty]} (${property}: ${d.properties[property]})`)
}
const getareaNodes = () => areasGroup.selectAll('path').data(geojsonareaData.features)
const getareaNode = (areaId) => getareaNodes()
.filter((c) => areaId === c.properties[identifyingProperty])
const highlightarea = (areaId) => {
getareaNode(areaId)
.classed('selectedarea', true)
}
const unhighlightarea = (areaId) => {
getareaNode(areaId)
.classed('selectedarea', false)
}
const highlightselectedAreas = () => {
getareaNodes()
.filter((c) => selectedAreas[c.properties[identifyingProperty]])
.classed('selectedarea', true)
}
const handleareaClick = (event, d) => {
const ctrlPressed = event.ctrlKey
const areaId = d.properties[identifyingProperty]
if (!ctrlPressed) {
// unselect all currently selected countries except the clicked one
for (const key in selectedAreas) {
if (key != areaId) {
unhighlightarea(parseInt(key)); // the key of an object is a string; however, in this case the values are integers, hence the parseInt
delete selectedAreas[key]
}
}
}
if (selectedAreas[areaId]) {
// clicked area was already selected
unhighlightarea(areaId)
delete selectedAreas[areaId]
} else {
highlightarea(areaId)
selectedAreas[areaId] = d
}
zoomToselectedAreas()
}
const zoomToselectedAreas = () => {
if (Object.keys(selectedAreas).length == 0) reset() // no areas are selected
else {
const selectedAreasGeoJSON = geojsonareaData.features.filter((c) => selectedAreas[c.properties[identifyingProperty]])
var minX = Number.POSITIVE_INFINITY;
var minY = Number.POSITIVE_INFINITY;
var maxX = Number.NEGATIVE_INFINITY;
var maxY = Number.NEGATIVE_INFINITY;
selectedAreasGeoJSON.forEach((geojson) => { // [process all GeoJSON polygons in all selected countries to find the furthest reaches in terms of X and Y coordinate]
const bounds = geoGenerator.bounds(geojson);
minX = Math.min(minX, bounds[0][0]);
minY = Math.min(minY, bounds[0][1]);
maxX = Math.max(maxX, bounds[1][0]);
maxY = Math.max(maxY, bounds[1][1]);
})
const dx = maxX - minX;
const dy = maxY - minY;
const x = (minX + maxX) / 2;
const y = (minY + maxY) / 2;
const newScale = Math.max(1, Math.min(4, 0.9 / Math.max(dx / mapWidth, dy / mapHeight)));
const transform = d3.zoomIdentity
.translate(mapWidth / 2, mapHeight / 2) // translate to center of map
.scale(newScale) // scale to the newScale factor
.translate(-x, -y) // translate to the newly calculate focus point
areasGroup.transition().duration(750).call(zoomBehavior.transform, transform);
}
}
</script>
</body>
</html>