Get started on environment generation

This commit is contained in:
MeowcaTheoRange 2024-05-29 10:15:05 -05:00
parent 3a1ac18187
commit 5b2aa4dc8b
3 changed files with 121 additions and 7 deletions

File diff suppressed because one or more lines are too long

View file

@ -1,8 +1,114 @@
import "https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"; // window.L
import "./leaflet.js"; // window.L
const options = {
lang: "en_US",
offs: 0,
viewportPadding: 20,
boundsPadding: 0.1,
}
const defaultPolyStyling = {
color: "#000000",
opacity: 1,
fill: true,
fillOpacity: 0.25,
weight: 3
};
var map = L.map('leaflet-map').setView([0, 0], 2);
function moveBounds(polys, xoff = 0, yoff = xoff) {
return polys.map(([x, y]) => [y + yoff, x + xoff]);
}
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(map);
// Get tile data
async function getTileData(floor) {
let tileDataReq = await fetch(`/data/${options.lang}/map/${floor}`);
let tileData;
if (tileDataReq.ok)
tileData = await tileDataReq.json();
return tileData.map((room) =>
L.polygon(moveBounds(room.poly, options.offs), defaultPolyStyling)
);
}
// Get floor data
async function getFloorData() {
let floorDataReq = await fetch(`/data/${options.lang}/map/`);
let floorData;
if (floorDataReq.ok)
floorData = await floorDataReq.json();
// Add to Leaflet
const floors = await Promise.all(floorData.map(async (data) => {
const tileData = await getTileData(data.id);
const floorPoly = L.polygon(moveBounds(data.poly, options.offs), defaultPolyStyling)
return L.featureGroup([
floorPoly,
...tileData
]);
}));
return {
layers: floorData,
floors: floors
}
}
// Create map
async function createMap() {
const data = await getFloorData();
let map = L.map('leaflet-map', {
center: [0, 0],
zoom: 2,
crs: L.CRS.Simple
});
const mainLayer = L.tileLayer('', {
maxZoom: 4,
minZoom: 1,
attribution: 'Test data'
}).addTo(map);
const floor = data.floors[0].addTo(map);
const layerBounds = floor.getBounds();
const blb = layerBounds.pad(options.boundsPadding);
map.setMaxBounds(blb);
map.fitBounds(layerBounds, { padding: [options.viewportPadding, options.viewportPadding] });
const entries = Object.fromEntries(data.floors.map((floor, i) => [
`${data.layers[i].name}`,
floor
]));
let layerControl = L.control.layers(entries).addTo(map);
return {
floors: data.floors,
map,
mainLayer
};
}
async function mainFunction() {
const { floors, map, mainLayer } = await createMap();
map.on('baselayerchange', ({ layer, name }) => {
const layerBounds = layer.getBounds();
const blb = layerBounds.pad(options.boundsPadding);
map.setMaxBounds(blb);
map.fitBounds(layerBounds, { padding: [options.viewportPadding, options.viewportPadding] });
});
}
mainFunction();

View file

@ -7,8 +7,10 @@ body, html {
}
#leaflet-map {
background-color: #404040;
display: inline-block;
box-sizing: border-box;
height: 100%;
width: 100%;
}
}