import { getCookie, setCookie } from './utils.js' function getCoordinates() { let location = [51.505, -0.09]; // London by default on leaflet let lat = getCookie("lat"); let lng = getCookie("lng"); if (lat != undefined && lng != undefined) { location = [lat, lng]; console.log(`Got a previous geolocation cookie at ${location[0]}, ${location[1]}`) } return location; } function updateLocationCookies([lat, lng]) { setCookie("lat", lat, 10); setCookie("lng", lng, 10); } function geolocationHandler() { let location = getCoordinates(); let message = document.querySelector('.message'); // Init map let map = L.map('map').setView(location, 15); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap' }).addTo(map); let marker = undefined; // Get geolocation function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(setLocation); } else { message.innerHTML = "Geolocation is not supported by this browser."; } } function setLocation(position) { location = [position.coords.latitude, position.coords.longitude]; if (marker === undefined) { marker = new L.marker(location, { draggable: 'true' }); marker.on('dragend', updateMarker); marker.addTo(map); } else { marker.setLatLng(location); } map.setView(location, 15); updateLocationCookies(location); } function updateMap(event) { if (marker === undefined) { marker = new L.marker(event.latlng, { draggable: 'true' }); marker.on('dragend', updateMarker); marker.addTo(map); } else { marker.setLatLng(event.latlng); } updateLocationCookies([event.latlng.lat, event.latlng.lng]); } function updateMarker(event) { let position = marker.getLatLng(); map.panTo([position.lat, position.lng]); updateLocationCookies([position.lat, position.lng]); } map.on('click', updateMap); document.querySelector('.geolocation-button') .addEventListener('click', getLocation); } export { geolocationHandler, getCoordinates }