This is the code I am working from:
var GeoCoded = {done: false};
$(document).ready(function(){
console.log('ready!');
autosuggest();
console.log($('#myform input[type="submit"]'));
$('#myform').on('submit',function(e){
if(GeoCoded.done)
return true;
e.preventDefault();
console.log('submit stopped');
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('location').value;
$('#myform input[type="submit"]').attr('disabled',true);
geocoder.geocode({
'address': address
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
//if you only want to submit in the event of successful geocoding, you can only trigger submission here.
GeoCoded.done = true;
$('#myform').submit();
} else {
console.log("Geocode was not successful for the following reason: " + status);
//enable the submit button
$('#myform input[type="submit"]').attr('disabled',false);
}
});
});
});
This works how I want BUT, I wanted to complete the geocode when someone clicks on the autocomplete. So, when they type something and click on a suggestion from the autosuggest list, it actually completes the geocode call when the click the result.
If anyone could tell me if this is possible I would really appreciate it, because I havent been able to figure out how to do it myself.
Autocomplete incorporates geocoding automatically. Example here.
Edit:
Here is the gist of that example:
The key lines for creating the autocomplete control are:
var input = document.getElementById('searchTextField');
var options = {
types: [],
componentRestrictions: {country: 'us'}
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
You also need to load the Places library:
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
and in your HTML:
<input id="searchTextField" type="text" size="50" value="">
By the way, you don't "add autocomplete to the geocoder".The Places Autocomplete class includes geocoding capabilities.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.