Places Autocomplete Validation

Places Autocomplete JQuery Validate Places TextSearch

by Robert Dodd

HTML

<script src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<form id="search-form" >
    <input type="text" name="searchfield" id="searchfield" /><br/>
    <input type="hidden" name="placeref" id="placeref" />
    <input type="submit" value="Search" id="submitbutton" /><br/>
</form>
<hr />
<div id="placename"></div>

<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 service;

var submitted = false;
var validated = false;

var place;
var placesearch;

function initialize() {
    
    var input = document.getElementById('searchfield');
    var options = {
        types: [],
        componentRestrictions: {country: 'au'}
    };
    
    autocomplete = new google.maps.places.Autocomplete(input, options);
    
    google.maps.event.addListener(autocomplete, 'place_changed', function() {
        var p = autocomplete.getPlace();
        if (!p.geometry) {
            // Inform the user that a place was not found and return.
            return;
        }
        place = p;
        placesearch = $('#searchfield').val();
        $('#placeref').val(place.reference);
    });
	
    //initialize places service to perform AutocompletePredictions
	service = new google.maps.places.AutocompleteService();
	
	$("#search-form").validate({
		rules: {
			searchfield: {             // compound rule
				required: true
			},
            placeinfo: {
                required: false
            }
		},
		submitHandler: function(form) {
            if (submitted) {
                return false;
            }
			if (validated || $("#searchfield").val() == placesearch) { 
                
                //disable button
                disableSearch();
                
                $('#placename').text('Success - "' + JSON.stringify(place) + '"');
				alert('valid form submitted');
                validated = false;
                submitted = true;
                // return true;
                
			} else { 

                // address is not validated yet, look up on Google Maps
				var request = {
                    input: $("#searchfield").val(),
                    componentRestrictions: {country: 'au'}
				};
				service.getPlacePredictions(request, predictionsCallback);
                
                //disable button
                disableSearch();
			}
            return false;
		}
	});
}

function disableSearch() {
   ...