refactor: remove unnecessary control from leaflet-map

This commit is contained in:
log101 2024-07-22 14:29:29 +03:00
parent 09e69f61b9
commit d5bc7b98dd
4 changed files with 33 additions and 158 deletions

View File

@ -32,20 +32,12 @@ export class LeafletMap extends LitElement {
@query("#mapid") @query("#mapid")
_mapElement!: HTMLDivElement; _mapElement!: HTMLDivElement;
@query("#go-to-target-control-button")
_goToTargetButton!: HTMLButtonElement;
@query("#ask-permission-control-button")
_askPermissionButton!: HTMLButtonElement;
// Properties and states // Properties and states
@property({ type: Object, noAccessor: true }) targetPosition?: LatLngTuple; @property({ type: Object, noAccessor: true }) targetPosition?: LatLngTuple;
@property({ type: Object }) @property({ type: Object })
currentPosition?: LatLngTuple; currentPosition?: LatLngTuple;
@state()
protected _map?: L.Map; protected _map?: L.Map;
@state()
protected _currentLocationMarker?: L.Marker; protected _currentLocationMarker?: L.Marker;
firstUpdated(): void { firstUpdated(): void {

View File

@ -39,7 +39,7 @@ export class LockedContent extends LitElement {
]; ];
// Components properties/attributes, no accessor attribute disables detecting // Components properties/attributes, no accessor attribute disables detecting
// changes as these are readonly attriubtes there is no need to attach setters // changes as these are readonly attributes there is no need to attach setters
@property({ noAccessor: true }) readonly imageId?: string; @property({ noAccessor: true }) readonly imageId?: string;
@property({ noAccessor: true }) readonly imageURL?: string; @property({ noAccessor: true }) readonly imageURL?: string;
@property({ type: Object, noAccessor: true }) @property({ type: Object, noAccessor: true })
@ -73,7 +73,7 @@ export class LockedContent extends LitElement {
} }
private _dispatchAskPermissionEvent() { private _dispatchAskPermissionEvent() {
const event = new Event("askpermission"); const event = new Event("askpermission", { bubbles: true, composed: true });
this.dispatchEvent(event); this.dispatchEvent(event);
} }

View File

@ -70,8 +70,12 @@ const dateFromNow = dayjs.utc(data?.created_at).from(dayjs.utc());
imageURL={`http://localhost:3000/images/${data?.blob_url}`} imageURL={`http://localhost:3000/images/${data?.blob_url}`}
targetPosition={data?.loc}></locked-content> targetPosition={data?.loc}></locked-content>
<leaflet-map id="leaflet-map-component" targetPosition={data?.loc} <div
></leaflet-map> id="map"
class="w-full h-[450px] rounded"
data-target-location={data?.loc}
>
</div>
<ShareButton client:only /> <ShareButton client:only />
<div class="flex justify-center"> <div class="flex justify-center">
@ -81,6 +85,10 @@ const dateFromNow = dayjs.utc(data?.created_at).from(dayjs.utc());
</div> </div>
</main> </main>
<script> <script>
import { errorCallback } from "@/components/LockedContent/geolocation";
import { onLocationSuccess } from "@/scripts/initMap";
let watchId: number;
function updateCurrentLocation(position: GeolocationPosition) { function updateCurrentLocation(position: GeolocationPosition) {
const lockedContent = document.getElementById("locked-content-component"); const lockedContent = document.getElementById("locked-content-component");
if (lockedContent) { if (lockedContent) {
@ -90,13 +98,7 @@ const dateFromNow = dayjs.utc(data?.created_at).from(dayjs.utc());
); );
} }
const leafletMap = document.getElementById("leaflet-map-component"); onLocationSuccess(position);
if (leafletMap) {
leafletMap.setAttribute(
"currentPosition",
`[${position.coords.latitude}, ${position.coords.longitude}]`
);
}
} }
navigator.permissions navigator.permissions
@ -104,7 +106,10 @@ const dateFromNow = dayjs.utc(data?.created_at).from(dayjs.utc());
.then((permissionStatus) => { .then((permissionStatus) => {
switch (permissionStatus.state) { switch (permissionStatus.state) {
case "granted": case "granted":
window.navigator.geolocation.watchPosition(updateCurrentLocation); watchId = window.navigator.geolocation.watchPosition(
updateCurrentLocation,
errorCallback
);
break; break;
case "denied": case "denied":
case "prompt": case "prompt":
@ -114,9 +119,14 @@ const dateFromNow = dayjs.utc(data?.created_at).from(dayjs.utc());
}); });
window.addEventListener("askpermission", () => { window.addEventListener("askpermission", () => {
console.log("ask permission"); if (!watchId) {
watchId = window.navigator.geolocation.watchPosition(
updateCurrentLocation,
errorCallback
);
}
}); });
</script> </script>
<script src="../components/locked-content.ts"></script> <script src="../components/locked-content.ts"></script>
<script src="../components/leaflet-map.ts"></script> <script src="../scripts/initMap.ts"></script>
</Layout> </Layout>

View File

@ -30,54 +30,12 @@ L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
'&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>', '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
}).addTo(map); }).addTo(map);
map.on("locationerror", onLocationError);
map.on("locationfound", onLocationSuccess);
let currentLocationMarker: L.Marker; let currentLocationMarker: L.Marker;
function onLocationError(err: L.ErrorEvent) { export function onLocationSuccess(position: GeolocationPosition) {
let errorMessage;
switch (err.code) {
case 1:
errorMessage =
"Konum izni alınamadı, lütfen tarayıcınızın ve cihazınızın gizlilik ayarlarını kontrol edin.";
break;
case 2:
errorMessage =
"Konumunuz tespit edilemedi, lütfen biraz sonra tekrar deneyiniz.";
break;
case 3:
errorMessage =
"Konum isteği zaman aşımına uğradı, lütfen sayfayı yenileyip tekrar deneyiniz.";
break;
default:
errorMessage =
"Konum izni alınamadı, lütfen tarayıcınızın ve cihazınızın gizlilik ayarlarını kontrol edin.";
break;
}
// @ts-ignore
Toastify({
text: errorMessage,
duration: 3000,
gravity: "top", // `top` or `bottom`
position: "center", // `left`, `center` or `right`
stopOnFocus: true, // Prevents dismissing of toast on hover
style: {
background: "black",
borderRadius: "6px",
margin: "16px",
},
onClick: function () {}, // Callback after click
}).showToast();
}
function onLocationSuccess(locationEvent: L.LocationEvent) {
const position = locationEvent.latlng;
const currentPos = { const currentPos = {
lat: position.lat, lat: position.coords.latitude,
lng: position.lng, lng: position.coords.longitude,
}; };
if (currentLocationMarker) { if (currentLocationMarker) {
@ -88,29 +46,7 @@ function onLocationSuccess(locationEvent: L.LocationEvent) {
} }
} }
// @ts-ignore L.Control allows extensions const CurrentLocation = L.Control.extend({
L.Control.AskPermisson = L.Control.extend({
onAdd: function () {
const locationButton = document.createElement("button");
locationButton.textContent = "Konum İzni Ver";
locationButton.classList.add("custom-map-control-button");
locationButton.type = "button";
locationButton.addEventListener("click", (ev) => {
startWatchingLocation();
locationButton.textContent = "Konumuma Git";
L.DomEvent.stopPropagation(ev);
});
return locationButton;
},
});
// @ts-ignore L.Control allows extensions
L.Control.CurrentLocation = L.Control.extend({
onAdd: function (map: L.Map) { onAdd: function (map: L.Map) {
const locationButton = document.createElement("button"); const locationButton = document.createElement("button");
@ -120,35 +56,17 @@ L.Control.CurrentLocation = L.Control.extend({
locationButton.type = "button"; locationButton.type = "button";
locationButton.addEventListener("click", (ev) => { locationButton.addEventListener("click", () => {
if (currentLocationMarker) { if (currentLocationMarker) {
map.setView(currentLocationMarker.getLatLng(), 12); map.setView(currentLocationMarker.getLatLng(), 12);
} else {
// @ts-ignore
Toastify({
text: "Konum izni alınamadı, lütfen tarayıcınızın ve cihazınızın gizlilik ayarlarını kontrol edin.",
duration: 3000,
gravity: "top", // `top` or `bottom`
position: "center", // `left`, `center` or `right`
stopOnFocus: true, // Prevents dismissing of toast on hover
style: {
background: "black",
borderRadius: "6px",
margin: "16px",
},
onClick: function () {}, // Callback after click
}).showToast();
} }
L.DomEvent.stopPropagation(ev);
}); });
return locationButton; return locationButton;
}, },
}); });
// @ts-ignore L.Control allows extensions const GoToTargetLocation = L.Control.extend({
L.Control.GoToTargetLocation = L.Control.extend({
onAdd: function (map: L.Map) { onAdd: function (map: L.Map) {
const locationButton = document.createElement("button"); const locationButton = document.createElement("button");
@ -164,36 +82,11 @@ L.Control.GoToTargetLocation = L.Control.extend({
}, },
}); });
// @ts-ignore L.Control allows extensions const goToCurrentLocationControl = new CurrentLocation({
L.control.askPermission = function (opts) {
// @ts-ignore L.Control allows extensions
return new L.Control.AskPermisson(opts);
};
// @ts-ignore L.Control allows extensions
L.control.goToCurrentLocation = function (opts) {
// @ts-ignore L.Control allows extensions
return new L.Control.CurrentLocation(opts);
};
// @ts-ignore L.Control allows extensions
L.control.targetLocation = function (opts) {
// @ts-ignore L.Control allows extensions
return new L.Control.GoToTargetLocation(opts);
};
// @ts-ignore L.Control allows extensions
const goToCurrentLocationControl = L.control.goToCurrentLocation({
position: "bottomleft", position: "bottomleft",
}); });
// @ts-ignore L.Control allows extensions const targetLocationControl = new GoToTargetLocation({
const askPermissionControl = L.control.askPermission({
position: "bottomleft",
});
// @ts-ignore L.Control allows extensions
const targetLocationControl = L.control.targetLocation({
position: "bottomleft", position: "bottomleft",
}); });
@ -210,29 +103,9 @@ function addTargetLocationMarker(target: TargetLocation) {
} }
} }
function startWatchingLocation() {
goToCurrentLocationControl.addTo(map);
askPermissionControl.remove();
}
function initLocationControls() { function initLocationControls() {
targetLocationControl.addTo(map); targetLocationControl.addTo(map);
// Check geolocation permission, if user has given permission before goToCurrentLocationControl.addTo(map);
// start watching user location
navigator.permissions
.query({ name: "geolocation" })
.then((permissionStatus) => {
switch (permissionStatus.state) {
case "granted":
startWatchingLocation();
break;
case "denied":
case "prompt":
askPermissionControl.addTo(map);
default:
break;
}
});
} }
addTargetLocationMarker(TARGET_LOCATION); addTargetLocationMarker(TARGET_LOCATION);