/
interface.html
434 lines (405 loc) · 16.5 KB
/
interface.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
<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: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>
<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?
*/
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://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 © <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, 3 bit is the best way
// still allow 8 bit as it makes zoom out much nicer
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 = [];
const mapsLoaded = [];
Puck.eval(`require("Storage").list(/openstmap\\.\\d+\\.json/)\n`,function(files) {
console.log("MAPS:",files);
files.sort();
let promise = Promise.resolve();
files.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) {
mapsLoaded.push({mapNumber: mapNumber, mapInfo: mapInfo});
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>
`;
}
resolve();
});
}));
});
promise = promise.then(() => new Promise(resolve => {
setTimeout(() => {
mapsLoaded.forEach(mapLoaded => {
let latlon = L.latLng(mapLoaded.mapInfo.lat, mapLoaded.mapInfo.lon);
let map = L.map(`tile-map-${mapLoaded.mapNumber}`);
L.tileLayer(PREVIEWTILELAYER, {
maxZoom: 18
}).addTo(map);
let marker = new L.marker(latlon).addTo(map);
const dist = mapLoaded.mapInfo.scale * mapLoaded.mapInfo.tilesize * mapLoaded.mapInfo.w;
map.fitBounds(latlon.toBounds(dist/2/*meters*/), {animation: false});
});
}, 0);
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";
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) {
var options = {
compression:false, output:"raw",
mode:"web"
};
if (document.getElementById("3bit").checked) {
options = {
compression:false, output:"raw",
mode:"3bit",
diffusion:"bayer2"
};
}
/* 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);
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');
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>