Implementing a Map with Latitude and Longitude in JavaScript

Introduction

Today's web applications would be incomplete without interactive maps, which give users simple ways to explore and engage with geographic data. Using Leaflet, a lightweight JavaScript library, and geolocation to determine the user's current location on the map, we will build dynamic and interactive maps in this Article.

HTML Structure

by adding together the program's HTML framework. For users to enter their latitude, longitude, state, city, and pincode, we'll include form elements. We'll also make an element to show the map.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>

<div class="row">
    <div class="col-lg-7 col-md-7 col-12">
        <form method="post" role="form" id="RegisterPOS" class="php-email-form">
            <div class="row">
                <div class="col-md-6 col-12 form-group mt-3">
                    <input type="text" name="Latitude" class="form-control" id="Latitude" placeholder="Latitude" required>
                    <div class="invalid-feedback">Please enter latitude.</div>
                </div>
                <div class="col-md-6 col-12 form-group mt-3">
                    <input type="text" name="Longitude" class="form-control" id="Longitude" placeholder="Longitude" required>
                    <div class="invalid-feedback">Please enter longitude.</div>
                </div>
                <div class="col-md-6 col-12 form-group mt-3">
                    <input type="text" name="State" class="form-control" id="State" placeholder="State" required>
                    <div class="invalid-feedback">Please enter state.</div>
                </div>
                <div class="col-md-6 col-12 form-group mt-3">
                    <input type="text" name="City" class="form-control" id="City" placeholder="City" required>
                    <div class="invalid-feedback">Please enter city.</div>
                </div>
                <div class="col-md-6 col-12 form-group mt-3">
                    <input type="text" name="Pincode" class="form-control" id="Pincode" placeholder="Pincode" required>
                    <div class="invalid-feedback">Please enter pincode.</div>
                </div>
            </div>
        </form>
    </div>
    <div class="col-lg-5 col-md-5 col-12">
        <div class="row">
            <div class="col-md-12">
                <div id="map" style="height: 400px;"></div>
            </div>
        </div>
    </div>
</div>

CSS styling

Let's apply some CSS styling to make sure our map looks good and fits nicely in the layout. We'll configure the map container's height, width, and border radius.

 #map {
        height: 100px;
        WIDTH: 100px;
        border-radius: 8px;
    }

Implementing Leaflet JavaScript

Now let's look at the JavaScript code that initializes the Leaflet map and uses geolocation to place the user.

  var map = L.map('map');
 // Add a base map layer (you can choose any tile layer you prefer)
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{
       
    }).addTo(map);

    var marker = L.marker([0, 0], {
        draggable: true // Allow marker to be dragged
    }).addTo(map);
    window.onload = function () {
        getLocation();
    };
    function getLocation() {
        if (navigator.geolocation) {
           
            navigator.geolocation.getCurrentPosition(function (position)
            {
                var latitude = position.coords.latitude;
                var longitude = position.coords.longitude;
                document.getElementById("Latitude").value = latitude;
                document.getElementById("Longitude").value = longitude;
                var userLatLng = [position.coords.latitude, position.coords.longitude];
                map.setView(userLatLng, 13); // Set map view to user's location
                marker.setLatLng(userLatLng); 
                // Fetch address details using OpenStreetMap Nominatim API
                fetch(`https://nominatim.openstreetmap.org/reverse?lat=${latitude}&lon=${longitude}&format=json`)
                    .then(response => response.json())
                    .then(data => {
                        var address = data.address;
                        console.log(address);
                        var district = address.state_district.replace(" District", "");

                        document.getElementById("City").value = district;
                        document.getElementById("State").value = address.state;
                        document.getElementById("Pincode").value = address.postcode;

                    })
                    .catch(error => console.error("Error fetching address details:", error));
            },
                function (error) {
                console.error("Error getting user location:", error.message);
            });
        } else {
            alert("Geolocation is not supported by this browser.");
        }
    }

Output

Output

Conculsion

We've implemented Leaflet in JavaScript to successfully create a map with latitude and longitude markers. If more markers, popups, or overlays are needed, you can further alter the map to suit your needs. With the many features Leaflet provides, you can easily create dynamic and interactive maps for your online applications.


Similar Articles