// Initialize the center button (to re-center the map) function initCenter() { var centerBtnDiv = document.getElementById('ctrButton'); map.controls[google.maps.ControlPosition.RIGHT_CENTER].push(centerBtnDiv) centerBtnDiv.title = 'Click to recenter the map'; // Setup the click event listeners: reset center location and zoom factor centerBtnDiv.addEventListener('click', function() { map.setCenter(centerPoint); map.setZoom(initZoom); clearPlacePins(); }); } // Initialize the search box and listener function initSearch() { // Create the search box and link it to the UI element. var input = document.getElementById('search-input'); var searchBox = new google.maps.places.SearchBox(input); map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); // Bias the SearchBox results towards current map's viewport. map.addListener('bounds_changed', function() { searchBox.setBounds(map.getBounds()); }); // Listen for the event fired when the user selects a prediction and retrieve // more details for that place. searchBox.addListener('places_changed', function() { var places = searchBox.getPlaces(); if (places.length == 0) { return; } clearPlacePins(); // Create a bounding region to include the search result places var bounds = new google.maps.LatLngBounds(); // For each place, get the icon, name and location. // There may be multiple search results places.forEach(function(place) { if (!place.geometry) { console.log("Returned place contains no geometry"); return; } // Create a marker for each place. placeMarker = new google.maps.Marker( { map: map, title: place.name, position: place.geometry.location }) // Click on the marker to remove it from the display placeMarker.addListener('click', function() { placeMarker.setMap(null); }); // Add this marker to the collection of current markers placePins.push(placeMarker); // Create a bounding region to include this place if (place.geometry.viewport) { // Only geocodes have viewport. bounds.union(place.geometry.viewport); } else { bounds.extend(place.geometry.location); } }); // This will pan and zoom to the area around the marker //map.fitBounds(bounds); // This will center the map on the new marker(s) but not zoom map.setCenter(bounds.getCenter()); }); } // Remove any place pins from a previous search function clearPlacePins() { placePins.forEach(function(marker) { marker.setMap(null); }); placePins = []; }