public

Google Maps API + Places AutoComplete JS

  • Download Gist
google_maps_places_autocomplete.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
$(document).ready(function()
{
$('blockquote.text').expander();
function initialize() {
var mapDiv = $('#map_canvas');
var lat = mapDiv.data('latitude'),
lng = mapDiv.data('longitude');
var mapOptions = {
center: new google.maps.LatLng(lat,lng),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
 
var input = document.getElementById('search');
var autocomplete = new google.maps.places.Autocomplete(input);
 
autocomplete.bindTo('bounds', map);
 
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
 
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(16); // Why 17? Because it looks good.
}
 
var image = new google.maps.MarkerImage(
place.icon,
new google.maps.Size(71, 71),
new google.maps.Point(0, 0),
new google.maps.Point(17, 34),
new google.maps.Size(35, 35));
marker.setIcon(image);
marker.setPosition(place.geometry.location);
 
var address = '';
if (place.address_components) {
address = [(place.address_components[0] &&
place.address_components[0].short_name || ''),
(place.address_components[1] &&
place.address_components[1].short_name || ''),
(place.address_components[2] &&
place.address_components[2].short_name || '')
].join(' ');
}
 
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
google.maps.event.addListener(marker, 'click', function() {
return place
});
});
 
}
google.maps.event.addDomListener(window, 'load', initialize);
 
 
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.