Home / Widgets / To create the map and mapper as written by kodee
Duplicate Snippet

Embed Snippet on Your Site

To create the map and mapper as written by kodee

Code Preview
js
document.addEventListener('DOMContentLoaded', function () {
    const map = L.map('treasure-map').setView([51.5033, -0.1196], 12);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);
    const items = document.querySelectorAll('.treasure-item');
    const markers = [];
    items.forEach(function (item) {
        const lat = Number(item.dataset.lat);
        const lng = Number(item.dataset.lng);
        if (!Number.isFinite(lat) || !Number.isFinite(lng)) return;
        const marker = L.marker([lat, lng])
            .addTo(map)
            .bindPopup(item.dataset.title || 'Free item');
        markers.push({ marker, lat, lng, item });
    });
    document.getElementById('locate-me').addEventListener('click', function () {
        if (!navigator.geolocation) {
            alert('Location is not supported by this browser.');
            return;
        }
        navigator.geolocation.getCurrentPosition(function (position) {
            const userLat = position.coords.latitude;
            const userLng = position.coords.longitude;
            L.circleMarker([userLat, userLng], {
                radius: 8,
                color: '#1769aa',
                fillColor: '#1769aa',
                fillOpacity: 0.8
            }).addTo(map).bindPopup('Your location').openPopup();
            map.setView([userLat, userLng], 13);
            markers.forEach(function (entry) {
                const distance = map.distance(
                    [userLat, userLng],
                    [entry.lat, entry.lng]
                );
                entry.item.hidden = distance > 10000;
                entry.marker.setOpacity(distance <= 10000 ? 1 : 0.25);
            });
        }, function () {
            alert('Location permission was not granted.');
        });
    });
});

Comments

Add a Comment