Last active
November 14, 2022 22:54
-
-
Save badsyntax/4330899 to your computer and use it in GitHub Desktop.
Googe places autocomplete implementation using Twitter bootstrap typeahead and google's autocomplete and geocoding services
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Author: Richard Willis - badsyntax.co | |
* Example here: http://demos.badsyntax.co/places-search-bootstrap/example.html | |
* | |
* Please note: This is not a reliable method of geocoding the address. Using the | |
* PlacesService is a much better approach. View the example above for an example | |
* of using the PlacesService to geocode the address. | |
*/ | |
var service = new google.maps.places.AutocompleteService(); | |
var geocoder = new google.maps.Geocoder(); | |
$(field).typeahead({ | |
source: function(query, process) { | |
service.getPlacePredictions({ input: query }, function(predictions, status) { | |
if (status == google.maps.places.PlacesServiceStatus.OK) { | |
process($.map(predictions, function(prediction) { | |
return prediction.description; | |
})); | |
} | |
}); | |
}, | |
updater: function (item) { | |
geocoder.geocode({ address: item }, function(results, status) { | |
if (status != google.maps.GeocoderStatus.OK) { | |
alert('Cannot find address'); | |
return; | |
} | |
map.setCenter(results[0].geometry.location); | |
map.setZoom(12); | |
}); | |
return item; | |
} | |
}); |
@badsyntax You created a project for it on google developer console and assigned the demo an API key.... then you deleted the project. Probably best just not to have given it an API key in the first place
I think it will be a little late to answer @ronnyandre :) But this would be better. And moreover if any map on page it would be fit bounds to selected suggestions geometry
var geocoder = new google.maps.Geocoder();
$('.typeahead').typeahead({
autoselect: true,
minLength: 4,
},{
name: 'google',
displayKey: 'address',
templates: {
header: '<h5 class="typeahead-header">Google Results</h5>'
},
source: function (q, sync, async){
geocoder.geocode({ address: q }, function (results, status) {
for (var i = results.length - 1; i >= 0; i--) {
async([{address:results[i].formatted_address, geometry:results[i].geometry}]);
}
});
}
}
).on('typeahead:selected', function (obj, datum) {
if(datum)
{
var geometry = datum.geometry;
map.fitBounds(geometry.bounds? geometry.bounds : geometry.viewport);
}
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thx for sharing! :)