Skip to content

Instantly share code, notes, and snippets.

@pradeeprjth
Created August 5, 2021 07:34
Show Gist options
  • Save pradeeprjth/64fbf47b6a04f67b17dea57d2fd57ef2 to your computer and use it in GitHub Desktop.
Save pradeeprjth/64fbf47b6a04f67b17dea57d2fd57ef2 to your computer and use it in GitHub Desktop.
// 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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment