felt/static/map.js

82 lines
1.8 KiB
JavaScript
Raw Normal View History

2023-07-03 05:10:58 +00:00
let map = null;
let mapImg = null;
2023-07-05 07:18:46 +00:00
let tokens = [];
const worldBounds = [[180, -180],[-180, 180]];
2023-07-03 05:10:58 +00:00
function initializeMap(mapImgUrl) {
2023-07-08 05:56:41 +00:00
let init = false;
if (!map) {
2023-07-08 05:56:41 +00:00
init = true;
map = L.map('map', { minZoom: 0, maxZoom: 4, crs: L.CRS.Simple });
map.on("zoomend", ()=>{resizeMarkers();scaleSpritePreview();});
}
if (mapImg) {
mapImg.removeFrom(map);
}
mapImg = L.imageOverlay(mapImgUrl, worldBounds);
mapImg.addTo(map);
map.setMaxBounds(worldBounds);
2023-07-08 05:56:41 +00:00
if (init) {
map.setView([0,0], 2);
}
while (tokens.some(t=>t)) {
tokens[0].m.removeFrom(map);
tokens.shift();
}
2023-07-05 07:18:46 +00:00
}
// this works but assumes the map is square (reasonable limitation I think)
function resizeMarkers() {
tokens.forEach(t=>{
const icon = t.m.options.icon;
const scaleFactor = mapImg._image.clientWidth / mapImg._image.naturalWidth;
icon.options.iconSize = [scaleFactor * t.sz[0], scaleFactor * t.sz[1]];
t.m.setIcon(icon);
});
}
function getCascadingPos() {
const topLeft = worldBounds[0];
const n = tokens.length;
topLeft[1] += (n+1)*5;
topLeft[0] -= (n+1)*5;
return topLeft;
}
2023-07-08 05:56:41 +00:00
function NewToken(w, h, oX, oY, img, name, x, y) {
return {
sz: [w, h],
m: L.marker((x && y) ? [y,x] : getCascadingPos(), {
icon: L.icon({
iconUrl: img,
iconSize: [w,h],
}),
title: name,
draggable: true,
autoPan: true
}),
};
}
2023-07-05 07:18:46 +00:00
function addToken(token) {
const self = { sz: token.sz, m: L.marker(token.pos, {
icon: L.icon({
iconUrl: token.img,
iconSize: token.sz,
}),
title: token.name,
draggable: true,
autoPan: true
})};
tokens.push(self);
self.m.addTo(map);
}
// token for testing in browser console
const t = {
img: "https://nilfm.cc/favicon.png",
sz: [32,32],
pos: [0,0],
name: "test",
2023-07-03 05:10:58 +00:00
}