Limit (Restrict) Google AutoComplete result to City only in JavaScript

Last Reply 2 months ago By dharmendr

Posted 2 months ago

i use google auto complete to show address but i want to show only city not complete address like mumbai, patna etc not complete address

pls advice

    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&sensor=false&key=AIzaSyD_Ia-RHd5bIWM"></script>
    <script type="text/javascript">
        google.maps.event.addDomListener(window, 'load', function () {
            var places = new google.maps.places.Autocomplete(document.getElementById('<%=txtaddress.ClientID%>'));
            google.maps.event.addListener(places, 'place_changed', function () {
                var place = places.getPlace();
                var address = place.formatted_address;
                var latitude = place.geometry.location.lat();
                var longitude = place.geometry.location.lng();
                var mesg = "Address: " + address;
                mesg += "\nLatitude: " + latitude;
                mesg += "\nLongitude: " + longitude;
                //alert(mesg);
            });
        });
    </script>
You are viewing reply posted by: dharmendr 2 months ago.
Posted 2 months ago

Hi nauna,

Check this example. Now please take its reference and correct your code.

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&key=API_KEY"></script>
    <script type="text/javascript">
        google.maps.event.addDomListener(window, 'load', function () {
            var options = { types: ['(cities)'] };
            var places = new google.maps.places.Autocomplete(document.getElementById('txtAddress'), options);
            google.maps.event.addListener(places, 'place_changed', function () {
                var place = places.getPlace();
                var address = place.formatted_address;
                var latitude = place.geometry.location.lat();
                var longitude = place.geometry.location.lng();
                var mesg = "Address: " + address;
                mesg += "\nLatitude: " + latitude;
                mesg += "\nLongitude: " + longitude;
                alert(mesg);
            });
        });
    </script>
</head>
<body>
    <input type="text" id="txtAddress" />
</body>
</html>

Screenshot