detect location using broswer geolocation features

detect location using broswer geolocation features

 

o detect a user's location using the browser's geolocation feature and populate text boxes with location data, you can utilize the browser’s built-in geolocation API in conjunction with a free geocoding service to convert latitude and longitude into human-readable addresses. Here’s a streamlined approach using OpenStreetMap’s Nominatim API for reverse geocoding, which doesn't require an API key.

Step-by-Step Implementation

1. Create the ASP.NET MVC Project

Assuming you have an ASP.NET MVC project set up, you'll need to create a controller and a view.

 

 

@{
    ViewBag.Title = "Detect Location";
}

<h2>Detect Location</h2>

<form id="locationForm">
    <label for="street">Street:</label>
    <input type="text" id="street" name="street" readonly /><br />

    <label for="city">City:</label>
    <input type="text" id="city" name="city" readonly /><br />

    <label for="state">State:</label>
    <input type="text" id="state" name="state" readonly /><br />

    <label for="country">Country:</label>
    <input type="text" id="country" name="country" readonly /><br />
</form>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        // Check if geolocation is supported
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var lat = position.coords.latitude;
                var lon = position.coords.longitude;

                $.ajax({
                    url: `https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lon}&format=json`,
                    method: 'GET',
                    success: function(data) {
                        if (data && data.address) {
                            var address = data.address;

                            $('#street').val(address.road || address.display_name || '');
                            $('#city').val(address.city || address.town || address.village || '');
                            $('#state').val(address.state || '');
                            $('#country').val(address.country || '');
                        }
                    },
                    error: function() {
                        alert('Error retrieving location data.');
                    }
                });
            }, function() {
                alert('Geolocation permission denied.');
            });
        } else {
            alert('Geolocation not supported.');
        }
    });
</script>
 

Share This with your friend by choosing any social account


Upcoming Articles
You may also read following recent Post
Copyright Future Minutes © 2015- 2024 All Rights Reserved.   Terms of Service  |   Privacy Policy |  Contact US|  Pages|  Whats new?
Update on: Dec 20 2023 05:10 PM