Building an Interactive Map with Auto-Location using Google Maps JavaScript API

In the of web development, integrating maps into your applications can offer valuable location-based features. we can create a web page that features an interactive map with automatic user location detection and a search bar using the Google Maps JavaScript API.


Here is an example//Initializing the Google Maps JavaScript API

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> 
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAA2ukvrb1kWQZ2dttsNIMynLJqVCYYrhw&libraries=places&callback=initMap" async defer></script>
 <script>
        var map;
        var markers = [];


     $(document).ready(function () {
        initMap();
        setupAutocomplete();
    });

    function initMap() {
        map = new google.maps.Map(document.getElementById('google-map'), {
            zoom: 9,
            center: { lat: 17.441902, lng: 78.394285 }
        });
    }

    function searchLocation() {
        var locationInput = document.getElementById('searched_bar').value;
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'address': locationInput }, function (results, status) {
            if (status == 'OK' && results[0]) {
                var location = results[0].geometry.location;

                // Clear and add markers (assuming you have these functions defined)
                clearMarkers();
                addMarker(location, locationInput);

                map.setCenter(location);
                map.setZoom(15);
            } else {
                console.error('Error geocoding address:', status);

                // Provide user-friendly error feedback on the webpage
                alert('Error finding location. Please try again.');
            }
        });
    }

    function setupAutocomplete() {
        var input = document.getElementById('searched_bar');
        var searchBox = new google.maps.places.SearchBox(input);

        map.addListener('bounds_changed', function () {
            searchBox.setBounds(map.getBounds());
        });

        searchBox.addListener('places_changed', function () {
            var places = searchBox.getPlaces();

            if (places.length === 0) {
                return;
            }

            places.forEach(function (place) {
                if (!place.geometry) {
                    console.log('Returned place contains no geometry');
                    return;
                }
            });
        });
    }


     
function addMarker(location, name) {
    var latLng = location.split(",");
    var lat = parseFloat(latLng[0]);
    var lng = parseFloat(latLng[1]);


    var marker = new google.maps.Marker({
        position: { lat: lat, lng: lng },
        map: map,
        title: name
    });

    markers.push(marker);
}

   function clearMarkers() {
            for (var i = 0; i < markers.length; i++) {
                markers[i].setMap(null);
            }
            markers = [];
        }
       

    
Sign In or Register to comment.