44 lines
1.5 KiB
JavaScript
44 lines
1.5 KiB
JavaScript
import { getCookie, setCookie } from './utils.js'
|
|
|
|
function geoLocationHandler() {
|
|
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]}`)
|
|
}
|
|
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: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
|
|
}).addTo(map);
|
|
// Init marker
|
|
let marker = L.marker(location).addTo(map);
|
|
|
|
// 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];
|
|
marker.setLatLng(location);
|
|
map.setView(location, 15);
|
|
setCookie("lat", position.coords.latitude, 10);
|
|
setCookie("lng", position.coords.longitude, 10);
|
|
console.log("Geolocation cookie saved for future games");
|
|
}
|
|
|
|
document.querySelector('.geolocation-button')
|
|
.addEventListener('click', getLocation);
|
|
}
|
|
|
|
export {
|
|
geoLocationHandler
|
|
} |