I am building a dashboard for a potential package tracking application. I am using Leaflet and OpenStreetMap for now.
I am trying to fetch the user's current location and show it on the map. Unfortunately, when I fetch the location, the map goes blank. See the attached images. When the location is fetched, you'll see a blue dot. I don't understand what am I doing wrong. I have attached the relevant code here:
HTML:
I have included this in head: <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
<div id="map"></div>
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
Then closed the body and other tags.
CSS:
/* Map Container */
#map {
height: 500px;
width: 100%;
max-width: 800px;
margin: 20px 10px;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
float: right;
}
.leaflet-popup-tip-container {
display: none; /* Hide the default popup tip */
}
.leaflet-popup-content-wrapper {
border-radius: 10px; /* Optional: Rounded corners for the popup */
}
JavaScript:
// Initialize and add the map
function initMap() {
const map = L.map("map").setView([12.9716, 77.5946], 10); // Bengaluru
const tileLayer = L.tileLayer(
"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
{
attribution:
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}
).addTo(map); // Immediately add the tile layer
let userMarker = null; // Initialize userMarker as null
if (navigator.geolocation) {
navigator.geolocation.watchPosition(
(position) => {
const lat = position.coords.latitude;
const lng = position.coords.longitude;
// Update the map view
map.setView([lat, lng], 10);
if (!userMarker) {
// Create marker on initial location fetch
userMarker = L.circleMarker([lat, lng], {
color: "blue",
radius: 10,
fillOpacity: 0.5,
}).addTo(map);
// Create and bind the popup (only once)
userMarker
.bindPopup("Your current location.", {
autoClose: true, // Keep popup open on click
closeOnClick: true, // Prevent popup from closing on map click
})
.openPopup();
} else {
// Update existing marker position
userMarker.setLatLng([lat, lng]).openPopup(); // Re-open the popup
}
},
() => {
alert("Unable to retrieve your location.");
}
);
} else {
alert("Geolocation is not supported by your browser.");
}
}
window. Onload = initMap();
Media Assets:
lat < -90 || lat > 90
andlong < -180 || long > 180
? I tried your code here and it works for me.