Autocomplete locations only without radio buttons - google-maps

I found a script from one of my colleague.
All I want is an autocomplete from Google maps for the locations in United states and Canada. I saw that I cannot add multiple countries in componentRestrictions but, if you know a workaround that would be of great help too.
The Script which I have here is :
<!DOCTYPE html>
<html>
<head>
<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<style>
body {
font-family: sans-serif;
font-size: 14px;
}
#map_canvas {
height: 400px;
width: 600px;
margin-top: 0.6em;
}
input {
border: 1px solid rgba(0, 0, 0, 0.5);
}
input.notfound {
border: 2px solid rgba(255, 0, 0, 0.4);
}
</style>
<script>
function initialize() {
var input = document.getElementById('searchTextField');
var options = {
types: ['(cities)'],
componentRestrictions: {country: 'us'}
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
google.maps.event.addDomListener(radioButton, 'click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div>
<input id="searchTextField" type="text" size="50">
<input type="radio" name="type" id="changetype-all" checked="checked">
<label for="changetype-all">All</label>
<input type="radio" name="type" id="changetype-establishment">
<label for="changetype-establishment">Establishments</label>
<input type="radio" name="type" id="changetype-geocode">
<label for="changetype-geocode">Geocodes</lable>
</div>
</body>
</html>
This script works! But, the problem is, I do not want radio buttons and when I remove them and relevant script, it stops working completely!
I just want auto complete without anything else around it.
Again, this script is not written by me.
EDIT:
My question is related to https://gis.stackexchange.com/questions/31916/i-am-trying-to-put-autocomplete-of-google-api-v3-for-places-but-giving-some-err
which Google gave me... although even that chap is struggling :(

The multiple countries filter was introduced in version 3.27 of Maps JavaScript API in January 2017:
You can now restrict Autocomplete predictions to only surface from multiple countries. You can do this by specifying up to 5 countries in the componentRestrictions field of the AutocompleteOptions.
https://developers.google.com/maps/documentation/javascript/releases
https://developers.google.com/maps/documentation/javascript/reference#ComponentRestrictions
Have a look at this example: http://jsbin.com/ramagi/edit?html,output
var G = google.maps;
var chicago = new G.LatLng(41.850033, -87.6500523);
var infowindow = new G.InfoWindow();
var marker;
function initialize() {
var mapOptions = {
center: chicago,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
marker = new G.Marker({map:map});
var input = document.getElementById('searchTextField');
var options = {
types: ['(cities)'],
componentRestrictions: {country: ['us', 'ca']}
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
var image = new google.maps.MarkerImage(
place.icon,
new google.maps.Size(71, 71),
new google.maps.Point(0, 0),
new google.maps.Point(17, 34),
new google.maps.Size(35, 35));
marker.setIcon(image);
marker.setPosition(place.geometry.location);
var address = '';
if (place.address_components) {
address = [(place.address_components[0] &&
place.address_components[0].short_name || ''),
(place.address_components[1] &&
place.address_components[1].short_name || ''),
(place.address_components[2] &&
place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
body {
font-family: sans-serif;
font-size: 14px;
}
#map_canvas {
height: 400px;
width: 600px;
margin-top: 0.6em;
}
input {
border: 1px solid rgba(0, 0, 0, 0.5);
}
input.notfound {
border: 2px solid rgba(255, 0, 0, 0.4);
}
<div>
<input id="searchTextField" type="text" size="50">
<div id="map_canvas"></div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&libraries=places"></script>

All I had to do was simply remove lines, one by one... I noticed, I removed that extra } until Chrome console told me!
Simple solution.
<!DOCTYPE html>
<html>
<head>
<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<style>
body {
font-family: sans-serif;
font-size: 14px;
}
#map_canvas {
height: 400px;
width: 600px;
margin-top: 0.6em;
}
input {
border: 1px solid rgba(0, 0, 0, 0.5);
}
input.notfound {
border: 2px solid rgba(255, 0, 0, 0.4);
}
</style>
<script>
function initialize() {
var input = document.getElementById('searchTextField');
var options = {
componentRestrictions: {country: 'us'}
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<form method = "POST">
<div>
<input id="searchTextField" type="text" size="50" name="location">
</div>
<input type = "submit" />
</body>
</html>

Copy + paste service (Live demo here.):
<!DOCTYPE html>
<html>
<head>
<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<style>
body {
font-family: sans-serif;
font-size: 14px;
}
#map_canvas {
height: 400px;
width: 600px;
margin-top: 0.6em;
}
input {
border: 1px solid rgba(0, 0, 0, 0.5);
}
input.notfound {
border: 2px solid rgba(255, 0, 0, 0.4);
}
</style>
<script>
var G = google.maps;
var chicago = new G.LatLng(41.850033, -87.6500523);
var infowindow = new G.InfoWindow();
var marker;
function initialize() {
var mapOptions = {
center: chicago,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
marker = new G.Marker({map:map});
var input = document.getElementById('searchTextField');
var options = {
types: ['(cities)'],
componentRestrictions: {country: 'us'}
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
var image = new google.maps.MarkerImage(
place.icon,
new google.maps.Size(71, 71),
new google.maps.Point(0, 0),
new google.maps.Point(17, 34),
new google.maps.Size(35, 35));
marker.setIcon(image);
marker.setPosition(place.geometry.location);
var address = '';
if (place.address_components) {
address = [(place.address_components[0] &&
place.address_components[0].short_name || ''),
(place.address_components[1] &&
place.address_components[1].short_name || ''),
(place.address_components[2] &&
place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div>
<input id="searchTextField" type="text" size="50">
<div id="map_canvas"></div>
</div>
</body>
</html>

If you don't want any radio button, just replace them with , something like this:
<div name="type" id="changetype-all" checked="checked"></div>
<label for="changetype-all">All</label>
<div name="type" id="changetype-establishment"></div>
<label for="changetype-establishment">Establishments</label>
<div name="type" id="changetype-geocode"></div>
<label for="changetype-geocode">Geocodes</lable>

Related

1st Dynamic Google maps API autocomplete.getPlace() returns null

I have 2 input boxes pickup and deliver. here is the library call:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=mykey&libraries=places&callback=initMap">
</script>
and my autocomplete snipplet:
var inputStart = document.getElementsByClassName('ginput');
for (var i = 0; i < inputStart.length; i++) {
var autocomplete = new google.maps.places.Autocomplete(inputStart[i]);
console.log(autocomplete);
autocomplete.inputId = inputStart[i].id;
autocomplete.bindTo('bounds', map);
autocomplete.setFields(
['address_components', 'geometry', 'icon', 'name']);
var infowindow = new google.maps.InfoWindow();
var infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
console.log(place);
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert("No details available for input: '" + place.name + "'");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
//console.table(place);
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || ''),
(place.address_components[6] && place.address_components[6].short_name || '')
].join(' ');
}else{
alert("No Place");
}
infowindowContent.children['place-icon'].src = place.icon;
//infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-address'].textContent = address;
infowindow.open(map, marker);
HTML:
<b>Pickup:</b>
<div id="pac-container-start">
<input id="pac-input-start" class="ginput" type="text"
placeholder="Enter a pickup location">
</div>
<b>Dropoff:</b>
<div id="pac-container-end">
<input id="pac-input-end" class="ginput" type="text"
placeholder="Enter a dropoff location">
</div>
The problem is after selecting an address from the dropdown, i get an error:
scripts.js:159 Uncaught TypeError: Cannot read property 'geometry' of undefined
I have logged out places and it is undefined, funny thing is when i select an address in the 2nd box, it seems to work fine. no errors, maps out the proper directions and all.
Almost seems to me like its confused on which box is sending the request?
Pointing me in the right direction would be much appreciated.
Your autocomplete is left on the last input, so it no longer works on the first.
One way to fix that would be to use Array.prototype.forEach to iterate through the input collection, giving function closure on each autocomplete instance:
Array.prototype.forEach.call(inputStart, function(el, i) {
console.log(inputStart[i].id);
var autocomplete= new google.maps.places.Autocomplete(inputStart[i]);
console.log(autocomplete);
autocomplete.inputId = inputStart[i].id;
autocomplete.bindTo('bounds', map);
autocomplete.setFields(
['address_components', 'geometry', 'icon', 'name']);
var infowindow = new google.maps.InfoWindow();
var infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
console.log(place);
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert("No details available for input: '" + place.name + "'");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
//console.table(place);
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || ''),
(place.address_components[6] && place.address_components[6].short_name || '')
].join(' ');
} else {
alert("No Place");
}
infowindowContent.children['place-icon'].src = place.icon;
//infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-address'].textContent = address;
infowindow.open(map, marker);
})
})
proof of concept fiddle
code snippet
// 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 infowindow = new google.maps.InfoWindow();
var infowindowContent = document.getElementById('infowindow-content');
var inputStart = document.getElementsByClassName('ginput');
//for (var i = 0; i < inputStart.length; i++) {
// inputStart.forEach(function() {
Array.prototype.forEach.call(inputStart, function(el, i) {
console.log(inputStart[i].id);
var autocomplete= new google.maps.places.Autocomplete(inputStart[i]);
console.log(autocomplete);
autocomplete.inputId = inputStart[i].id;
autocomplete.bindTo('bounds', map);
autocomplete.setFields(
['address_components', 'geometry', 'icon', 'name']);
infowindow.setContent(infowindowContent);
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
console.log(place);
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert("No details available for input: '" + place.name + "'");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
//console.table(place);
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || ''),
(place.address_components[6] && place.address_components[6].short_name || '')
].join(' ');
} else {
alert("No Place");
}
infowindowContent.children['place-icon'].src = place.icon;
//infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-address'].textContent = address;
infowindow.open(map, marker);
})
})
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 80%;
}
/* 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;
}
.ginput {
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;
}
<div class="pac-card" id="pac-card">
<div id="pac-container">
<input id="pac-input" class="ginput" type="text"
placeholder="Enter a location" value="Potts Point">
<input id="pac-input2" class="ginput" type="text"
placeholder="Enter a location" value="Sydney">
</div>
</div>
<div id="map"></div>
<div id="infowindow-content">
<img src="" width="16" height="16" id="place-icon">
<span id="place-name" class="title"></span><br>
<span id="place-address"></span>
</div>
<!-- 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=initMap&v=quarterly"
async defer></script>

Save Map Instance outside of Google Maps

I've made a google maps API (HTML) script that created markers when the user clicks on the map. I've also integrated Google+ login functions so users are unique and have profiles. I now want to make it so users can create their markers on their desired positions and then save the map so they can come back to it later. I however don't want them to use this "https://developers.google.com/maps/documentation/javascript/examples/save-widget" provided function because then the markers are synched to their google+. In other words I only want the markers to save to my website, not to their personal google maps. How would I go about saving the state of the map only on my site?
Heres the fiddle of my code: https://jsfiddle.net/hgvsurt5/
Heres the code:
<head>
<style>
#map-canvas {
width: 900px;
height: 600px;
}
.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 marker = []
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;
}
</script>
<script>
var map;
var myCenter = new google.maps.LatLng(51.508742, -0.120850);
function initialize() {
var mapProp = {
center: myCenter,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
draggable: true,
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() + '<br>Longitude: ' + location.lng()
});
infowindow.open(map, marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:900px;height:600px;"></div>
</body>
You must somehow bring the desired data into a format which may be sended and stored. A good approach would be to use a Data-layer to draw the features on the map, you may easily use the method toGeoJson of the Data-layer to convert the data into a geoJson and send it to a server(where you store the data).
A simple implementation:
function initialize() {
var map = new google.maps.Map(document.getElementById("googleMap"), {
center: new google.maps.LatLng(51.508742, -0.120850),
zoom: 5,
noClear: true
}),
//this may be the stored data
data = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-0.120850, 51.508742]
},
"properties": {}
}]
},
win = new google.maps.InfoWindow,
//some buttons for interaction
ctrl = document.getElementById('datactrl'),
fx = {
'data-save': {
click: function() {
//use this method to store the data somewhere,
//e.g. send it to a server
map.data.toGeoJson(function(json) {
data = json;
});
}
},
'data-show': {
click: function() {
alert('you may send this JSON-string to a server and store it there:\n\n' +
JSON.stringify(data))
}
},
'data-load': {
click: function() {
//use this method to load the data from somwhere
//e.g. from a server via loadGeoJson
map.data.forEach(function(f) {
map.data.remove(f);
});
map.data.addGeoJson(data)
},
init: true
},
'data-clear': {
click: function() {
//use this method to clear the data
//when you also want to remove the data on the server
//send a geoJSON with empty features-array to the server
map.data.forEach(function(f) {
map.data.remove(f);
});
data = {
type: "FeatureCollection",
features: []
};
}
}
};
for (var id in fx) {
var o = ctrl.querySelector('input[id=' + id + ']');
google.maps.event.addDomListener(o, 'click', fx[id].click);
if (fx[id].init) {
google.maps.event.trigger(o, 'click');
}
}
map.controls[google.maps.ControlPosition.TOP_CENTER].push(ctrl);
function placeMarker(location) {
var feature = new google.maps.Data.Feature({
geometry: location
});
map.data.add(feature);
}
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
google.maps.event.addListener(map.data, 'click', function(e) {
if (e.feature.getGeometry().getType() === 'Point') {
win.setOptions({
content: 'Latitude: ' + e.feature.getGeometry().get().lat() +
'<br>Longitude: ' + e.feature.getGeometry().get().lng(),
pixelOffset: new google.maps.Size(0, -40),
map: map,
position: e.feature.getGeometry().get()
});
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#googleMap {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="googleMap">
<div id="datactrl">
<input type="button" id="data-save" value="save" />
<input type="button" id="data-show" value="show saved data" />
<input type="button" id="data-load" value="load saved data" />
<input type="button" id="data-clear" value="remove all data" />
</div>
</div>

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

Search for a place via google map api

I want to search for a place via maps. I used following example of auto-complete a place's address. Its working fine but i don't want user to type i want to send a place name and it should search automatically. Currently working code (Shows result when type)
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete</title>
<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;
padding: 0 11px 0 13px;
width: 400px;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
text-overflow: ellipsis;
}
#pac-input:focus {
border-color: #4d90fe;
margin-left: -1px;
padding-left: 14px; /* Regular padding-left + 1. */
width: 401px;
}
.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 src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script>
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
var types = document.getElementById('type-selector');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon(/** #type {google.maps.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(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
google.maps.event.addDomListener(radioButton, 'click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<input id="pac-input" class="controls" type="text"
>
<div id="type-selector" class="controls">
<input type="radio" name="type" id="changetype-all" checked="checked">
<label for="changetype-all">All</label>
<input type="radio" name="type" id="changetype-establishment">
<label for="changetype-establishment">Establishments</label>
<input type="radio" name="type" id="changetype-geocode">
<label for="changetype-geocode">Geocodes</label>
</div>
<div id="map-canvas"></div>
</body>
</html>
When i type in pac-input it shows suggestions and after clicking shows marker. how to search automatically for a location if i pass a default value to pac-input?

How to hide or display a Google Maps Layer?

I have prepared a simplified test case and a screenshot.
I think I'm missing a tiny bit, just few lines of code.
I have 2 overlays (the weather and clouds) in my JavaScript Google Map and would like to hide or show them when a corresponding check box is clicked:
Here is the test case, just paste it into an .html file and it will run:
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
h1,p {
text-align: center;
}
#map {
width: 700px;
height: 400px;
margin-left: auto;
margin-right: auto;
background-color: #CCCCFF;
}
</style>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false&language=de&libraries=weather"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
findCity('Berlin');
$('#weather_box,#clouds_box').click(function(){
alert('How to hide/show layers? Checked: ' + $(this).is(':checked'));
});
});
function createMap(center) {
var opts = {
zoom: 6,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
return new google.maps.Map(document.getElementById('map'), opts);
}
function findCity(city) {
var gc = new google.maps.Geocoder();
gc.geocode({address: city}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var pos = results[0].geometry.location;
var map = createMap(pos);
var marker = new google.maps.Marker({
map: map,
title: city,
position: pos,
animation: google.maps.Animation.DROP
});
var weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.CELSIUS
});
weatherLayer.setMap(map);
//var cloudLayer = new google.maps.weather.CloudLayer();
//cloudLayer.setMap(map);
}
});
}
</script>
</head>
<body>
<h1>Berlin</h1>
<p>Show:
<label><input type="checkbox" id="weather_box" checked>weather</label>
<label><input type="checkbox" id="clouds_box">clouds</label>
</p>
<div id="map"></div>
</body>
</html>
UPDATE: Thanks, here a working version for everyone
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
h1,p {
text-align: center;
}
#map {
width: 700px;
height: 400px;
margin-left: auto;
margin-right: auto;
background-color: #CCCCFF;
}
</style>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false&language=de&libraries=weather"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
var map;
var WeatherLayer;
var CloudsLayer;
$(function() {
findCity('Berlin');
});
function createMap(center) {
var opts = {
zoom: 6,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
return new google.maps.Map(document.getElementById('map'), opts);
}
function findCity(city) {
var gc = new google.maps.Geocoder();
gc.geocode({address: city}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var pos = results[0].geometry.location;
map = createMap(pos);
var marker = new google.maps.Marker({
map: map,
title: city,
position: pos,
animation: google.maps.Animation.DROP
});
weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.CELSIUS
});
weatherLayer.setMap(map);
cloudsLayer = new google.maps.weather.CloudLayer();
//cloudsLayer.setMap(map);
$('#weather_box').click(function(){
weatherLayer.setMap($(this).is(':checked') ? map : null);
});
$('#clouds_box').click(function(){
cloudsLayer.setMap($(this).is(':checked') ? map : null);
});
$('#weather_box,#clouds_box').removeAttr('disabled');
}
});
}
</script>
</head>
<body>
<h1>Berlin</h1>
<p>Show:
<label><input type="checkbox" id="weather_box" disabled="true" checked>weather</label>
<label><input type="checkbox" id="clouds_box" disabled="true">clouds</label>
</p>
<div id="map"></div>
</body>
</html>
You can hide/show the layer with setMap method:
if ($(this).is(':checked'))
weatherLayer.setMap(map); // show
else
weatherLayer.setMap(null); // hide
See working example: http://jsfiddle.net/EeVUr/2/ (removed your second checkbox, as you have only one layer now. But you can easily create two different layers and switch them.)
If you use deckgl along with deckgl, set the visible property to true or false.
and in updateTriggers, keep the variable that decides the visibility
eg:
new GeoJsonLayer({
...otherProps,
updateTriggers: {
visible: [decisionVariable],
}
visible: decisionVariable ? true : false,
})