🚀 DevOps Certified Professional
📅 Starting: 1st of Every Month 🤝 +91 8409492687 | 🤝 +1 (469) 756-6329 🔍 Contact@DevOpsSchool.com

Adding an Auto-Complete Address Field to your Forms (Laravel)

DevOpsLaravel

Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

What we are building

First of all we need to get a google maps API, go through this documentation to get an API of your own.

we need Geocoding API and Maps JavaScript API

Next thing we need to do is to put a initializing script in our blade file

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initAutocomplete&libraries=places&v=weekly"async></script>
  • Make sure to provide your api key in the script

The above script will call a method name initAutocomplete that we have to write in our .js file

<form> 
   <div class="row mt-3">
     <div class="col-md-12">
       <input type="text" id="address-input" name="address1" class="form-control" value="">
      <input type="hidden" name="address_latitude" id="address-latitude" value="" required/ >
      <input type="hidden" name="address_longitude" id="address-longitude" value="" required/>
     </div>
   </div>
   <div><button class="btn btn-primary" type="submit">Save Profile</button>
 </div>
</form>
  • Make sure you form have these matching selectors
// This method will be initialised by our script call-back
function initAutocomplete() {
$('form').on('keyup keypress', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.preventDefault();
return false;
}
});
// here we are getting the input keywords in locationInput constant
const locationInputs = document.getElementsByClassName("map-input");
const autocompletes = [];
const geocoder = new google.maps.Geocoder;
for (let i = 0; i < locationInputs.length; i++) {
const input = locationInputs[i];
const fieldKey = input.id.replace("-input", "");
const isEdit = document.getElementById(fieldKey + "-latitude").value != '' && document.getElementById(fieldKey + "-longitude").value != '';
const latitude = parseFloat(document.getElementById(fieldKey + "-latitude").value) || -33.8688;
const longitude = parseFloat(document.getElementById(fieldKey + "-longitude").value) || 151.2195;
const autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.key = fieldKey;
autocompletes.push({input: input , autocomplete: autocomplete});
// manipulating our latitude and longitude to send it to autocomplete method
}
for (let i = 0; i < autocompletes.length; i++) {
const input = autocompletes[i].input;
const autocomplete = autocompletes[i].autocomplete;
google.maps.event.addListener(autocomplete, 'place_changed', function () {
const place = autocomplete.getPlace();
// this place variable will fetch the places mathed to your keyword
geocoder.geocode({'placeId': place.place_id}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
const lat = results[0].geometry.location.lat();
const lng = results[0].geometry.location.lng();
setLocationCoordinates(autocomplete.key, lat, lng);
}
});
if (!place.geometry) {
alert("No details available for input: '" + place.name + "'");
input.value = "";
return;
}
});
}
}
function setLocationCoordinates(key, lat, lng) {
const latitudeField = document.getElementById(key + "-" + "latitude");
const longitudeField = document.getElementById(key + "-" + "longitude");
latitudeField.value = lat;
longitudeField.value = lng;
console.log(lat);
console.log(lng);
}

What i have done in above code

  • In the above code the first method initAutocomplete() method is initializing by our script call-back
  • Next thing we are getting the input keywords in locationInput constant
  • Then with the help of geocoder we are manipulating our provided key word to form let long and
  • Next we initializing autocomplete = new google.maps.places.Autocomplete(input);
  • At the end we are getting the provide address in our place variable
  • There is an another method setLocationCoordinates() i used this method to set let long so that I can store the co-ordinates along with the address in DB

That’s it, hope this help ;