Creating a Mobile Map View with Leaflet and Location Marker
In this guide, you will learn how to create an interactive mobile map view using the Leaflet library that uses your browser's current location. We will go step by step through the process of embedding a map, retrieving the location, and placing a marker at the current position.
Step 1: Integration of the required resources
To get started, you need to integrate the Leaflet library into your HTML document. Here is the code you can insert in the <head>
area of your HTML document:
1<head>
2 ...
3 <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
4</head>
5<body>
6 ...
7 <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
8</body>
Step 2: HTML structure
Create an HTML element that serves as a container for your map. Here's an example:
1<div id="map" style="height: 400px;"></div>
Step 3: JavaScript code
Insert the following JavaScript code below the HTML element to initialize the map, retrieve the location, and add a marker:
1<script>
2 const map = L.map('map').setView([0, 0], 15);
3
4 L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
5 maxZoom: 19,
6 attribution: '© OpenStreetMap contributors'
7 }).addTo(map);
8
9 map.locate({ setView: true, maxZoom: 15 });
10
11 function onLocationFound(e) {
12 var marker = L.marker(e.latlng).addTo(map);
13 marker.bindPopup("You are here!").openPopup();
14 }
15
16 map.on('locationfound', onLocationFound);
17
18 function onLocationError(e) {
19 alert("Your location could not be found.");
20 }
21
22 map.on('locationerror', onLocationError);
23</script>
Conclusion
Congratulations! You have successfully created a mobile map view that uses your browser's location and places a marker at your current position. This is a foundation upon which you can build more features and tweaks to make your map view even more interactive.