function init() {
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 1,
center: new google.maps.LatLng(0, 0),
noClear: true,
disableDefaultUI: true
}),
diagonal = 250, //length of the diagonal in km
inputs = map.getDiv().querySelectorAll('input[id^="pac"]'),
acs = [],
area = new google.maps.Rectangle(),
marker = new google.maps.Marker({
animation: google.maps.Animation.DROP
});
for (var i = 0; i < inputs.length, i < 2; ++i) {
map.controls[google.maps.ControlPosition.TOP_CENTER].push(inputs[i]);
acs.push(new google.maps.places.Autocomplete(inputs[i]));
if (i === 1) {
//first input
google.maps.event.addListener(acs[0], 'place_changed', function() {
//when there is a valid place
if (this.getPlace().geometry) {
var center = this.getPlace().geometry.location,
bounds = new google.maps.LatLngBounds(center);
//create a area around the place
bounds.extend(google.maps.geometry.spherical.computeOffset(center, diagonal / 2 * 1000, 135));
bounds.extend(google.maps.geometry.spherical.computeOffset(center, diagonal / 2 * 1000, 315));
//just a rectangle to visualize the used area
area.setOptions({
map: map,
bounds: bounds
});
map.fitBounds(bounds);
//set the prefered search-area for the 2nd autocomplete
acs[1].setBounds(bounds);
} else {
acs[1].setBounds(null);
area.setMap(null);
}
});
//2nd input
google.maps.event.addListener(acs[1], 'place_changed', function() {
//when there is a valid place
if (this.getPlace().geometry) {
//draw a marker and set the center of the map
var center = this.getPlace().geometry.location;
map.setCenter(center)
marker.setOptions({
map: map,
position: center
})
} else {
marker.setMap(null);
}
});
}
}
}
html,
body,
#map_canvas {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map_canvas">
<input id="pac1">
<input id="pac2">
</div>
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places,geometry&callback=init"></script>