Geolocation and Map App with Leaflet.js

29 Oct 2024 10:54 AM

In this guide, we’ll build an interactive Geolocation Map App using Leaflet.js, a lightweight library for web mapping. The app will display your current location on a map and allow users to add markers dynamically.

Step 1: Set Up Project Files

/LeafletMapApp  
│
├── index.html  
├── styles.css  
└── script.js  

Step 2: Add HTML (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Geolocation Map App</title>
  <link rel="stylesheet" href="styles.css">
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
</head>
<body>
  <h1>My Location Map</h1>
  <div id="map"></div>
  <button id="locate-btn">Locate Me</button>
  <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
  <script src="script.js"></script>
</body>
</html>

Step 3: Add CSS Styles (styles.css)

body {
  margin: 0;
  font-family: Arial, sans-serif;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f0f0f0;
}

h1 {
  margin-top: 10px;
}

#map {
  width: 80%;
  height: 500px;
  margin: 20px 0;
  border-radius: 10px;
}

button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

Step 4: Add JavaScript Logic (script.js)

// Initialize the Leaflet map
const map = L.map('map').setView([51.505, -0.09], 13);

// Set up the tile layer (Mapbox, OpenStreetMap, or another provider)
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

// Function to add a marker at a given location
function addMarker(lat, lng) {
  L.marker([lat, lng]).addTo(map)
    .bindPopup('You are here!')
    .openPopup();
}

// Locate the user’s position when the button is clicked
document.getElementById('locate-btn').addEventListener('click', () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(position => {
      const { latitude, longitude } = position.coords;
      map.setView([latitude, longitude], 15); // Move map to the user's location
      addMarker(latitude, longitude); // Add a marker at the user's location
    }, () => {
      alert('Unable to retrieve your location.');
    });
  } else {
    alert('Geolocation is not supported by your browser.');
  }
});

Step 5: Test the App

  1. Open index.html in your browser.
  2. Click “Locate Me” to move the map to your current location.
  3. A marker will be added at your position with a popup message.

Explanation

  1. Leaflet.js Setup:

    • The tile layer uses OpenStreetMap tiles to render the map.
    • The map object is initialized with a center coordinate and zoom level.
  2. Geolocation API:

    • The navigator.geolocation API retrieves the user’s coordinates.
    • The map centers on the user’s position, and a marker is added dynamically.
  3. User Interaction:

    • A button triggers geolocation to ensure user control over location access.

Possible Enhancements

  • Custom Markers: Use custom icons instead of the default markers.
  • Save Markers: Store markers in local storage or a database.
  • Directions API: Use a service like Mapbox for routing and directions.
  • Clustering: Add marker clustering for multiple points.

Conclusion

This app combines Leaflet.js and the Geolocation API to build a practical, interactive web map. It demonstrates how to visualize user locations and interact with maps dynamically. Let me know if you want to explore more advanced features like marker clustering or routing!

 

 

 

1
11