Demo Autocomplete
by Robert Dodd
HTML
<script src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<form id="searchform" name="searchform" onSubmit="return validateForm()">
<input type="text" name="searchfield" id="searchfield" /><br/>
<input type="hidden" name="placeinfo" id="placeinfo" />
<input type="submit" value="Search" /><br/>
</form>
<div id="placename"></div>
<div id="map_canvas" class="gmap border_box"></div>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
CSS
.gmap {
width:100%;
height:250px;
border: 1px solid #4D2722;
}
.border_box {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
JavaScript
var map;
var service;
var infowindow;
var service;
var place;
var placesearch;
function initialize() {
//set up google map
map = new google.maps.Map(document.getElementById('map_canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(-27.420538,153.028107),
zoom: 10
});
//initialize places service to perform TextSearch
service = new google.maps.places.PlacesService(map);
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
var input = document.getElementById('searchfield');
var options = {
bounds: defaultBounds,
types: []
};
autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
place = autocomplete.getPlace();
placesearch = $('#searchfield').val();
if (!place.geometry) {
// Inform the user that a place was not found and return.
return;
}
updateMap();
});
}
function updateMap() {
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
// Use the viewport if it is provided.
map.fitBounds(place.geometry.viewport);
} else {
// Otherwise use the location and set a chosen zoom level.
map.setCenter(place.geometry.location);
map.setZoom(17);
}
}
function validateForm() {
searchfield = $('#searchfield').val();
if (searchfield == "" || searchfield == null) {
// No text entered
alert('Please enter text');
return false;
} else if (place && searchfield == placesearch) {
// Success
// return true to submit the form
updateMap();
alert('WADDUP!! Form submitted successfully bru!');
place = null;
placesearch = "";
...