Optimize javascript project 2

This commit is contained in:
Marcel Schwarz 2020-11-26 02:18:35 +01:00
parent d49cc6db97
commit 7ba71f2dd7
3 changed files with 103 additions and 116 deletions

View File

@ -2,12 +2,12 @@ const aufgabe1 = () => {
const map = L.map('map').setView([53.0, 14.0], 4) const map = L.map('map').setView([53.0, 14.0], 4)
map.addLayer(new L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { map.addLayer(new L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data <a href="https://openstreetmap.org">OpenStreetMap</a> contributors', attribution: 'Map data <a href="https://openstreetmap.org">OpenStreetMap</a> contributors',
minZoom: 1, minZoom: 0,
maxZoom: 18 maxZoom: 18
})) }))
const levels = [0, 20, 50, 100, 200, 250, 300, 400] const levels = [0, 20, 50, 100, 200, 250, 300, 400]
let geojson; let geojson
const getColor = density => { const getColor = density => {
switch (true) { switch (true) {

View File

@ -1,74 +1,62 @@
const aufgabe2 = () => { const aufgabe2 = () => {
const createIcon = imgName => L.icon({
iconUrl: `markers/${imgName}.png`,
iconSize: [60, 60],
iconAnchor: [30, 60],
popupAnchor: [0, -53]
})
const markerIcons = { const markerIcons = {
food: L.icon({ food: createIcon("food"),
iconUrl: 'markers/food.png', culture: createIcon("culture"),
iconSize: [60, 60], nature: createIcon("landscape"),
iconAnchor: [30, 60], train: createIcon("train")
popupAnchor: [0, -53]
}),
culture: L.icon({
iconUrl: 'markers/culture.png',
iconSize: [60, 60],
iconAnchor: [30, 60],
popupAnchor: [0, -53]
}),
nature: L.icon({
iconUrl: 'markers/landscape.png',
iconSize: [60, 60],
iconAnchor: [30, 60],
popupAnchor: [0, -53]
}),
train: L.icon({
iconUrl: 'markers/train.png',
iconSize: [60, 60],
iconAnchor: [30, 60],
popupAnchor: [0, -53]
})
} }
let map = L.map('poiMap').setView([48.779694, 9.177015], 14); let map = L.map('poiMap').setView([48.779694, 9.177015], 14);
map.addLayer(new L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { map.addLayer(new L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data <a href="https://openstreetmap.org">OpenStreetMap</a> contributors', attribution: 'Map data <a href="https://openstreetmap.org">OpenStreetMap</a> contributors',
minZoom: 1, minZoom: 0,
maxZoom: 18 maxZoom: 19
})) }))
const createFoodMarker = (coords, text) => L.marker(coords, {icon: markerIcons.food}).bindPopup(`<b>Essen und Trinken</b><br>${text}`)
const createCultureMarker = (coords, text) => L.marker(coords, {icon: markerIcons.culture}).bindPopup(`<b>Kunst und Kultur</b><br>${text}`)
const createNatureMarker = (coords, text) => L.marker(coords, {icon: markerIcons.nature}).bindPopup(`<b>Natur</b><br>${text}`)
const createTrainMarker = (coords, text) => L.marker(coords, {icon: markerIcons.train}).bindPopup(`<b>&Ouml;PNV</b><br>${text}`)
const foodLayer = L.layerGroup([ const foodLayer = L.layerGroup([
L.marker([48.780980, 9.169636], {icon: markerIcons.food}).bindPopup("<b>Essen und Trinken</b><br>Mensa Stuttgart"), createFoodMarker([48.780980, 9.169636], "Mensa Stuttgart"),
L.marker([48.778051, 9.176946], {icon: markerIcons.food}).bindPopup("<b>Essen und Trinken</b><br>Ochs'n Willi"), createFoodMarker([48.778051, 9.176946], "Ochs'n Willi"),
L.marker([48.779674, 9.178160], {icon: markerIcons.food}).bindPopup("<b>Essen und Trinken</b><br>K&ouml;nigsbau Passagen"), createFoodMarker([48.779674, 9.178160], "K&ouml;nigsbau Passagen"),
L.marker([48.780378, 9.172597], {icon: markerIcons.food}).bindPopup("<b>Essen und Trinken</b><br>HFT Block 4") createFoodMarker([48.780378, 9.172597], "HFT Block 4")
]) ])
const cultureLayer = L.layerGroup([ const cultureLayer = L.layerGroup([
L.marker([48.788165, 9.233864], {icon: markerIcons.culture}).bindPopup("<b>Kunst und Kultur</b><br>Mercedes-Benz Museum"), createCultureMarker([48.788165, 9.233864], "Mercedes-Benz Museum"),
L.marker([48.793296, 9.228010], {icon: markerIcons.culture}).bindPopup("<b>Kunst und Kultur</b><br>Porsche Arena"), createCultureMarker([48.793296, 9.228010], "Porsche Arena"),
L.marker([48.834270, 9.152479], {icon: markerIcons.culture}).bindPopup("<b>Kunst und Kultur</b><br>Porsche Museum"), createCultureMarker([48.834270, 9.152479], "Porsche Museum"),
L.marker([48.755866, 9.190109], {icon: markerIcons.culture}).bindPopup("<b>Kunst und Kultur</b><br>Fernsehturm"), createCultureMarker([48.755866, 9.190109], "Fernsehturm"),
L.marker([48.780149, 9.186586], {icon: markerIcons.culture}).bindPopup("<b>Kunst und Kultur</b><br>Staatsgalerie"), createCultureMarker([48.780149, 9.186586], "Staatsgalerie"),
L.marker([48.786550, 9.084028], {icon: markerIcons.culture}).bindPopup("<b>Kunst und Kultur</b><br>Schloss Solitude") createCultureMarker([48.786550, 9.084028], "Schloss Solitude")
]) ])
const natureLayer = L.layerGroup([ const natureLayer = L.layerGroup([
L.marker([48.804148, 9.208100], {icon: markerIcons.nature}).bindPopup("<b>Natur</b><br>Wilhelma"), createNatureMarker([48.804148, 9.208100], "Wilhelma"),
L.marker([48.782037, 9.268643], {icon: markerIcons.nature}).bindPopup("<b>Natur</b><br>Grabkapelle auf dem W&uuml;rttemberg"), createNatureMarker([48.782037, 9.268643], "Grabkapelle auf dem W&uuml;rttemberg"),
L.marker([48.785969, 9.187023], {icon: markerIcons.nature}).bindPopup("<b>Natur</b><br>Schlossgarten"), createNatureMarker([48.785969, 9.187023], "Schlossgarten"),
L.marker([48.818362, 9.184177], {icon: markerIcons.nature}).bindPopup("<b>Natur</b><br>Aussichtspunkt Burgholzhof") createNatureMarker([48.818362, 9.184177], "Aussichtspunkt Burgholzhof")
]) ])
const trainLayer = L.layerGroup([ const trainLayer = L.layerGroup([
L.marker([48.777440, 9.173764], {icon: markerIcons.train}).bindPopup("<b>&Ouml;PNV</b><br>Roteb&uuml;hlplatz"), createTrainMarker([48.777440, 9.173764], "Roteb&uuml;hlplatz"),
L.marker([48.784760, 9.182898], {icon: markerIcons.train}).bindPopup("<b>&Ouml;PNV</b><br>Stuttgart Hauptbahnhof"), createTrainMarker([48.784760, 9.182898], "Stuttgart Hauptbahnhof"),
L.marker([48.780173, 9.177220], {icon: markerIcons.train}).bindPopup("<b>&Ouml;PNV</b><br>B&ouml;rsenplatz"), createTrainMarker([48.780173, 9.177220], "B&ouml;rsenplatz"),
L.marker([48.755939, 9.142164], {icon: markerIcons.train}).bindPopup("<b>&Ouml;PNV</b><br>Seilbahn"), createTrainMarker([48.755939, 9.142164], "Seilbahn"),
L.marker([48.764290, 9.168611], {icon: markerIcons.train}).bindPopup("<b>&Ouml;PNV</b><br>Zahnradbahn"), createTrainMarker([48.764290, 9.168611], "Zahnradbahn"),
]) ])
map.addLayer(foodLayer)
map.addLayer(cultureLayer)
map.addLayer(natureLayer)
map.addLayer(trainLayer)
const overlayMaps = { const overlayMaps = {
'Essen und Trinken': foodLayer, 'Essen und Trinken': foodLayer,
'Kunst und Kultur': cultureLayer, 'Kunst und Kultur': cultureLayer,
@ -76,6 +64,7 @@ const aufgabe2 = () => {
'&Ouml;PNV': trainLayer '&Ouml;PNV': trainLayer
} }
Object.values(overlayMaps).forEach(layer => map.addLayer(layer))
L.control.layers(null, overlayMaps).addTo(map) L.control.layers(null, overlayMaps).addTo(map)
} }

View File

@ -1,38 +1,37 @@
const aufgabe3 = async () => { const aufgabe3 = async () => {
const years = [2015, 2016, 2017] const wantedYears = [2015, 2016, 2017]
const wantedSeries = [
{code: "SH_H2O_SAFE", displayName: "drinking water services"},
{code: "SH_SAN_SAFE", displayName: "sanitation services"}
]
const levels = [0, 50.0, 80.0, 85.0, 90.0, 95.0, 99.0, 99.9]
const loadData = async () => { const loadData = async () => {
const loadSeries = async seriesCode => { const loadSeries = async series => {
let maxNumberOfElements = (await axios.get("https://unstats.un.org/SDGAPI/v1/sdg/Series/Data", { let maxNumberOfElements = (await axios.get("https://unstats.un.org/SDGAPI/v1/sdg/Series/Data", {
params: {seriesCode} params: {seriesCode: series.code}
} }
)).data.totalElements )).data.totalElements
let requests = [] let requests = wantedYears.map(year => {
for (let year of years) { return axios.get("https://unstats.un.org/SDGAPI/v1/sdg/Series/Data", {
requests.push(axios.get("https://unstats.un.org/SDGAPI/v1/sdg/Series/Data", {
params: { params: {
seriesCode: seriesCode, seriesCode: series.code,
pageSize: maxNumberOfElements, pageSize: maxNumberOfElements,
timePeriod: year timePeriod: year
} }
})) })
} })
let dataArrays = (await Promise.all(requests)).map(arr => arr.data.data) let dataArrays = (await Promise.all(requests)).map(arr => arr.data.data)
const values = [].concat(...dataArrays) const values = [].concat(...dataArrays)
return values.filter(elem => elem.dimensions.Location === "ALLAREA") return values.filter(elem => elem.dimensions.Location === "ALLAREA")
} }
const apiData = await Promise.all(wantedSeries.map(loadSeries))
const apiData = await Promise.all([
loadSeries("SH_H2O_SAFE"),
loadSeries("SH_SAN_SAFE")
])
return [].concat(...apiData) return [].concat(...apiData)
}
const levels = [0, 50.0, 80.0, 85.0, 90.0, 95.0, 99.0, 99.9] }
const getColor = percentage => { const getColor = percentage => {
switch (true) { switch (true) {
@ -55,10 +54,11 @@ const aufgabe3 = async () => {
} }
} }
const map = L.map('suiMap').setView([53.0, 14.0], 4) const map = L.map('suiMap', {zoomControl: false}).setView([53.0, 14.0], 4)
L.control.zoom({position: 'bottomleft'}).addTo(map)
map.addLayer(new L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { map.addLayer(new L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data <a href="https://openstreetmap.org">OpenStreetMap</a> contributors', attribution: 'Map data <a href="https://openstreetmap.org">OpenStreetMap</a> contributors',
minZoom: 1, minZoom: 0,
maxZoom: 18 maxZoom: 18
})) }))
const [geojsonData, apiData] = await Promise.all([ const [geojsonData, apiData] = await Promise.all([
@ -68,10 +68,10 @@ const aufgabe3 = async () => {
// Attach api data to geojson // Attach api data to geojson
for (let elem of apiData) { for (let elem of apiData) {
const find = geojsonData.features.find(value => { const geoJsonFeature = geojsonData.features.find(value => {
return value.properties.name_long.includes(elem.geoAreaName) || elem.geoAreaName.includes(value.properties.name_long) return value.properties.name_long.includes(elem.geoAreaName) || elem.geoAreaName.includes(value.properties.name_long)
}) })
if (find) find.properties[elem.series + "_" + elem.timePeriodStart] = elem if (geoJsonFeature) geoJsonFeature.properties[elem.series + "_" + elem.timePeriodStart] = elem
} }
// Add the legend to the map // Add the legend to the map
@ -95,7 +95,7 @@ const aufgabe3 = async () => {
legend.addTo(map) legend.addTo(map)
// Control that shows state info on hover // Control that shows state info on hover
const info = L.control() const info = L.control({position: 'topleft'})
info.onAdd = () => { info.onAdd = () => {
info._div = L.DomUtil.create('div', 'info') info._div = L.DomUtil.create('div', 'info')
@ -117,52 +117,50 @@ const aufgabe3 = async () => {
info.addTo(map) info.addTo(map)
let layers = {} let layers = {}
let wantedSeries = [
{name: "SH_H2O_SAFE_2015", displayName: "drinking water services 2015"},
{name: "SH_H2O_SAFE_2016", displayName: "drinking water services 2016"},
{name: "SH_H2O_SAFE_2017", displayName: "drinking water services 2017"},
{name: "SH_SAN_SAFE_2015", displayName: "sanitation services 2015"},
{name: "SH_SAN_SAFE_2016", displayName: "sanitation services 2016"},
{name: "SH_SAN_SAFE_2017", displayName: "sanitation services 2017"},
]
for (let currSeries of wantedSeries) { for (let currSeries of wantedSeries) {
let geoJsonLayer = L.geoJson(geojsonData, { for (let currYear of wantedYears) {
style: feature => ({ let fullSeriesName = `${currSeries.code}_${currYear}`
stroke: true,
fill: true, let geoJsonLayer = L.geoJson(geojsonData, {
fillColor: getColor(feature.properties[currSeries.name].value), style: feature => ({
fillOpacity: 1, stroke: true,
dashArray: '3', fill: true,
weight: 2, fillColor: getColor(feature.properties[fullSeriesName].value),
color: 'black' fillOpacity: 1,
}), dashArray: '3',
filter: feature => { weight: 2,
return feature.properties.hasOwnProperty(currSeries.name) color: 'black'
}, }),
onEachFeature: (feature, layer) => { filter: feature => {
layer.on({ return feature.properties.hasOwnProperty(fullSeriesName)
mouseover: event => { },
event.target.setStyle({ onEachFeature: (feature, layer) => {
weight: 5, layer.on({
color: '#666', mouseover: event => {
dashArray: '', event.target.setStyle({
fillOpacity: 0.7 weight: 5,
}) color: '#666',
if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) event.target.bringToFront() dashArray: '',
info.update(feature.properties, currSeries.name) fillOpacity: 0.7
}, })
mouseout: event => { if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) event.target.bringToFront()
geoJsonLayer.resetStyle(event.target) info.update(feature.properties, fullSeriesName)
info.update() },
}, mouseout: event => {
click: event => map.fitBounds(event.target.getBounds()) geoJsonLayer.resetStyle(event.target)
}) info.update()
} },
}) click: event => map.fitBounds(event.target.getBounds())
layers[currSeries.displayName] = geoJsonLayer })
}
})
layers[`${currSeries.displayName} ${currYear}`] = geoJsonLayer
}
} }
map.addLayer(Object.values(layers)[0])
L.control.layers(layers, null).addTo(map) L.control.layers(layers, null).addTo(map)
} }