feat: toggle buttons reset & set-center

This commit is contained in:
relikd
2024-07-03 00:23:01 +02:00
parent 10316bd247
commit cf9bd5bdf6

View File

@@ -1,12 +1,18 @@
function MapLocationInit(mapId, options = {}) { function MapLocationInit(mapId, options = {}) {
const valField = document.getElementById(mapId + '_value'); const valField = document.getElementById(mapId + '_value');
const theMap = document.getElementById(mapId + '_map'); const theMap = document.getElementById(mapId + '_map');
const resetButton = document.getElementById(mapId + '_reset'); const btnAction = document.getElementById(mapId + '_btn');
function isZero(latlng) { function isZero(latlng) {
return latlng.lat === 0 && latlng.lng === 0; return latlng.lat === 0 && latlng.lng === 0;
} }
function asString(latlng) {
if (isZero(latlng)) { return ''; }
const pos = latlng.wrap();
return pos.lat.toFixed(6) + ',' + pos.lng.toFixed(6);
}
const osm = L.tileLayer(options.tileLayer || 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', options.tileOptions); const osm = L.tileLayer(options.tileLayer || 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', options.tileOptions);
const map = L.map(mapId + '_map', { const map = L.map(mapId + '_map', {
layers: [osm], layers: [osm],
@@ -25,9 +31,7 @@ function MapLocationInit(mapId, options = {}) {
} }
const marker = L.marker(loadPos(), { draggable: true }); const marker = L.marker(loadPos(), { draggable: true });
marker.on('move', function (e) { marker.on('move', function (e) {
const pos = map.wrapLatLng(e.latlng); valField.value = asString(e.latlng);
const flag = isZero(pos);
valField.value = flag ? null : pos.lat.toFixed(6) + ',' + pos.lng.toFixed(6);
}); });
map.on('click', function (e) { map.on('click', function (e) {
if (isZero(marker.getLatLng())) { if (isZero(marker.getLatLng())) {
@@ -35,15 +39,18 @@ function MapLocationInit(mapId, options = {}) {
setMapState(false); setMapState(false);
} }
}); });
resetButton.onclick = function () { btnAction.onclick = function () {
marker.setLatLng([0, 0]); const isReset = !!btnAction.dataset.reset;
setMapState(true); marker.setLatLng(isReset ? [0, 0] : map.getCenter());
setMapState(isReset ? true : false);
return false; return false;
}; };
function setMapState(initial) { function setMapState(initial) {
theMap.style.cursor = initial ? 'crosshair' : null; theMap.style.cursor = initial ? 'crosshair' : null;
initial ? marker.remove() : marker.addTo(map); initial ? marker.remove() : marker.addTo(map);
btnAction.dataset.reset = initial ? '' : '1';
btnAction.innerText = initial ? 'Set center' : 'Reset';
} }
setMapState(isZero(marker.getLatLng())); setMapState(isZero(marker.getLatLng()));