Google map api - autocomplete for hotels - google-maps

I try to make input field with google map api aucomplete but to search only for hotels...
I try:
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', function () {
var places = new google.maps.places.Autocomplete(
(
document.getElementById('hotel')), {
types: ['hotel']
});
// var places = new google.maps.places.Autocomplete(document.getElementById('hotel'));
google.maps.event.addListener(places, 'place_changed', function () {
var place = places.getPlace();
var address = place.formatted_address;
var phone = place.formatted_phone_number;
var name = place.name;
var url = place.website;
$('#address').val(address);
$('#phone').val(phone);
$('#url').val(url);
$('#hotel').val(name);
});
});
</script>
but dont work... What can be a solution here?

This is from https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-hotelsearch
// This example uses the autocomplete feature of the Google Places API.
// It allows the user to find all hotels in a given place, within a given
// country. It then displays markers for all the hotels returned,
// with on-click details for each hotel.
// 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, places, infoWindow;
var markers = [];
var autocomplete;
var countryRestrict = {'country': 'us'};
var MARKER_PATH = 'https://developers.google.com/maps/documentation/javascript/images/marker_green';
var hostnameRegexp = new RegExp('^https?://.+?/');
var countries = {
'au': {
center: {lat: -25.3, lng: 133.8},
zoom: 4
},
'br': {
center: {lat: -14.2, lng: -51.9},
zoom: 3
},
'ca': {
center: {lat: 62, lng: -110.0},
zoom: 3
},
'fr': {
center: {lat: 46.2, lng: 2.2},
zoom: 5
},
'de': {
center: {lat: 51.2, lng: 10.4},
zoom: 5
},
'mx': {
center: {lat: 23.6, lng: -102.5},
zoom: 4
},
'nz': {
center: {lat: -40.9, lng: 174.9},
zoom: 5
},
'it': {
center: {lat: 41.9, lng: 12.6},
zoom: 5
},
'za': {
center: {lat: -30.6, lng: 22.9},
zoom: 5
},
'es': {
center: {lat: 40.5, lng: -3.7},
zoom: 5
},
'pt': {
center: {lat: 39.4, lng: -8.2},
zoom: 6
},
'us': {
center: {lat: 37.1, lng: -95.7},
zoom: 3
},
'uk': {
center: {lat: 54.8, lng: -4.6},
zoom: 5
}
};
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: countries['us'].zoom,
center: countries['us'].center,
mapTypeControl: false,
panControl: false,
zoomControl: false,
streetViewControl: false
});
infoWindow = new google.maps.InfoWindow({
content: document.getElementById('info-content')
});
// Create the autocomplete object and associate it with the UI input control.
// Restrict the search to the default country, and to place type "cities".
autocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */ (
document.getElementById('autocomplete')), {
types: ['(cities)'],
componentRestrictions: countryRestrict
});
places = new google.maps.places.PlacesService(map);
autocomplete.addListener('place_changed', onPlaceChanged);
// Add a DOM event listener to react when the user selects a country.
document.getElementById('country').addEventListener(
'change', setAutocompleteCountry);
}
// When the user selects a city, get the place details for the city and
// zoom the map in on the city.
function onPlaceChanged() {
var place = autocomplete.getPlace();
if (place.geometry) {
map.panTo(place.geometry.location);
map.setZoom(15);
search();
} else {
document.getElementById('autocomplete').placeholder = 'Enter a city';
}
}
// Search for hotels in the selected city, within the viewport of the map.
function search() {
var search = {
bounds: map.getBounds(),
types: ['lodging']
};
places.nearbySearch(search, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
clearResults();
clearMarkers();
// Create a marker for each hotel found, and
// assign a letter of the alphabetic to each marker icon.
for (var i = 0; i < results.length; i++) {
var markerLetter = String.fromCharCode('A'.charCodeAt(0) + (i % 26));
var markerIcon = MARKER_PATH + markerLetter + '.png';
// Use marker animation to drop the icons incrementally on the map.
markers[i] = new google.maps.Marker({
position: results[i].geometry.location,
animation: google.maps.Animation.DROP,
icon: markerIcon
});
// If the user clicks a hotel marker, show the details of that hotel
// in an info window.
markers[i].placeResult = results[i];
google.maps.event.addListener(markers[i], 'click', showInfoWindow);
setTimeout(dropMarker(i), i * 100);
addResult(results[i], i);
}
}
});
}
function clearMarkers() {
for (var i = 0; i < markers.length; i++) {
if (markers[i]) {
markers[i].setMap(null);
}
}
markers = [];
}
// Set the country restriction based on user input.
// Also center and zoom the map on the given country.
function setAutocompleteCountry() {
var country = document.getElementById('country').value;
if (country == 'all') {
autocomplete.setComponentRestrictions({'country': []});
map.setCenter({lat: 15, lng: 0});
map.setZoom(2);
} else {
autocomplete.setComponentRestrictions({'country': country});
map.setCenter(countries[country].center);
map.setZoom(countries[country].zoom);
}
clearResults();
clearMarkers();
}
function dropMarker(i) {
return function() {
markers[i].setMap(map);
};
}
function addResult(result, i) {
var results = document.getElementById('results');
var markerLetter = String.fromCharCode('A'.charCodeAt(0) + (i % 26));
var markerIcon = MARKER_PATH + markerLetter + '.png';
var tr = document.createElement('tr');
tr.style.backgroundColor = (i % 2 === 0 ? '#F0F0F0' : '#FFFFFF');
tr.onclick = function() {
google.maps.event.trigger(markers[i], 'click');
};
var iconTd = document.createElement('td');
var nameTd = document.createElement('td');
var icon = document.createElement('img');
icon.src = markerIcon;
icon.setAttribute('class', 'placeIcon');
icon.setAttribute('className', 'placeIcon');
var name = document.createTextNode(result.name);
iconTd.appendChild(icon);
nameTd.appendChild(name);
tr.appendChild(iconTd);
tr.appendChild(nameTd);
results.appendChild(tr);
}
function clearResults() {
var results = document.getElementById('results');
while (results.childNodes[0]) {
results.removeChild(results.childNodes[0]);
}
}
// Get the place details for a hotel. Show the information in an info window,
// anchored on the marker for the hotel that the user selected.
function showInfoWindow() {
var marker = this;
places.getDetails({placeId: marker.placeResult.place_id},
function(place, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
}
infoWindow.open(map, marker);
buildIWContent(place);
});
}
// Load the place information into the HTML elements used by the info window.
function buildIWContent(place) {
document.getElementById('iw-icon').innerHTML = '<img class="hotelIcon" ' +
'src="' + place.icon + '"/>';
document.getElementById('iw-url').innerHTML = '<b><a href="' + place.url +
'">' + place.name + '</a></b>';
document.getElementById('iw-address').textContent = place.vicinity;
if (place.formatted_phone_number) {
document.getElementById('iw-phone-row').style.display = '';
document.getElementById('iw-phone').textContent =
place.formatted_phone_number;
} else {
document.getElementById('iw-phone-row').style.display = 'none';
}
// Assign a five-star rating to the hotel, using a black star ('✭')
// to indicate the rating the hotel has earned, and a white star ('✩')
// for the rating points not achieved.
if (place.rating) {
var ratingHtml = '';
for (var i = 0; i < 5; i++) {
if (place.rating < (i + 0.5)) {
ratingHtml += '✩';
} else {
ratingHtml += '✭';
}
document.getElementById('iw-rating-row').style.display = '';
document.getElementById('iw-rating').innerHTML = ratingHtml;
}
} else {
document.getElementById('iw-rating-row').style.display = 'none';
}
// The regexp isolates the first part of the URL (domain plus subdomain)
// to give a short URL for displaying in the info window.
if (place.website) {
var fullUrl = place.website;
var website = hostnameRegexp.exec(place.website);
if (website === null) {
website = 'http://' + place.website + '/';
fullUrl = website;
}
document.getElementById('iw-website-row').style.display = '';
document.getElementById('iw-website').textContent = website;
} else {
document.getElementById('iw-website-row').style.display = 'none';
}
}
/* 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;
}
table {
font-size: 12px;
}
#map {
width: 440px;
}
#listing {
position: absolute;
width: 200px;
height: 470px;
overflow: auto;
left: 442px;
top: 0px;
cursor: pointer;
overflow-x: hidden;
}
#findhotels {
position: absolute;
text-align: right;
width: 100px;
font-size: 14px;
padding: 4px;
z-index: 5;
background-color: #fff;
}
#locationField {
position: absolute;
width: 190px;
height: 25px;
left: 108px;
top: 0px;
z-index: 5;
background-color: #fff;
}
#controls {
position: absolute;
left: 300px;
width: 140px;
top: 0px;
z-index: 5;
background-color: #fff;
}
#autocomplete {
width: 100%;
}
#country {
width: 100%;
}
.placeIcon {
width: 20px;
height: 34px;
margin: 4px;
}
.hotelIcon {
width: 24px;
height: 24px;
}
#resultsTable {
border-collapse: collapse;
width: 240px;
}
#rating {
font-size: 13px;
font-family: Arial Unicode MS;
}
.iw_table_row {
height: 18px;
}
.iw_attribute_name {
font-weight: bold;
text-align: right;
}
.iw_table_icon {
text-align: right;
}
<div id="findhotels">
Find hotels in:
</div>
<div id="locationField">
<input id="autocomplete" placeholder="Enter a city" type="text" />
</div>
<div id="controls">
<select id="country">
<option value="all">All</option>
<option value="au">Australia</option>
<option value="br">Brazil</option>
<option value="ca">Canada</option>
<option value="fr">France</option>
<option value="de">Germany</option>
<option value="mx">Mexico</option>
<option value="nz">New Zealand</option>
<option value="it">Italy</option>
<option value="za">South Africa</option>
<option value="es">Spain</option>
<option value="pt">Portugal</option>
<option value="us" selected>U.S.A.</option>
<option value="uk">United Kingdom</option>
</select>
</div>
<div id="map"></div>
<div id="listing">
<table id="resultsTable">
<tbody id="results"></tbody>
</table>
</div>
<div style="display: none">
<div id="info-content">
<table>
<tr id="iw-url-row" class="iw_table_row">
<td id="iw-icon" class="iw_table_icon"></td>
<td id="iw-url"></td>
</tr>
<tr id="iw-address-row" class="iw_table_row">
<td class="iw_attribute_name">Address:</td>
<td id="iw-address"></td>
</tr>
<tr id="iw-phone-row" class="iw_table_row">
<td class="iw_attribute_name">Telephone:</td>
<td id="iw-phone"></td>
</tr>
<tr id="iw-rating-row" class="iw_table_row">
<td class="iw_attribute_name">Rating:</td>
<td id="iw-rating"></td>
</tr>
<tr id="iw-website-row" class="iw_table_row">
<td class="iw_attribute_name">Website:</td>
<td id="iw-website"></td>
</tr>
</table>
</div>
</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"
async defer></script>

Unfortunately, this isn't possible.
The Place Autocomplete API doesn't support filtering to only hotel results. The list of supported types for Autocomplete filtering is documented on the Google Developers site: Types supported in place autocomplete requests. hotel is not in the list.

Related

How to line up an Amcharts single country on google maps api?

I am trying to replicate the amcharts demo seen here:
https://www.amcharts.com/docs/v4/tutorials/using-mapchart-with-google-maps-api/
to only show Canada:
What is the best way to lock these two layers together like the amcharts world demo?
I have tried setting bounds, but the zoom scales don't line up. I'm sure there's an easier way that I'm simply not aware of.
var gmap;
function initGoogleMap() {
gmap = new google.maps.Map(document.getElementById("gmap"), {
scrollwheel: true,
center: new google.maps.LatLng(56.130366, -106.346771),
zoom: 3,
disableDefaultUI: true
});
var swBound = new google.maps.LatLng(41.6765556, -141.00275);
var neBound = new google.maps.LatLng(83.3362128, -52.3231981);
var bounds = new google.maps.LatLngBounds(swBound, neBound);
// google.maps.event.addListener(gmap, 'bounds_changed', updateMapPosition);
gmap.fitBounds(bounds);
}
var ammap = am4core.create("ammap", am4maps.MapChart);
ammap.geodata = am4geodata_canadaLow;
ammap.projection = new am4maps.projections.Mercator();
ammap.zoomDuration = 0;
ammap.homeZoomLevel = 0;
ammap.homeGeoPoint = {
latitude: 56.130366,
longitude: -106.346771
};
var polygonSeries = ammap.series.push(new am4maps.MapPolygonSeries());
polygonSeries.useGeodata = true;
ammap.zoomControl = new am4maps.ZoomControl();
var polygonTemplate = polygonSeries.mapPolygons.template;
polygonTemplate.tooltipText = "{name}";
polygonTemplate.fill = am4core.color("#74B266");
polygonTemplate.fillOpacity = 0.5;
var hs = polygonTemplate.states.create("hover");
hs.properties.fill = am4core.color("#367B25");
ammap.events.on("zoomlevelchanged", updateMapPosition);
ammap.events.on("mappositionchanged", updateMapPosition);
ammap.events.on("scaleratiochanged", updateMapPosition);
function updateMapPosition(ev) {
if ( typeof gmap === "undefined" )
return;
gmap.setZoom(Math.log2(ammap.zoomLevel) + 3);
gmap.setCenter( {
// a small adjustment needed for this div size:
lat: ammap.zoomGeoPoint.latitude,
lng: ammap.zoomGeoPoint.longitude
} );
}
#maps {
width: 1000px;
height: 500px;
border: 0px solid #eee;
margin: 0px auto;
position: relative;
}
.mapdiv {
width: 1000px;
height: 500px;
position: absolute;
top: 0;
left: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initGoogleMap" defer></script>
<script src="https://www.amcharts.com/lib/4/core.js?ver=5.9.2"></script>
<script src="https://www.amcharts.com/lib/4/maps.js?ver=5.9.2"></script>
<script type='text/javascript' src='https://cdn.amcharts.com/lib/4/geodata/canadaLow.js?ver=5.9.2' id='am-canada-js'></script>
<!-- HTML -->
<div id="maps">
<div id="gmap" class="mapdiv" style="visibility: visible;"></div>
<div id="ammap" class="mapdiv" style="visibility: visible;"></div>
</div>

Google Maps: Resetting Markers with Coordinates

I'm working on a Google Maps API program that provides a nearbySearch function based on longitude and latitude, and user given locations. It works almost exactly as intended, but there's one final part that I've been having a lot of trouble with, and that's resetting the markers. Here's a screenshot of the code when initially ran, the search works as intended, you can see the results to the right, and there's a section showing user locations (orange markers) and the number of users tied to these locations:
But when the user enters a latitude and longitude, the map will update, but nothing else will.
Something that I thought may help, and seems like it could've been close was setting an if else statement for the initMap function, and having an onclick function from the submit button change it to false, thus changing the starting lat & lng with the user lat & lng:
function initMap() {
// Create the map.
if (true)
var SHU = {
lat: lat,
lng: lng
}
else {
var SHU = {
lat: newLatlat,
lng: newLng
}};
But messing with the onclick function of submit just ended up ruining other aspects of the code, so I come asking for help. Here's the code, and it should run without issue, but you may need an API key of your own.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Base Mapper</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style id="compiled-css" type="text/css">
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding-top: 10px;
padding-left: 10px;
padding-right: 10px;
background-color: #ffd1b2
}
#right-panel {
font-family: 'Roboto', 'sans-serif';
line-height: 30px;
padding-left: 10px;
}
#right-panel select,
#right-panel input {
font-size: 15px;
}
#right-panel select {
width: 100%;
}
#right-panel i {
font-size: 12px;
}
#right-panel {
font-family: Arial, Helvetica, sans-serif;
position: absolute;
right: 5px;
top: 60%;
margin-top: -395px;
height: 650px;
width: 200px;
padding: 10px;
padding-left: 10px;
z-index: 10;
border: 1px solid #999;
background: #fff;
}
h2 {
font-size: 23px;
margin: 0 0 5px 0;
}
ul {
list-style-type: none;
padding: 0;
margin: 0;
height: 580px;
width: 200px;
overflow-y: scroll;
}
li {
background-color: #ffc965;
padding: 5px;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
li:nth-child(odd) {
background-color: #fff065;
}
#more {
width: 100%;
margin: 5px 0 0 0;
}
input[type=text],
select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
background-color: #ffefe5
}
.container {
border-radius: 5px;
background-color: #ffd1b2
padding: 80px;
width: 80%
}
button {
width: 100%;
background-color: #8f20b6;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #cba00d;
}
table {
width: 100%;
background-color: #8f20b6;
color: white;
padding: 25px 0px;
margin: 8px 0;
border: none;
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<form id="mapCenterForm" action="" onsubmit="return false;">
<label for="latitude">lat</label>
<input type="text" id="lat" name="latitude" placeholder="0.000000">
<label for="longitude">lng</label>
<input type="text" id="lng" name="longitude" placeholder="0.000000">
<br>
<button onclick="change_center(); return false">
Submit
</button>
</form>
<div id="map" style="height: 500px"></div>
</div>
<div id="right-panel">
<h2>Locations</h2>
<div id="number_results"></div>
<ul id="places"></ul>
<button id="more">More Results</button>
</div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIza...&callback=initMap" async defer></script>
<script type="text/javascript">
var blue_icon = 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png';
var orange_icon = 'http://maps.google.com/mapfiles/ms/icons/orange-dot.png';
var map;
var lat = 41.18076;
var lng = -73.20537;
var userLoc = 0;
var userCount = 0;
var stopper = 1;
function initMap() {
// Create the map.
if (true)
var SHU = {
lat: lat,
lng: lng
}
else {
var SHU = {
lat: newLatlat,
lng: newLng
}};
map = new google.maps.Map(document.getElementById('map'), {
center: SHU,
zoom: 13
});
google.maps.event.addListener(map, 'click', function(e) {
document.getElementById('lat').value = e.latLng.lat();
document.getElementById('lng').value = e.latLng.lng();
})
// Create the places service.
var service = new google.maps.places.PlacesService(map);
var getNextPage = null;
var moreButton = document.getElementById('more');
moreButton.onclick = function() {
moreButton.disabled = true;
if (getNextPage) getNextPage();
};
service.nearbySearch({
location: SHU,
radius: 4000,
keyword: "(library) OR (hospital)"
},
function(results, status, pagination) {
if (status !== 'OK') return;
createMarkers(results);
moreButton.disabled = !pagination.hasNextPage;
getNextPage = pagination.hasNextPage && function() {
pagination.nextPage();
};
});
}
function createMarkers(places) {
var harry = new google.maps.Marker({
position: {lat: 41.18076, lng: -73.20537},
map: map,
icon: orange_icon,
title: 'Harry & Martha Richardson'
})
if (((lat>40.78076&&lat<41.58076)||(lng>-73.60537&&lng<-72.80537))&&(stopper==1))
{ userLoc = userLoc+1
userCount = userCount+2 };
var Maria = new google.maps.Marker({
position: {lat: 41.14055, lng: -73.26827},
map: map,
icon: orange_icon,
title: 'Maria Blane'
})
if (((lat>40.74055&&lat<41.54055)||(lng>-74.00537&&lng<-73.20537))&&(stopper==1))
{ userLoc = userLoc+1
userCount = userCount+1};
var Kent = new google.maps.Marker({
position: {lat: 41.19613, lng: -73.21837},
map: map,
icon: orange_icon,
title: 'Kent, Pedro, Natasha'
})
if (((lat>40.79613&&lat<41.59613)||(lng>-73.61837&&lng<-72.81837))&&(stopper==1))
{ userLoc = userLoc+1
userCount = userCount+3 };
var DummyVar1 = new google.maps.Marker({
position: {lat: 38.897957, lng: -77.036560},
map: map,
icon: orange_icon,
title: 'Dummy Name'
})
if (((lat>38.497957&&lat<39.297957)||(lng>-77.43656&&lng<-76.63656))&&(stopper==1))
{ userLoc = userLoc+1
userCount = userCount+100 };
var DummyVar2 = new google.maps.Marker({
position: {lat: 36.056595, lng: -112.125092},
map: map,
icon: orange_icon,
title: 'Dummier Name'
})
if ((lat>35.656595&&lat<36.456595)||(lng>-112.525092&&lng<-111.725092))
{ userLoc = userLoc+1
userCount = userCount+100
};
{ stopper = 0 };
var bounds = new google.maps.LatLngBounds();
var placesList = document.getElementById('places');
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)
};
var marker = new google.maps.Marker({
map: map,
icon: blue_icon,
title: place.name,
position: place.geometry.location
});
var li = document.createElement('li');
li.textContent = place.name;
placesList.appendChild(li);
document.getElementById('number_results').innerHTML = placesList.children.length + " returned";
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
document.getElementById("val").innerHTML = "Based on your latitude of " + lat + " and longitude of " + lng +
", the total places found is: " + (document.getElementById('places').children.length) + ". User locations: " + userLoc + ". Total users: " + userCount + ".";
}
function change_center() {
var newLat = parseFloat(document.getElementById("lat").value);
var newLng = parseFloat(document.getElementById("lng").value);
map.setCenter({
lat: newLat,
lng: newLng
});
return false;
}
</script>
<script>
// tell the embed parent frame the height of the content
if (window.parent && window.parent.parent){
window.parent.parent.postMessage(["resultsFrame", {
height: document.body.getBoundingClientRect().height,
slug: "r96szuhx"
}], "*")
}
// always overwrite window.name, in case users try to set it manually
window.name = "result"
</script>
<table>
<tr>
<th id="val"></th>
</tr>
</table>
</body>
</html>
You need to re-run the query when the map center changes. I would suggest putting that query into a function you can call both places (and tracking the markers so you can remove them when you start a new query):
function nearbySearch() {
document.getElementById('places').innerHTML = "";
for (var i=0; i<markers.length;i++) {
markers[i].setMap(null);
}
markers = [];
// Create the places service.
var service = new google.maps.places.PlacesService(map);
var getNextPage = null;
var moreButton = document.getElementById('more');
moreButton.onclick = function() {
moreButton.disabled = true;
if (getNextPage) getNextPage();
};
service.nearbySearch({
location: map.getCenter(),
radius: 4000,
keyword: "(library) OR (hospital)"
},
function(results, status, pagination) {
if (status !== 'OK') return;
createMarkers(results);
moreButton.disabled = !pagination.hasNextPage;
getNextPage = pagination.hasNextPage && function() {
pagination.nextPage();
};
});
}
working code snippet:
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding-top: 10px;
padding-left: 10px;
padding-right: 10px;
background-color: #ffd1b2
}
#right-panel {
font-family: 'Roboto', 'sans-serif';
line-height: 30px;
padding-left: 10px;
}
#right-panel select,
#right-panel input {
font-size: 15px;
}
#right-panel select {
width: 100%;
}
#right-panel i {
font-size: 12px;
}
#right-panel {
font-family: Arial, Helvetica, sans-serif;
position: absolute;
right: 5px;
top: 60%;
margin-top: -395px;
height: 650px;
width: 200px;
padding: 10px;
padding-left: 10px;
z-index: 10;
border: 1px solid #999;
background: #fff;
}
h2 {
font-size: 23px;
margin: 0 0 5px 0;
}
ul {
list-style-type: none;
padding: 0;
margin: 0;
height: 580px;
width: 200px;
overflow-y: scroll;
}
li {
background-color: #ffc965;
padding: 5px;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
li:nth-child(odd) {
background-color: #fff065;
}
#more {
width: 100%;
margin: 5px 0 0 0;
}
input[type=text],
select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
background-color: #ffefe5
}
.container {
border-radius: 5px;
background-color: #ffd1b2 padding: 80px;
width: 80%
}
button {
width: 100%;
background-color: #8f20b6;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #cba00d;
}
table {
width: 100%;
background-color: #8f20b6;
color: white;
padding: 25px 0px;
margin: 8px 0;
border: none;
cursor: pointer;
}
<div class="container">
<form id="mapCenterForm" action="" onsubmit="return false;">
<label for="latitude">lat</label>
<input type="text" id="lat" name="latitude" placeholder="0.000000">
<label for="longitude">lng</label>
<input type="text" id="lng" name="longitude" placeholder="0.000000">
<br>
<button onclick="change_center(); return false">
Submit
</button>
</form>
<div id="map" style="height: 500px"></div>
</div>
<div id="right-panel">
<h2>Locations</h2>
<div id="number_results"></div>
<ul id="places"></ul>
<button id="more">More Results</button>
</div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>
<script type="text/javascript">
var blue_icon = 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png';
var orange_icon = 'http://maps.google.com/mapfiles/ms/icons/orange-dot.png';
var map;
var lat = 41.18076;
var lng = -73.20537;
var userLoc = 0;
var userCount = 0;
var stopper = 1;
var markers = [];
function initMap() {
// Create the map.
var SHU = {
lat: lat,
lng: lng
}
map = new google.maps.Map(document.getElementById('map'), {
center: SHU,
zoom: 13
});
google.maps.event.addListener(map, 'click', function(e) {
document.getElementById('lat').value = e.latLng.lat();
document.getElementById('lng').value = e.latLng.lng();
})
nearbySearch();
}
function createMarkers(places) {
var harry = new google.maps.Marker({
position: {
lat: 41.18076,
lng: -73.20537
},
map: map,
icon: orange_icon,
title: 'Harry & Martha Richardson'
})
if (((lat > 40.78076 && lat < 41.58076) || (lng > -73.60537 && lng < -72.80537)) && (stopper == 1)) {
userLoc = userLoc + 1
userCount = userCount + 2
};
var Maria = new google.maps.Marker({
position: {
lat: 41.14055,
lng: -73.26827
},
map: map,
icon: orange_icon,
title: 'Maria Blane'
})
if (((lat > 40.74055 && lat < 41.54055) || (lng > -74.00537 && lng < -73.20537)) && (stopper == 1)) {
userLoc = userLoc + 1
userCount = userCount + 1
};
var Kent = new google.maps.Marker({
position: {
lat: 41.19613,
lng: -73.21837
},
map: map,
icon: orange_icon,
title: 'Kent, Pedro, Natasha'
})
if (((lat > 40.79613 && lat < 41.59613) || (lng > -73.61837 && lng < -72.81837)) && (stopper == 1)) {
userLoc = userLoc + 1
userCount = userCount + 3
};
var DummyVar1 = new google.maps.Marker({
position: {
lat: 38.897957,
lng: -77.036560
},
map: map,
icon: orange_icon,
title: 'Dummy Name'
})
if (((lat > 38.497957 && lat < 39.297957) || (lng > -77.43656 && lng < -76.63656)) && (stopper == 1)) {
userLoc = userLoc + 1
userCount = userCount + 100
};
var DummyVar2 = new google.maps.Marker({
position: {
lat: 36.056595,
lng: -112.125092
},
map: map,
icon: orange_icon,
title: 'Dummier Name'
})
if ((lat > 35.656595 && lat < 36.456595) || (lng > -112.525092 && lng < -111.725092)) {
userLoc = userLoc + 1
userCount = userCount + 100
}; {
stopper = 0
};
var bounds = new google.maps.LatLngBounds();
var placesList = document.getElementById('places');
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)
};
var marker = new google.maps.Marker({
map: map,
icon: blue_icon,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
var li = document.createElement('li');
li.textContent = place.name;
placesList.appendChild(li);
document.getElementById('number_results').innerHTML = placesList.children.length + " returned";
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
document.getElementById("val").innerHTML = "Based on your latitude of " + lat + " and longitude of " + lng +
", the total places found is: " + (document.getElementById('places').children.length) + ". User locations: " + userLoc + ". Total users: " + userCount + ".";
}
function change_center() {
var newLat = parseFloat(document.getElementById("lat").value);
var newLng = parseFloat(document.getElementById("lng").value);
map.setCenter({
lat: newLat,
lng: newLng
});
nearbySearch();
return false;
}
function nearbySearch() {
document.getElementById('places').innerHTML = "";
for (var i=0; i<markers.length;i++) {
markers[i].setMap(null);
}
markers = [];
// Create the places service.
var service = new google.maps.places.PlacesService(map);
var getNextPage = null;
var moreButton = document.getElementById('more');
moreButton.onclick = function() {
moreButton.disabled = true;
if (getNextPage) getNextPage();
};
service.nearbySearch({
location: map.getCenter(),
radius: 4000,
keyword: "(library) OR (hospital)"
},
function(results, status, pagination) {
if (status !== 'OK') return;
createMarkers(results);
moreButton.disabled = !pagination.hasNextPage;
getNextPage = pagination.hasNextPage && function() {
pagination.nextPage();
};
});
}
</script>
<table>
<tr>
<th id="val"></th>
</tr>
</table>

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.

Adding multiple markers in google map from javaFX application by executing webengine.executescript method

I am trying to add multiple markers from my javaFX application through the webengine.executescript() method .I have fallen the method in a loop to show all the markers but it just shows the last positioned marker .Here is my javaFx code for that
Button refresh = new Button("Refresh");
refresh.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
String[] latitude = {"23.806744","10"};
String[] longitude = {"90.3685549","20"};
//networking should be here
for (int i = 0; i < latitude.length; i++) {
lat = Double.parseDouble(latitude[i]);
lon = Double.parseDouble(longitude[i]);
System.out.printf("%.2f %.2f%n", lat, lon);
webEngine.executeScript("" +
"window.lat = " + lat + ";" +
"window.lon = " + lon + ";" +
"document.goToLocation(window.lat,window. lon);"
);
}
}
}
);
function initMap() {
var latlng = new google.maps.LatLng(35.857908, 10.598997);
var origin_place_id = null;
var destination_place_id = null;
var travel_mode = google.maps.TravelMode.DRIVING;
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
directionsDisplay.setMap(map);
var origin_input = document.getElementById('origin-input');
var destination_input = document.getElementById('destination-input');
var modes = document.getElementById('mode-selector');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(origin_input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(destination_input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(modes);
var origin_autocomplete = new google.maps.places.Autocomplete(origin_input);
origin_autocomplete.bindTo('bounds', map);
var destination_autocomplete =
new google.maps.places.Autocomplete(destination_input);
destination_autocomplete.bindTo('bounds', map);
function expandViewportToFitPlace(map, place) {
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
}
origin_autocomplete.addListener('place_changed', function() {
var place = origin_autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
expandViewportToFitPlace(map, place);
// If the place has a geometry, store its place ID and route if we have
// the other place ID
origin_place_id = place.place_id;
route(origin_place_id, destination_place_id, travel_mode,
directionsService, directionsDisplay);
});
destination_autocomplete.addListener('place_changed', function() {
var place = destination_autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
expandViewportToFitPlace(map, place);
// If the place has a geometry, store its place ID and route if we have
// the other place ID
destination_place_id = place.place_id;
route(origin_place_id, destination_place_id, travel_mode,
directionsService, directionsDisplay);
});
function route(origin_place_id, destination_place_id, travel_mode,
directionsService, directionsDisplay) {
if (!origin_place_id || !destination_place_id) {
return;
}
directionsService.route({
origin: {'placeId': origin_place_id},
destination: {'placeId': destination_place_id},
provideRouteAlternatives: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
for (var i = 0, len = response.routes.length; i < len; i++) {
new google.maps.DirectionsRenderer({
map: map,
directions: response,
routeIndex: i
});
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
var marker = new google.maps.Marker({
position: new google.maps.LatLng(0,0),
map: map,
draggable: false,
title: "",
autoPan: false
});
document.goToLocation = function(x, y) {
alert("goToLocation, x: " + x +", y:" + y);
var latlng = new google.maps.LatLng(x, y);
marker.setPosition(latlng);
//map.setCenter(latLng);
}
}
<!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 {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
width:100%;
}
.controls {
margin-top: 15px;
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="map"></div>
It would be nice if anyone could help
Your problem is you create your marker only once. You then call document.goToLocation in your loop, simply updating the position of that one marker every time. At the end of the loop, it has the position of the last of those locations.
If you want a marker on every location, create a marker inside the document.goToLocation function:
document.goToLocation = function(x, y) {
alert("goToLocation, x: " + x +", y:" + y);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(x, y),
map: map,
draggable: false,
title: "",
autoPan: false
});
}

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