mirror of https://github.com/espruino/BangleApps
438 lines
17 KiB
HTML
438 lines
17 KiB
HTML
<html>
|
|
<head>
|
|
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" />
|
|
<link rel="stylesheet" href="../../css/spectre.min.css">
|
|
<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">
|
|
<div style="display:inline-block;text-align:center;vertical-align: top;" id="3bitdiv"> <input type="checkbox" id="3bit"></input><br/><span>3 bit</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>
|
|
<script src="https://unpkg.com/leaflet-geosearch@3.6.0/dist/bundle.min.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?
|
|
|
|
*/
|
|
var TILESIZE = 96; // Size of our tiles
|
|
var OSMTILESIZE = 256; // Size of openstreetmap tiles
|
|
/* 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
|
|
//var TILELAYER = 'http://a.tile.stamen.com/toner/{z}/{x}/{y}.png'; // black and white
|
|
var TILELAYER = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
|
|
var PREVIEWTILELAYER = 'https://{s}.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 © <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 © <a href="https://openstreetmap.org/copyright">OpenStreetMap</a> contributors</a>'
|
|
});
|
|
// 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);
|
|
|
|
// 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
|
|
function onInit(device) {
|
|
if (device && device.info && device.info.g) {
|
|
// On 3 bit devices, don't even offer the option. 3 bit is the only way
|
|
if (device.info.g.bpp==3) {
|
|
document.getElementById("3bit").checked = true;
|
|
document.getElementById("3bitdiv").style = "display:none";
|
|
}
|
|
}
|
|
|
|
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.readStorage(filename, fileContents => {
|
|
console.log(filename + " => " + fileContents);
|
|
let mapNumber = filename.match(/\d+/)[0]; // figure out what map number we are
|
|
let mapInfo;
|
|
try {
|
|
mapInfo = JSON.parse(fileContents);
|
|
} catch (e) {
|
|
console.error(e);
|
|
}
|
|
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>
|
|
`;
|
|
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});
|
|
}, 100);
|
|
}
|
|
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();
|
|
});
|
|
});
|
|
}
|
|
|
|
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";
|
|
}
|
|
|
|
// -----------------------------------------------------
|
|
var mapFiles = [];
|
|
|
|
// convert canvas into an actual tiled image file
|
|
function tilesLoaded(ctx, width, height, mapImageFile) {
|
|
var options = {
|
|
compression:false, output:"raw",
|
|
mode:"web"
|
|
};
|
|
if (document.getElementById("3bit").checked) {
|
|
options = {
|
|
compression:false, output:"raw",
|
|
mode:"3bit",
|
|
diffusion:"bayer2"
|
|
};
|
|
/* If in 3 bit mode, go through all the data beforehand and
|
|
turn the saturation up to maximum, so when thresholded it
|
|
works a lot better */
|
|
var imageData = ctx.getImageData(0,0,width,height);
|
|
var rgba = imageData.data;
|
|
var l = width*height*4;
|
|
for (var i=0;i<l;i+=4) {
|
|
var min = Math.min(rgba[i+0],rgba[i+1],rgba[i+2]);
|
|
var max = Math.max(rgba[i+0],rgba[i+1],rgba[i+2]);
|
|
var d = max-min;
|
|
if (max<120 || (d<8 && max<215)) { // black, or a darker grey
|
|
rgba[i+0]=0;
|
|
rgba[i+1]=0;
|
|
rgba[i+2]=0;
|
|
} else if (min>240 || d<8) { // white or grey
|
|
rgba[i+0]=255;
|
|
rgba[i+1]=255;
|
|
rgba[i+2]=255;
|
|
} else { // another colour - use max saturation
|
|
rgba[i+0] = (rgba[i+0]-min) * 255 / d;
|
|
rgba[i+1] = (rgba[i+1]-min) * 255 / d;
|
|
rgba[i+2] = (rgba[i+2]-min) * 255 / d;
|
|
}
|
|
}
|
|
ctx.putImageData(imageData,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);
|
|
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');
|
|
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>
|