Places Search Box
by samunplugged
HTML
<div id="form">
<fieldset class="form">
<legend>
Address (using Google Maps SearchBox autocomplete)
</legend>
<p class="help">
Start typing address below
</p>
<input name="address" id="pac-input" class="controls" type="text" placeholder="Address" >
<input name="city" placeholder="City" />
<input name="state" placeholder="State" maxlength="2" />
<input name="zipcode" placeholder="Zip" maxlength="6" />
</fieldset>
<fieldset class="json">
<legend>
JSON
</legend>
<textarea id="jsonText" name="jsonText" readonly placeholder="(JSON will be displayed when available)"></textarea>
</fieldset>
</div>
<span class="adr_address"></span>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initAutocomplete"
async defer></script>
CSS
#form fieldset.form {
height: 50vh;
overflow-y: scroll;
overflow-x: hidden;
}
#form fieldset.json {
height: 30vh;
overflow: hidden;
}
legend {
font-size: 18px;
}
.help {
color: darkgray;
margin-left: 25px;
}
#form input {
display: block;
margin: 25px;
line-height: 21px;
height: auto;
padding: 0 11px 0 13px;
}
#form input::after {
display: block;
content: '';
clear: both:
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 15px;
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-weight: 300;
text-overflow: ellipsis;
width: 300px;
}
#pac-input:focus {
border-color: #4d90fe;
}
textarea {
width: 100%;
height: 100%;
}
.adr_address {
display: none;
}
JavaScript
function initAutocomplete() {
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var options = {
types: ['(addresses)'],
componentRestrictions: {country: 'us'}
};
var searchBox = new google.maps.places.SearchBox(input, options);
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function(e) {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
var json = JSON.stringify(places[0], null, 4);
var jsonTextElm = document.getElementById('jsonText');
jsonTextElm.innerText = json;
/* places.forEach(function(place) {
var json = JSON.stringify(place);
jsonTextElm.innerText += json;
}); */
var adr_address = document.querySelector('.adr_address');
adr_address.innerHTML = places[0].adr_address;
document.querySelector('[name="city"]').value = document.querySelector('.adr_address .locality').innerText;
document.querySelector('[name="state"]').value = document.querySelector('.adr_address .region').innerText;
document.querySelector('[name="zipcode"]').value = document.querySelector('.adr_address .postal-code').innerText;
document.querySelector('[name="address"]').value = document.querySelector('.adr_address .street-address').innerText;
});
}