Leaflet-Customelement/leaflet_snippet.html
2024-04-21 18:48:39 +02:00

116 lines
3.1 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<title>Leaflet Multi Polygons</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id="map" style = "width: 1700px; height: 860px"></div>
<script>
function alertJ(x){
let s = JSON.stringify(x, null, 4);
alert(s);
}
async function search(name){
let results = localStorage.getItem("https://nominatim.openstreetmap.org/search.php?q="+name+"&polygon_geojson=1&format=json");
if(results){
console.log("Use cache!");
return JSON.parse(results);
}
else{
console.log("Use fetch!");
let resp = await fetch("https://nominatim.openstreetmap.org/search.php?q="+name+"&polygon_geojson=1&format=json");
let results = await resp.json();
localStorage.setItem("https://nominatim.openstreetmap.org/search.php?q="+name+"&polygon_geojson=1&format=json", JSON.stringify(results));
return results;
}
}
function right_result(result){
return result.osm_type === "relation";
}
//let resp = await fetch("https://nominatim.openstreetmap.org/details?osmtype=R&osmid=175905&format=json");
//let name = "Braunschweig";
//let name = "Berlin, Germany";
//let name = "Berlin";
//let name = "Leipzig";
//let name = "Erfurt";
//let name = "Germany";
//let name = "Ukraine";
//let name = "Iran";
//let name = "India";
//let name = "Bhutan";
(async function(){
let spec = {
areas: {
"Potsdam": "blue",
"Erfurt": "yellow",
"Berlin": "red",
"Bernau": "orange"
},
focus: "Berlin"
};
let polygons = {};
for(let k of Object.keys(spec.areas)){
let results = await search(k);
let result = results.filter(right_result)[0];
polygons[k] = result;
}
let mapOptions = {
//center: [52.6787254, 13.5881114],
//center: [Number(result.lat), Number(result.lon)],
center: [Number(polygons[spec.focus].lat), Number(polygons[spec.focus].lon)],
zoom: 11
};
let map = new L.map('map', mapOptions);
let layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
map.addLayer(layer);
function switch_coords(poly){
return poly.map(t => [t[1], t[0]]);
}
for(let k of Object.keys(polygons)){
let result = polygons[k];
let latlang;
switch(result.geojson.type){
case "MultiPolygon":
latlang = [
...result.geojson.coordinates[0].map(x => switch_coords(x))
];
break;
case "Polygon":
latlang = [
...[ switch_coords(result.geojson.coordinates[0]) ]
];
break;
}
let multiPolygonOptions = {color: spec.areas[k], weight:2};
let multipolygon = L.multiPolygon(latlang , multiPolygonOptions);
multipolygon.addTo(map);
}
}());
</script>
</body>
</html>