BangleApps/apps/openstmap/interface.html

425 lines
16 KiB
HTML
Raw Normal View History

<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" />
<link rel="stylesheet" href="../../css/spectre.min.css">
2022-01-12 13:54:21 +00:00
<link rel="stylesheet" href="https://unpkg.com/leaflet-geosearch@3.6.0/dist/geosearch.css"/>
</head>
<style>
body {
padding: 0;
margin: 0;
}
html, body, #map, #mapsLoaded, #mapContainer {
position: relative;
height: 100%;
width: 100%;
}
#map { z-index: 1; }
#controls {
padding: 10px;
margin: 10px;
border: 1px solid black;
position:absolute;
right:0px;top:0px;
background-color: rgb(255, 255, 255);
z-index: 100;
}
#maptiles {
width: 256px;
height: 256px;
}
.tile-title {
font-weight:bold;
font-size: 125%;
}
.tile-map {
width: 128px;
height: 128px;
}
</style>
</head>
<body>
<div id="mapsLoadedContainer">
</div>
<div id="mapContainer">
<div id="map">
</div>
<div id="controls">
2024-01-27 09:15:31 +00:00
<div style="display:inline-block;text-align:left;vertical-align: top;" id="3bitdiv">
<input type="checkbox" id="3bit"></input><span>3 bit</span>
<br>
<input type="checkbox" id="preview"><span>Preview</span>
</div>
<div class="form-group" style="display:inline-block;">
<select class="form-select" id="mapSize">
<option value="4">Small (4x4)</option>
<option value="5" selected>Medium (5x5)</option>
<option value="7">Large (7x7)</option>
<option value="10">XL (10x10)</option>
<option value="15">XXL (15x15)</option>
</select>
</div>
<button id="getmap" class="btn btn-primary">Get Map</button><button class="btn" onclick="showLoadedMaps()">Map List</button><br/>
<canvas id="maptiles" style="display:none"></canvas>
<div id="uploadbuttons" style="display:none"><button id="upload" class="btn btn-primary">Upload</button>
<button id="cancel" class="btn">Cancel</button>
<span id="mapstats"></span></div>
</div>
</div>
<script src="../../core/lib/interface.js"></script>
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="../../webtools/heatshrink.js"></script>
<script src="../../webtools/imageconverter.js"></script>
2022-01-12 13:54:21 +00:00
<script src="https://unpkg.com/leaflet-geosearch@3.6.0/dist/bundle.min.js"></script>
<script src="imagefilter.js"></script>
<script>
/*
TODO:
* Could maybe use palettised output?
* Could potentially use a custom 16 color palette?
* Allow user to choose size of map area to be uploaded (small/med/large)
* What is faster? Storing as a compressed image and decompressing, or storing decompressed?
*/
2022-03-17 08:28:55 +00:00
var TILESIZE = 96; // Size of our tiles
var OSMTILESIZE = 256; // Size of openstreetmap tiles
2020-04-08 20:34:40 +00:00
/* Can see possible tiles on http://leaflet-extras.github.io/leaflet-providers/preview/
However some don't allow cross-origin use */
//var TILELAYER = 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png'; // simple, high contrast, TOO SLOW
2020-04-08 20:34:40 +00:00
//var TILELAYER = 'http://a.tile.stamen.com/toner/{z}/{x}/{y}.png'; // black and white
2023-04-25 09:09:07 +00:00
var TILELAYER = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';
var PREVIEWTILELAYER = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';
var loadedMaps = [];
// Tiles used for Bangle.js itself
var bangleTileLayer = L.tileLayer(TILELAYER, {
maxZoom: 18,
attribution: 'Map data &copy; <a href="https://openstreetmap.org/copyright">OpenStreetMap</a> contributors</a>'
});
// Tiles used for the may the user sees (faster)
var previewTileLayer = L.tileLayer(PREVIEWTILELAYER, {
maxZoom: 18,
attribution: 'Map data &copy; <a href="https://openstreetmap.org/copyright">OpenStreetMap</a> contributors</a>'
});
2020-04-08 20:34:40 +00:00
// Could optionally overlay trails: https://wiki.openstreetmap.org/wiki/Tiles
// Create map and try and set the location to where the browser thinks we are
var map = L.map('map').locate({setView: true, maxZoom: 16, enableHighAccuracy:true});
previewTileLayer.addTo(map);
2022-03-17 08:28:55 +00:00
// Search box:
const searchProvider = new window.GeoSearch.OpenStreetMapProvider();
const searchControl = new GeoSearch.GeoSearchControl({
provider: searchProvider,
style: 'button',
updateMap: true,
autoClose: true,
showMarker: false,
keepResult: true,
autoComplete: false
});
map.addControl(searchControl);
// ---------------------------------------- Run at startup
2022-03-17 08:28:55 +00:00
function onInit(device) {
if (device && device.info && device.info.g) {
2023-08-07 11:22:40 +00:00
// On 3 bit devices, 3 bit is the best way
// still allow 8 bit as it makes zoom out much nicer
2022-03-17 08:28:55 +00:00
if (device.info.g.bpp==3) {
document.getElementById("3bit").checked = true;
2023-08-07 11:22:40 +00:00
//document.getElementById("3bitdiv").style = "display:none";
2022-03-17 08:28:55 +00:00
}
}
showLoadedMaps();
}
function showLoadedMaps() {
document.getElementById("mapsLoadedContainer").style.display = "";
document.getElementById("mapContainer").style.display = "none";
Util.showModal("Loading maps...");
let mapsLoadedContainer = document.getElementById("mapsLoadedContainer");
mapsLoadedContainer.innerHTML = "";
loadedMaps = [];
Puck.write(`\x10Bluetooth.println(require("Storage").list(/openstmap\\.\\d+\\.json/))\n`,function(files) {
console.log("MAPS:",files);
let promise = Promise.resolve();
files.trim().split(",").forEach(filename => {
if (filename=="") return;
promise = promise.then(() => new Promise(resolve => {
Util.readStorageJSON(filename, mapInfo => {
console.log(filename + " => " + JSON.stringify(mapInfo));
let mapNumber = filename.match(/\d+/)[0]; // figure out what map number we are
loadedMaps[mapNumber] = mapInfo;
if (mapInfo!==undefined) {
let latlon = L.latLng(mapInfo.lat, mapInfo.lon);
mapsLoadedContainer.innerHTML += `
<div class="tile">
<div class="tile-icon">
<div class="tile-map" id="tile-map-${mapNumber}">
</div>
</div>
<div class="tile-content">
<p class="tile-title">Map ${mapNumber}</p>
<p class="tile-subtitle">${mapInfo.w*mapInfo.h} Tiles (${((mapInfo.imgx*mapInfo.imgy)>>11).toFixed(0)}k)</p>
</div>
<div class="tile-action">
<button class="btn btn-primary" onclick="onMapDelete(${mapNumber})">Delete</button>
</div>
</div>
`;
2022-12-01 13:47:48 +00:00
setTimeout(function() {
let map = L.map(`tile-map-${mapNumber}`);
L.tileLayer(PREVIEWTILELAYER, {
maxZoom: 18
}).addTo(map);
let marker = new L.marker(latlon).addTo(map);
map.fitBounds(latlon.toBounds(2000/*meters*/), {animation: false});
}, 500);
}
resolve();
});
}));
});
promise = promise.then(() => new Promise(resolve => {
if (!loadedMaps.length) {
mapsLoadedContainer.innerHTML += `
<div class="tile">
<div class="tile-icon">
<div class="tile-map">
</div>
</div>
<div class="tile-content">
<p class="tile-title">No Maps Loaded</p>
</div>
<div class="tile-action">
</div>
</div>
`;
}
mapsLoadedContainer.innerHTML += `
<div class="tile">
<div class="tile-icon">
<div class="tile-map">
</div>
</div>
<div class="tile-content">
</div>
<div class="tile-action">
<button class="btn btn-primary" onclick="showMap()">Add Map</button>
</div>
</div>
`;
Util.hideModal();
}));
});
}
function onMapDelete(mapNumber) {
console.log("delete", mapNumber);
Util.showModal(`Erasing map ${mapNumber}...`);
Util.eraseStorage(`openstmap.${mapNumber}.json`, function() {
Util.eraseStorage(`openstmap.${mapNumber}.img`, function() {
Util.hideModal();
showLoadedMaps();
});
});
2022-03-17 08:28:55 +00:00
}
function showMap() {
document.getElementById("mapsLoadedContainer").style.display = "none";
document.getElementById("mapContainer").style.display = "";
document.getElementById("maptiles").style.display="none";
document.getElementById("uploadbuttons").style.display="none";
map.invalidateSize();
map.locate({setView: true, maxZoom: 16, enableHighAccuracy:true});
}
// -----------------------------------------------------
var mapFiles = [];
// convert canvas into an actual tiled image file
function tilesLoaded(ctx, width, height, mapImageFile) {
2022-03-17 08:28:55 +00:00
var options = {
compression:false, output:"raw",
mode:"web"
};
if (document.getElementById("3bit").checked) {
options = {
compression:false, output:"raw",
mode:"3bit",
2022-11-25 17:05:30 +00:00
diffusion:"bayer2"
};
}
2023-08-07 11:22:40 +00:00
/* Go through all the data beforehand and
turn the saturation up to maximum, so if thresholded to 3 bits it
works a lot better */
var imageData = ctx.getImageData(0,0,width,height);
var dstData = ctx.createImageData(width, height);
var filterOptions = {};
imageFilterFor3BPP(imageData, dstData, filterOptions);
ctx.putImageData(dstData,0,0);
console.log("Compression options", options);
var w = Math.round(width / TILESIZE);
var h = Math.round(height / TILESIZE);
var tiledImage;
for (var y=0;y<h;y++) {
for (var x=0;x<w;x++) {
var imageData = ctx.getImageData(x*TILESIZE, y*TILESIZE, TILESIZE, TILESIZE);
var rgba = imageData.data;
options.rgbaOut = rgba;
options.width = TILESIZE;
options.height = TILESIZE;
var imgstr = imageconverter.RGBAtoString(rgba, options);
2024-01-27 09:15:31 +00:00
if (document.getElementById("preview").checked) {
ctx.putImageData(imageData,x*TILESIZE, y*TILESIZE); // write preview
}
/*var compress = 'require("heatshrink").decompress('
if (!imgstr.startsWith(compress)) throw "Data in wrong format";
imgstr = imgstr.slice(compress.length,-1);*/
if (tiledImage) tiledImage += imgstr.substr(3); // skip header
else tiledImage = imgstr; // for first image, keep the header
}
}
return [{
name:mapImageFile,
content:tiledImage
}];
}
document.getElementById("getmap").addEventListener("click", function() {
var MAPTILES = parseInt(document.getElementById("mapSize").value);
var MAPSIZE = TILESIZE*MAPTILES; /// Size of map we download to Bangle in pixels
var OSMTILECOUNT = (Math.ceil((MAPSIZE+TILESIZE) / OSMTILESIZE)+1); // how many tiles do we download from OSM in each direction
var zoom = map.getZoom();
var centerlatlon = map.getBounds().getCenter();
var center = map.project(centerlatlon, zoom).divideBy(OSMTILESIZE); // the center of our map
// ox/oy = offset in pixels
var ox = Math.round((center.x - Math.floor(center.x)) * OSMTILESIZE);
var oy = Math.round((center.y - Math.floor(center.y)) * OSMTILESIZE);
// adjust offset because we want to center our map
ox -= MAPTILES * TILESIZE / 2;
oy -= MAPTILES * TILESIZE / 2;
center = center.floor(); // make sure we're in the middle of a tile
// JS version of Bangle.js's projection
function bproject(lat, lon) {
const degToRad = Math.PI / 180; // degree to radian conversion
const latMax = 85.0511287798; // clip latitude to sane values
const R = 6378137; // earth radius in m
if (lat > latMax) lat=latMax;
if (lat < -latMax) lat=-latMax;
var s = Math.sin(lat * degToRad);
return new L.Point(
(R * lon * degToRad),
(R * Math.log((1 + s) / (1 - s)) / 2)
);
}
// Work out scale factors (how much from Bangle.project does one pixel equate to?)
var pc = map.unproject(center.multiplyBy(OSMTILESIZE), zoom);
var pd = map.unproject(center.multiplyBy(OSMTILESIZE).add({x:1,y:0}), zoom);
var bc = bproject(pc.lat, pc.lng)
var bd = bproject(pd.lat, pd.lng)
var scale = bc.distanceTo(bd);
// test
/*var p = bproject(centerlatlon.lat, centerlatlon.lng);
var q = bproject(mylat, mylon);
var testPt = {
x : (q.x-p.x)/scale + (MAPSIZE/2),
y : (MAPSIZE/2) - (q.y-p.y)/scale
};*/
var tileGetters = [];
// Render everything to a canvas...
var canvas = document.getElementById("maptiles");
canvas.style.display="";
var ctx = canvas.getContext('2d');
2022-03-17 08:28:55 +00:00
canvas.width = MAPSIZE;
canvas.height = MAPSIZE;
var tileMin = Math.round(-OSMTILECOUNT/2);
var tileMax = Math.round(OSMTILECOUNT/2);
for (var i = tileMin; i <= tileMax; i++) {
for (var j = tileMin; j <= tileMax; j++) {
(function(i,j){
var coords = new L.Point(center.x+i, center.y+j);
coords.z = zoom;
var img = new Image();
img.crossOrigin = "Anonymous";
tileGetters.push(new Promise(function(resolve,reject) {
img.onload = function(){
ctx.drawImage(img,i*OSMTILESIZE - ox, j*OSMTILESIZE - oy);
/*if (testPt) {
ctx.fillStyle="green";
ctx.fillRect(testPt.x-1, testPt.y-5, 3,10);
ctx.fillRect(testPt.x-5, testPt.y-1, 10,3);
}*/
/*ctx.fillStyle="black";
ctx.fillRect(i*OSMTILESIZE - ox, j*OSMTILESIZE - oy, 6,6);*/
resolve();
};
}));
bangleTileLayer._tileZoom = previewTileLayer._tileZoom;
img.src = bangleTileLayer.getTileUrl(coords);
})(i,j);
}
}
Promise.all(tileGetters).then(() => {
document.getElementById("uploadbuttons").style.display="";
var mapNumber = 0;
while (loadedMaps[mapNumber]) mapNumber++;
let mapImageFile = `openstmap.${mapNumber}.img`;
mapFiles = tilesLoaded(ctx, canvas.width, canvas.height, mapImageFile);
mapFiles.unshift({name:`openstmap.${mapNumber}.json`,content:JSON.stringify({
imgx : canvas.width,
imgy : canvas.height,
tilesize : TILESIZE,
scale : scale, // how much of Bangle.project(latlon) does one pixel equate to?
lat : centerlatlon.lat,
lon : centerlatlon.lng,
w : Math.round(canvas.width / TILESIZE), // width in tiles
h : Math.round(canvas.height / TILESIZE), // height in tiles
fn : mapImageFile
})});
var mapSizeInK = Math.round(mapFiles.reduce((r,m)=>m.content.length+r,0)/1000);
document.getElementById("mapstats").innerText = "Size : "+ (mapSizeInK+"kb");
console.log(mapFiles);
});
});
document.getElementById("upload").addEventListener("click", function() {
Util.showModal("Uploading...");
let promise = Promise.resolve();
mapFiles.forEach(file => {
promise = promise.then(function() {
return new Promise(resolve => {
Util.writeStorage(file.name, file.content, resolve);
});
});
});
promise.then(function() {
Util.hideModal();
console.log("Upload Complete");
showLoadedMaps();
});
});
document.getElementById("cancel").addEventListener("click", function() {
showMap();
});
</script>
</body>
</html>