Autocomplete Location Search using Google Maps JavaScript API and jQuery


Location search box helps to find the exact location that the user wants to provide. Generally, HTML input box is used to get the address from the user, where the user needs to enter their address manually. But if you want to make location input box more user-friendly, autocomplete location search box is a great option. Using autocomplete address search box, the user can select their exact location on Google Map.

In this tutorial, we will show you how to implement autocomplete location search box functionality in the web application using Google Maps JavaScript API, jQuery and jQuery UI. In the example script, we will implement the following functionalities.

  • Autocomplete location search box.
  • Point the location with a marker on Google map.
  • Change marker position on location change.
  • Get latitude, longitude, and address of the selected location.
  • Location change by marker drag&drop.

Bootstrap Library

The example script uses Bootstrap library to styling the search input field and button. If you don’t want to use Bootstrap library, not need to include it.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

jQuery & jQuery UI Library

The jQuery is used to get and set the location information, so include the jQuery library. And the jQuery UI library is used to add autocomplete feature to the location search box.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

Google Maps JavaScript API

Google Maps JavaScript API is used to get the location info (address, latitude, and longitude) and display map. You need to create an API key in Google Developers Console and enable Google Maps Geocoding API library. Specify this API key in API URL for using the Google Maps JavaScript API.

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>

See this step-by-step instruction to get your own API key – How to Get Google Maps JavaScript API Key

JavaScript Code

The JavaScript code has the following four sections.

  • The initialize() method creates a Google map and points a location with a marker on Google map. Initially, a default position is shown on the map. But if any location is selected by the autocomplete box, this position will be shown on the Google Map. Also, the respective address, latitude, and longitude are display under the Google Map.
  • In the second section, the autocomplete functionality is added to the input box (search_location). On selecting an address from autocomplete box, the respective location will be shown on the Google map with a marker. Also, the respective address, latitude, and longitude are display under the Google Map.
  • The third section is triggered when the Locate button (get_map) is clicked. The Geo location data is fetched based on the given address and shows on the Google map with a marker. Also, the respective address, latitude, and longitude are display under the Google Map.
  • The fourth section is used to change the location when the marker position is changed by drag & drop.
<script>
var geocoder;
var map;
var marker;

/*
 * Google Map with marker
 */
function initialize() {
    var initialLat = $('.search_latitude').val();
    var initialLong = $('.search_longitude').val();
    initialLat = initialLat?initialLat:36.169648;
    initialLong = initialLong?initialLong:-115.141000;

    var latlng = new google.maps.LatLng(initialLat, initialLong);
    var options = {
        zoom: 16,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("geomap"), options);

    geocoder = new google.maps.Geocoder();

    marker = new google.maps.Marker({
        map: map,
        draggable: true,
        position: latlng
    });

    google.maps.event.addListener(marker, "dragend", function () {
        var point = marker.getPosition();
        map.panTo(point);
        geocoder.geocode({'latLng': marker.getPosition()}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                marker.setPosition(results[0].geometry.location);
                $('.search_addr').val(results[0].formatted_address);
                $('.search_latitude').val(marker.getPosition().lat());
                $('.search_longitude').val(marker.getPosition().lng());
            }
        });
    });

}

$(document).ready(function () {
    //load google map
    initialize();
    
    /*
     * autocomplete location search
     */
    var PostCodeid = '#search_location';
    $(function () {
        $(PostCodeid).autocomplete({
            source: function (request, response) {
                geocoder.geocode({
                    'address': request.term
                }, function (results, status) {
                    response($.map(results, function (item) {
                        return {
                            label: item.formatted_address,
                            value: item.formatted_address,
                            lat: item.geometry.location.lat(),
                            lon: item.geometry.location.lng()
                        };
                    }));
                });
            },
            select: function (event, ui) {
                $('.search_addr').val(ui.item.value);
                $('.search_latitude').val(ui.item.lat);
                $('.search_longitude').val(ui.item.lon);
                var latlng = new google.maps.LatLng(ui.item.lat, ui.item.lon);
                marker.setPosition(latlng);
                initialize();
            }
        });
    });
    
    /*
     * Point location on google map
     */
    $('.get_map').click(function (e) {
        var address = $(PostCodeid).val();
        geocoder.geocode({'address': address}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                marker.setPosition(results[0].geometry.location);
                $('.search_addr').val(results[0].formatted_address);
                $('.search_latitude').val(marker.getPosition().lat());
                $('.search_longitude').val(marker.getPosition().lng());
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
        e.preventDefault();
    });

    //Add listener to marker for reverse geocoding
    google.maps.event.addListener(marker, 'drag', function () {
        geocoder.geocode({'latLng': marker.getPosition()}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    $('.search_addr').val(results[0].formatted_address);
                    $('.search_latitude').val(marker.getPosition().lat());
                    $('.search_longitude').val(marker.getPosition().lng());
                }
            }
        });
    });
});
</script>

If you want to add restriction by the country, specify componentRestrictions option in geocode() method. For example, you want to show the addresses only from the USA on autocomplete box, the geocoder.geocode() need to be defined like the below.

geocoder.geocode({
    'address': request.term,
    componentRestrictions: {country: "us"}
})

HTML Code

The input field is used to search address and the Locate button is used to get the location information based on the given address. The Google Map is displayed under the geomap div. The rest of the HTML is used to display the location information (address, latitude, and longitude).

<!-- search input box -->
<form>
<div class="form-group input-group">
    <input type="text" id="search_location" class="form-control" placeholder="Search location">
    <div class="input-group-btn">
        <button class="btn btn-default get_map" type="submit">
            Locate
        </button>
    </div>
</div>
</form>

<!-- display google map -->
<div id="geomap"></div>

<!-- display selected location information -->
<h4>Location Details</h4>
<p>Address: <input type="text" class="search_addr" size="45"></p>
<p>Latitude: <input type="text" class="search_latitude" size="30"></p>
<p>Longitude: <input type="text" class="search_longitude" size="30"></p>

CSS Code

The following CSS sets the height and width of the Google Map div.

#geomap{
    width: 100%;
    height: 400px;
}

Autocomplete Places Search Box using Google Maps JavaScript API

Conclusion

The example code shows how you can implement an autocomplete location search input box and get latitude & longitude. You can easily extend the functionality of this script as per your needs. If you want to store the user location info (address, latitude, and longitude) in the database, use AJAX to send the location data to the PHP file and insert into the database.

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You

Leave a reply