Google Maps SearchBox not searching in bounds - google-maps

I'm having problems getting google's searchbox service to run properly for me.
What I have is a map with a polygon drawn on it. I would like to use the searchbox and/or autocomplete service to return ONLY business of the specified type (e.g. restaurants, fast food, warehouses, etc.) that are within this polygons boundaries.
I can use the nearby service to return results based on type or keyword. I can also get the searchbox to return results for restaurants; however, if I update the search to look for other businesses, such as warehouses, the map zooms out and shows warehouses all over the world.
Here is a working fiddle example:
<html>
<head>
<meta charset="utf-8">
<title>Transition Center Online</title>
<meta name="description" content="">
<meta name="title" content="">
<meta name="author" content="WWRF">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#map {
height: 600px;
width: 100%;
}
#description {
font-family: Roboto;
font-size: 15px;
font-weight: 300;
}
#infowindow-content .title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
.pac-card {
margin: 10px 10px 0 0;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
background-color: #fff;
font-family: Roboto;
}
#pac-container {
padding-bottom: 12px;
margin-right: 12px;
}
.pac-controls {
display: inline-block;
padding: 5px 11px;
}
.pac-controls label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
#title {
color: #fff;
background-color: #4d90fe;
font-size: 25px;
font-weight: 500;
padding: 6px 12px;
}
#target {
width: 345px;
}
</style>
</head>
<body>
<div class="container">
<p>TODO: Add Google JavaScript Map with walkroute outline.</p>
<p>TODO: List walking times</p>
<p>TODO: List common walk routes and businesses</p>
<!-- where the map will live -->
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
</div>
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var map;
var infowindow;
function initMap() {
var wwrf = {
lat: 37.682319,
lng: -97.333311
};
map = new google.maps.Map(document.getElementById('map'), {
center: wwrf,
zoom: 14
});
var squareCoords = [
{lat: 37.697465, lng: -97.341629},
{lat: 37.697636, lng: -97.317306},
{lat: 37.671759, lng: -97.317142},
{lat: 37.673308, lng: -97.352833},
{lat: 37.693239, lng: -97.352852}
];
// Construct the walkroute polygon.
var walkRoute = new google.maps.Polygon({
paths: squareCoords,
strokeColor: '#008000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#008000',
fillOpacity: 0.1
});
walkRoute.setMap(map);
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: wwrf,
radius: 1600,
type: ['establishment'],
//keyword: ['restaurant']
}, callback);
var walkRouteBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(37.673308, -97.352833),
new google.maps.LatLng(37.697636, -97.317306),
);
var options = {
bounds: walkRouteBounds,
strictBounds: true
};
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input, options);
map.controls[google.maps.ControlPosition.TOP_CENTER].push(input);
var markers = [];
// 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();
searchBox.setBounds(walkRouteBounds);
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(37.673308, -97.352833),
new google.maps.LatLng(37.697636, -97.317306),
);
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
//icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<strong>' + place.name + '</strong><br/>' + place.formatted_address);
infowindow.open(map, this);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=your_api&libraries=places&callback=initMap" async defer></script>
</body>
GoogleMap searchbox fiddle
EDIT: Alright so I have been able to come up with a solution using a dropdown box, although it is not ideal because I have to hard code my keywords.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Walkroute Dropdown</title>
<meta name="description" content="">
<meta name="title" content="">
<meta name="author" content="WWRF">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#map {
height: 600px;
width: 100%;
}
#description {
font-family: Roboto;
font-size: 15px;
font-weight: 300;
}
#infowindow-content .title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
.pac-card {
margin: 10px 10px 0 0;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
background-color: #fff;
font-family: Roboto;
}
#pac-container {
padding-bottom: 12px;
margin-right: 12px;
}
.pac-controls {
display: inline-block;
padding: 5px 11px;
}
.pac-controls label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
#title {
color: #fff;
background-color: #4d90fe;
font-size: 25px;
font-weight: 500;
padding: 6px 12px;
}
#target {
width: 345px;
}
</style>
</head>
<body>
<div class="container">
<select name="mapchange" onchange="updateMap(this.options[this.selectedIndex].value)">
<option value="restaurants">Restaurants</option>
<option value="warehouses">Warehouses</option>
<option value="temp services">Temp Services</option>
</select>
<!-- where the map will live -->
<div id="map"></div>
</div>
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var map;
var infowindow;
var wwrf = {
lat: 37.682319,
lng: -97.333311
};
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: wwrf,
zoom: 14
});
var squareCoords = [
{lat: 37.697465, lng: -97.341629},
{lat: 37.697636, lng: -97.317306},
{lat: 37.671759, lng: -97.317142},
{lat: 37.673308, lng: -97.352833},
{lat: 37.693239, lng: -97.352852}
];
// Construct the walkroute polygon.
var walkRoute = new google.maps.Polygon({
paths: squareCoords,
strokeColor: '#008000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#008000',
fillOpacity: 0.1
});
walkRoute.setMap(map);
infowindow = new google.maps.InfoWindow();
/*var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: wwrf,
radius: 1600,
type: ['establishment'],
keyword: ['restaurant']
}, callback);*/
}
var markers = [];
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
// Create a marker for each place.
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<strong>' + place.name + '</strong><br/>' + place.formatted_address);
infowindow.open(map, this);
});
}
function updateMap(selectControl) {
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
var keyword = selectControl;
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: wwrf,
radius: 1600,
type: ['establishment'],
keyword: keyword
}, callback);
}
function clearMarkers() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=your_api&libraries=places&callback=initMap" async defer></script>
</body>
</html>
And here's a link to the fiddle: Walkroute dropdown

I can see that you try to initialize the SearchBox with strictBounds: true option, but unfortunately, the SearchBox doesn't support strict bounds filter at current moment. If you can switch to the Autocomplete, it is indeed supports strict bounds and you can initialize the autocomplete like
var options = {
bounds: walkRouteBounds,
strictBounds: true,
types: ['establishment']
};
var input = document.getElementById('pac-input');
var autocomplete = new google.maps.places.Autocomplete(input, options);
Regarding the strict bounds for SearchBox, there is a feature request in Google issue tracker:
https://issuetracker.google.com/issues/67982212
Feel free to star the feature request to add your vote and subscribe to notifications.

Ok ,I've been looking to this for a while and here comes a possible solution that I thought:
So inside the For loop in the callback Function may I suggest before creating a marker to ask (with a IF and I think there is a method called contains that returns a boolean) if the
place.geometry.location is inside your bounds, so if the place is not inside your bounds then you do not create that marker, therefore the map won't zoom out.
Another solution would be forcing the zoom to a value after the autocomplete search.
I hope with this you could find a solution to your issue.

Related

How to get parameters like country,city,state and area information when user share their location...?

I am providing a form to a user which takes some information about the user.
Instead of taking the address by providing them options like drop box which includes many countries,cities,states and area, I would provide them Google Map so that user can share their location and when user submit the form, then I must be able to get country,city,state,area and latitude and longitude and store that in MySQL database
When a user share their location, below codes gives all the required data, like country,state,city,area,pin-code, latitude,longitude and many more....
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Places Search Box</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#description {
font-family: Roboto;
font-size: 15px;
font-weight: 300;
}
#infowindow-content .title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
.pac-card {
margin: 10px 10px 0 0;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
background-color: #fff;
font-family: Roboto;
}
#pac-container {
padding-bottom: 12px;
margin-right: 12px;
}
.pac-controls {
display: inline-block;
padding: 5px 11px;
}
.pac-controls label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
#title {
color: #fff;
background-color: #4d90fe;
font-size: 25px;
font-weight: 500;
padding: 6px 12px;
}
#target {
width: 345px;
}
</style>
</head>
<body>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
<script>
// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13,
mapTypeId: 'roadmap'
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-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());
});
var markers = [];
// 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;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete"
async defer></script>
</body>
</html>

Google Maps AutoComplete and Directions with fixed destination and variable origin

I am using GoogleMaps with AutoComplete and Directions services to draw a route between two markers (places). The example on google maps documentation has two input fields, one for origin and other for destination. I have destination LatLong. How can I fix the destination with these latLong and draw route when user selects origin.
destination lat/lng: latitude: 25.116810, longitude: 55.123562
link to jsfiddle JsFiddle
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.controls {
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#origin-input,
#destination-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 200px;
}
#origin-input:focus,
#destination-input:focus {
border-color: #4d90fe;
}
#mode-selector {
color: #fff;
background-color: #4d90fe;
margin-left: 12px;
padding: 5px 11px 0px 11px;
}
#mode-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
</style>
</head>
<body>
<input id="origin-input" class="controls" type="text"
placeholder="Enter an origin location">
<input id="destination-input" class="controls" type="text"
placeholder="Enter a destination location">
<div id="mode-selector" class="controls">
<input type="radio" name="type" id="changemode-walking" checked="checked">
<label for="changemode-walking">Walking</label>
<input type="radio" name="type" id="changemode-transit">
<label for="changemode-transit">Transit</label>
<input type="radio" name="type" id="changemode-driving">
<label for="changemode-driving">Driving</label>
</div>
<div id="map"></div>
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'WALKING';
var originInput = document.getElementById('origin-input');
var destinationInput = document.getElementById('destination-input');
var modeSelector = document.getElementById('mode-selector');
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, {placeIdOnly: true});
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput, {placeIdOnly: true});
this.setupClickListener('changemode-walking', 'WALKING');
this.setupClickListener('changemode-transit', 'TRANSIT');
this.setupClickListener('changemode-driving', 'DRIVING');
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(originInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(destinationInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(modeSelector);
}
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
var radioButton = document.getElementById(id);
var me = this;
radioButton.addEventListener('click', function() {
me.travelMode = mode;
me.route();
});
};
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {'placeId': this.originPlaceId},
destination: {'placeId': this.destinationPlaceId},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=your_api_key&libraries=places&callback=initMap"
async defer></script>
</body>
</html>
set the desired destination (hard code it)
destination: new google.maps.LatLng(25.116810, 55.123562);
remove the autocomplete associated with the destination
Note that for some reason your destination doesn't work for walking directions, so you may want to remove the travelMode selection.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {
lat: 25.116810,
lng: 55.123562
},
zoom: 13
});
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(25.116810, 55.123562)
});
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.travelMode = 'DRIVING';
var originInput = document.getElementById('origin-input');
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, {
placeIdOnly: true
});
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(originInput);
}
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
var radioButton = document.getElementById(id);
var me = this;
radioButton.addEventListener('click', function() {
me.travelMode = mode;
me.route();
});
};
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
me.originPlaceId = place.place_id;
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {
'placeId': this.originPlaceId
},
destination: new google.maps.LatLng(25.116810, 55.123562),
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
.controls {
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#origin-input,
#destination-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 200px;
}
#origin-input:focus,
#destination-input:focus {
border-color: #4d90fe;
}
#mode-selector {
color: #fff;
background-color: #4d90fe;
margin-left: 12px;
padding: 5px 11px 0px 11px;
}
#mode-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
</style>
</head>
<body>
<input id="origin-input" class="controls" type="text" placeholder="Enter an origin location">
<div id="map"></div>
<script>
</script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap" async defer></script>
</body>
</html>
In
this.directionsService.route({
origin: {'placeId': this.originPlaceId},
destination: {'placeId': this.destinationPlaceId},
travelMode: this.travelMode
}, function(response, status) {
In destination substitude with a LatLng:
destination: {lat: 25.116810, lng: 55.123562}
and you can erase input for destination or any event associated to get this field from user.

How to identify multiple names used in google maps to key to the same name?

Typically, a place name (e.g. Mumbai) has different names that show up in Google maps - e.g. Mumbai Maharashtra, Mumbai India or just Mumbai.
how do we identify it's the same place (without depending on co-ordinates which are known to change)? Something like a unique key or string name that I can use to look up into my application?
This key exists. It is name the Place IDs. A place Id is unique for each address in the world. You can convert an address to a place id with this function:
var request = {
location: map.getCenter(),
radius: '500',
query: 'Google Sydney'
};
var service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
// Checks that the PlacesServiceStatus is OK, and adds a marker
// using the place ID and location from the PlacesService.
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
console.log (results[0].place_id);
var marker = new google.maps.Marker({
map: map,
place: {
placeId: results[0].place_id,
location: results[0].geometry.location
}
});
}
}
This is an other example maybe a quite more complicated:
// This sample uses the Place Autocomplete widget to allow the user to search
// for and select a place. The sample then displays an info window containing
// the place ID and other information about the place that the user has
// selected.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
var input = document.getElementById('pac-input');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
// Set the position of the marker using the place ID and location.
marker.setPlace({
placeId: place.place_id,
location: place.geometry.location
});
marker.setVisible(true);
document.getElementById('place-name').textContent = place.name;
document.getElementById('place-id').textContent = place.place_id;
document.getElementById('place-address').textContent =
place.formatted_address;
infowindow.setContent(document.getElementById('infowindow-content'));
infowindow.open(map, marker);
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.controls {
background-color: #fff;
border-radius: 2px;
border: 1px solid transparent;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
box-sizing: border-box;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
height: 29px;
margin-left: 17px;
margin-top: 10px;
outline: none;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
.controls:focus {
border-color: #4d90fe;
}
.title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
<input id="pac-input" class="controls" type="text"
placeholder="Enter a location">
<div id="map"></div>
<div id="infowindow-content">
<span id="place-name" class="title"></span><br>
Place ID <span id="place-id"></span><br>
<span id="place-address"></span>
</div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap"
async defer></script>
This is another example of reverse geocoding with place id:
// Initialize the map.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: 40.72, lng: -73.96}
});
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
document.getElementById('submit').addEventListener('click', function() {
geocodePlaceId(geocoder, map, infowindow);
});
}
// This function is called when the user clicks the UI button requesting
// a reverse geocode.
function geocodePlaceId(geocoder, map, infowindow) {
var placeId = document.getElementById('place-id').value;
geocoder.geocode({'placeId': placeId}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
#floating-panel {
width: 440px;
}
#place-id {
width: 250px;
}
<div id="floating-panel">
<!-- Supply a default place ID for a place in Brooklyn, New York. -->
<input id="place-id" type="text" value="ChIJd8BlQ2BZwokRAFUEcm_qrcA">
<input id="submit" type="button" value="Reverse Geocode by Place ID">
</div>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
All this is a bit complicated...
You can consult the google developer web site for more informations:
Geocoding place id
Example geocoding
Reverse geocoding
Example reverse geocoding
Tell me if you do not understand or if you have some questions or some comments.

how to add my location button to google map

i would like to add my location button to my map like the real google map does.
ihave tried some plugins but they didnt had location button, what should i do?
here is one plugin that i used:
var mapOptions = {
zoom: 17,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var GeoMarker = new GeolocationMarker(map);
For web browsers you can use the html5 built in geolocation to get your location: You can follow this doc: https://developers.google.com/maps/documentation/javascript/examples/map-geolocation
But first set a default location in case the browser doesn't support Geolocation
var myLocation = {lat: -34.397, lng: 150.644};
After that in your init function you can get your location like this:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
myLocation.lat = position.coords.latitude;
myLocation.lng = position.coords.longitude;
map.setCenter(myLocation);
}, function() {
handleLocationError(true, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, map.getCenter());
}
Set your location's coordinates as default center of the map
map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
center: myLocation,
mapTypeId: 'roadmap'
});
Then just call this function if you want to go back to your location
function goToMyLocation() {
map.setCenter(myLocation);
}
Check this working example: https://jsbin.com/ricebu/edit?html,css,js,output
Here is the code snippet as well
var map;
var btnLocation = document.getElementById("btn-location");
var myLocation = {
lat: -34.397,
lng: 150.644
};
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
center: myLocation,
mapTypeId: 'roadmap'
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
myLocation.lat = position.coords.latitude;
myLocation.lng = position.coords.longitude;
// I just added a marker for you to verify your location
var marker = new google.maps.Marker({
position: myLocation,
map: map
});
map.setCenter(myLocation);
}, function() {
handleLocationError(true, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
console.log(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
btnLocation.addEventListener('click', function() {
goToMyLocation();
});
function goToMyLocation() {
map.setCenter(myLocation);
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#btn-location {
position: absolute;
right: 20px;
top: 20px;
z-index: 1;
padding: 20px;
border: none;
border-radius: 4px;
background-color: rgba(255, 255, 255, 0.8);
transition: 0.5s;
}
#btn-location:hover {
background-color: rgba(0, 0, 0, 1);
color: white;
cursor: pointer;
}
<html>
<head>
<title>Location</title>
</head>
<body>
<button id="btn-location">Go to my Location</button>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCKQX3cyZ7pVKmBwE8wiowivW9qH62AVk8&callback=initMap"></script>
</body>
</html>
var btnLocation = document.getElementById("btn-location");
var myLocation = {
lat: -34.397,
lng: 150.644
};
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
center: myLocation,
mapTypeId: 'roadmap'
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
myLocation.lat = position.coords.latitude;
myLocation.lng = position.coords.longitude;
// I just added a marker for you to verify your location
var marker = new google.maps.Marker({
position: myLocation,
map: map
});
map.setCenter(myLocation);
}, function() {
handleLocationError(true, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
console.log(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
btnLocation.addEventListener('click', function() {
goToMyLocation();
});
function goToMyLocation() {
map.setCenter(myLocation);
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#btn-location {
position: absolute;
right: 20px;
top: 20px;
z-index: 1;
padding: 20px;
border: none;
border-radius: 4px;
background-color: rgba(255, 255, 255, 0.8);
transition: 0.5s;
}
#btn-location:hover {
background-color: rgba(0, 0, 0, 1);
color: white;
cursor: pointer;
}
<html>
<head>
<title>Location</title>
</head>
<body>
<button id="btn-location">Go to my Location</button>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCKQX3cyZ7pVKmBwE8wiowivW9qH62AVk8&callback=initMap"></script>
</body>
</html>
You can also consider using https://www.npmjs.com/package/google-maps-current-location
It adds the typical button to the map, it handles the geolocation, and it also adds the blue circle surrounding the marker.
Hope it helps :)

Store Locator in google maps, input zip code and display markers on map and sidebar

I'm close to finishing this but I'm having a trouble with the Search box of gmaps.
The concept of the project is to type in a zip code(in my example a fixed one, 15124) and display on the map a number of markers(representing the stores in that area) and in a sidebar their names. The only problem I am facing is the auto-complete/getPlaces property that the search-box has. How do I get rid of this property? I just want a plain input text so that i can write the z.c. and then take that and compare it to see if it's true.Here's my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Store Locate</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=false&libraries=places"></script>
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
</style>
<script type="text/javascript">
var side_bar_html = "";
// arrays to hold copies of the markers and html used by the side_bar
var gmarkers = [];
var marker;
var map = null;
var t=1;
function initialize() {
// create the map
var myOptions = {
zoom: 11,
center: new google.maps.LatLng(37.9833333, 23.7333333),
mapTypeControl: true,
mapTypeControlOptions:{style:google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
initSearchBox(map, 'pac-input');
}//----------------INIT END--------------------
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function initSearchBox(map, controlId) {
// Create the search box and link it to the UI element.
var input = (document.getElementById(controlId));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(input);
// [START region_getplaces]
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
//get first place
var place = places[0];
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50),
content : place.info
});
// Add markers to the map
// Set up the markers with info windows
// add the points
if ((document.getElementById(controlId).value) == ("Marousi, 15124, Vorios Tomeas Athinon, Greece" ||(document.getElementById(controlId).value) == 15124) && t==1){
var point = new google.maps.LatLng(38.0397739,23.8004445);
var marker = createMarker(point,"Relay Marketing","<b>Relay Marketing Services</b> <br>Vlahernon 10,15124,Marousi<br>211 411 2311")
var point = new google.maps.LatLng(38.0409333,23.7954601);
var marker = createMarker(point,"Nespresso S.A.","<b>Nespresso S.A.</b><br>Agiou Thoma 27,15124,Marousi")
var point = new google.maps.LatLng(38.0473031,23.8053483);
var marker = createMarker(point,"Regency Entertainment","<b>Regency Entertainment</b><br>Agiou Konstantinou 49,15124,Marousi <br>210 614 9800")
var point = new google.maps.LatLng(38.050986,23.8084322);
var marker = createMarker(point,"Just4U","<b>Just4U</b> <br>Dimitriou Gounari 84, 15124, Marousi<br>210 614 1923")
var point = new google.maps.LatLng(38.0400533,23.8011982);
var marker = createMarker(point,"Ekka Cars S.A.","<b>Ekka</b> <br>Leoforos Kifisias 79,15124,Marousi<br>210 349 8000")
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
t -=1;//This is so if you search again, it doesn't display again in sidebar
}
map.fitBounds(place.geometry.viewport);
});
}
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
//zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body style="margin:0px; padding:0px;" >
<input id="pac-input" class="controls" type="text" placeholder="Ταχυδρομικός κωδικός">
<table border="1">
<tr>
<td>
<div id="map_canvas" style="width: 550px; height: 450px"></div>
</td>
<td valign="top" style="width:160px; text-decoration: underline; color: #4444ff;">
<div id="side_bar"></div> <hr/>
</td>
</tr>
</table>
</body>
</html>
How to add search box
1 Ensure Places Library is loaded, for example:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
Note: To use the functionality contained within this library, you must
first load it using the libraries parameter in the Maps API bootstrap
URL: libraries=places
Create the search box and link it to the UI element.
HTML:
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
JavaScript:
// Create the search box and link it to the UI element.
var input = (document.getElementById(controlId));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(input);
3 Initialize Search Box control:
function initSearchBox(map,controlId) {
// Create the search box and link it to the UI element.
var input = (document.getElementById(controlId));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(input);
// [START region_getplaces]
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
//get first place
var place = places[0];
var marker = new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location
});
map.fitBounds(place.geometry.viewport);
});
}
Example
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(40.714364, -74.005972),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var locations = [
['New York', 40.714364, -74.005972, 'http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png']
];
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'click', function () {
infowindow.close();
});
var markers = [];
for (var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: locations[i][3]
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
markers.push(marker);
}
initSearchBox(map, 'pac-input');
}
function initSearchBox(map, controlId) {
// Create the search box and link it to the UI element.
var input = (document.getElementById(controlId));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(input);
// [START region_getplaces]
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
//get first place
var place = places[0];
var marker = new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location,
icon: 'http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png'
});
map.fitBounds(place.geometry.viewport);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px;
}
.controls {
margin-top: 16px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map-canvas"></div>
I found this example on Google website, it's an complete HTML file :
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
.controls {
margin-top: 16px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
</style>
<title>Places search box</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<script>
// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
function initialize() {
var markers = [];
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
map.fitBounds(defaultBounds);
// Create the search box and link it to the UI element.
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(
/** #type {HTMLInputElement} */(input));
// [START region_getplaces]
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
// [END region_getplaces]
// Bias the SearchBox results towards places that are within the bounds of the
// current map's viewport.
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#target {
width: 345px;
}
</style>
</head>
<body>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map-canvas"></div>
</body>
</html>
I hope it will be useful...
Source : https://developers.google.com/maps/documentation/javascript/examples/places-searchbox