Add location control to the map properly

This commit is contained in:
Austen Adler 2023-03-19 13:52:20 -04:00
parent 83288289d6
commit 4f63a87a76
2 changed files with 35 additions and 21 deletions

View File

@ -7,11 +7,17 @@
let mapElement;
let locationChecked;
let locationControl;
export let onMapClick = () => {};
export let map;
const locationCheckedChanged = () => {
const locationCheckedChanged = (setValue) => {
if (setValue === true || setValue === false) {
// Shortcut to set it in this function, if they passed a boolean
locationChecked = !!setValue;
}
if (locationChecked) {
console.log('Starting location');
map.locate({ setView: true, watch: true, enableHighAccuracy: true });
@ -29,36 +35,40 @@
// TODO: Pick a better spot
map.setView([51.505, -0.09], 13);
map.on('locationerror', (e) => {
// If getting location caused an error, disable tracking
console.error('Error getting location', e);
locationChecked = false;
locationCheckedChanged();
locationCheckedChanged(false);
});
map.on('dragstart', (e) => {
// If they move the map at all, they are not interested in their location anymore
locationCheckedChanged(false);
});
map.on('click', (e) => {
// If they click the map at all, they are not interested in their location anymore
locationCheckedChanged(false);
});
map.on('click', onMapClick);
map.on('locationfound', (e) => {
dispatch('locationfound', e);
});
// Add the location control
let ctrl = leaflet.control();
ctrl.onAdd = () => {
return locationControl;
};
ctrl.update = (props) => {
console.info('Clicked ctrl:', props);
};
ctrl.addTo(map);
leaflet
.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution:
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
})
.addTo(map);
// let popup = leaflet.popup();
// map.on('click', (e) => {
// try {
// // TODO: Leaflet allows sending coordinates out of the standard range
// latlng = e.latlng;
// addr = address_from_lat_lon(latlng.lat, latlng.lng);
// popup.setLatLng(e.latlng).setContent(`${addr}`).openOn(map);
// } catch (err) {
// console.error(err);
// addr = '';
// popup.setLatLng(e.latlng).setContent(`You clicked at ${e.latlng}`).openOn(map);
// }
// });
}
});
@ -71,9 +81,13 @@
</script>
<div id="container" class="h-3/4">
<label>
<label
bind:this={locationControl}
class="bg-white p-2 border-black border-solid"
on:click|stopPropagation
>
<input type="checkbox" bind:checked={locationChecked} on:change={locationCheckedChanged} />
Watch my location
Location
</label>
<div id="map" bind:this={mapElement} class="h-full w-full" />
</div>

View File

@ -4,7 +4,7 @@ import * as xpinWasm from 'xpin-wasm';
export const emptyxpin = {
address: '',
latLon: [0.0, 0.0],
decimalDegrees: '',
decimalDegrees: ''
};
export function getxpin(xpin) {