Create a form
<form action="/location-results" method="get"> <div class="search-field"> <input type="search" placeholder="Enter a suburb, or postcode" id="searchTextField"> <input type="text" name="state_short" id="state_short"> <button type="submit"><img src="201.svg"></button> </div> </form>
Add Script
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places" async defer></script> <script> google.maps.event.addDomListener(window, 'load', function () { //$(window).on("load",function() { const input = document.getElementById('searchTextField'); const option = { componentRestrictions: {country: ["au", "nz"]} } var places = new google.maps.places.Autocomplete(input, option); 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 latlng = new google.maps.LatLng(latitude, longitude); var geocoder = geocoder = new google.maps.Geocoder(); geocoder.geocode({ 'latLng': latlng }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { if (results[0]) { var address = results[0].formatted_address; var state = results[0].address_components[results[0].address_components.length - 3].long_name; var state_short = results[0].address_components[results[0].address_components.length - 3].short_name; var city = results[0].address_components[results[0].address_components.length - 4].long_name; console.log(state+' '+state_short); $('#state_short').val(state_short); } } }); }); }); </script>
Jagdish Sarma Asked question November 28, 2022