Cannot read property 'setPosition' HTML5 - html

My objective right now is to basically add a marker wherever the user is in the google maps. The API works, a KML file I added with polygons work and i'm sure it doesn't mess with any of the code so far.
However, I have" Cannot read property 'setPosition' of undefined" error at line 99 of the code. it will probably have an easy solution but I cannot see it myself.
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAjp8cvAcEYCwzuCyTQORL3Z1iQPdQMg_8&callback=initMap" async defer>
</script>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<title>Protoype: Just Don't</title>
<meta charset="utf-8">
<style>
html, body, #map {
height: 100%;
margin: 0;
padding: 0;
}
/* Style the buttons so that they are consistently coloured and sized */
.button {
background-color: #008CBA; /* Blue */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
/* Style the search box */
.search input[type=text] {
float: right;
padding: 6px;
border: none;
margin-top: 8px;
margin-right: 16px;
font-size: 17px;
}
/* When the screen is less than 640px wide, stack the search field vertically instead of horizontally */
#media screen and (max-width: 640px) {
.search a, .search input[type=text] {
float: none;
display: block;
text-align: left;
width: 100%;
margin: 0;
padding: 14px;
}
.search input[type=text] {
border: 1px solid #ccc;
}
}
</style>
</head>
<body>
<h3>Just don't app test</h3>
<div class="search">
<input type=text placeholder="Search..">
</div>
Settings
Account
Add Review
<div id="map"></div>
<script>
var map, infoWindow;
function initMap() {
InfoWindow = new google.maps.InfoWindow;
var Paisley = {lat: 55.845890, lng: -4.423741};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
center: Paisley
});
var kmlLayer = new google.maps.KmlLayer({
url: 'https://firebasestorage.googleapis.com/v0/b/just-don-t.appspot.com/o/Project%20examples.kml?alt=media&token=65140cfc-de3a-4658-8b2b-0354f4909d38',
suppressInfoWindows: true,
map: map
});
kmlLayer.addListener('click', function(kmlEvent) {
var text = kmlEvent.featureData.description;
showInContentWindow(text);
});
function showInContentWindow(text) {
var sidediv = document.getElementById('content-window');
sidediv.innerHTML = text;
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
;
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition (pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
</script>
</body>
Any tips on how to solve it or if you find another problem in my code will be greatly appreciated.

The main issue I believe was the mismatch in variable names. Initially you declared InfoWindow when creating the reference but throughout thereafter refer to infoWindow. Additionally the functions showInContentWindow and handleLocationError needn't be declared within the initMap function.
The following works OK - but the geoLocation puts the Location found nowhere near Paisley for me ... the css here was just basic for testing.
Anyone would think Paisley was an unsafe place after dark judging by some of the descriptions that appear when clicking on the KML Layer - never saw much of Paisley when we used to go to 'Club69' back in the day...
<html>
<head>
<meta charset='utf-8' />
<title>Google Maps: KML Layer</title>
<script id='gm' async defer src="//maps.google.com/maps/api/js?key=AIzaSyAjp8cvAcEYCwzuCyTQORL3Z1iQPdQMg_8&callback=initMap&region=en-GB&language=en"></script>
<script>
var infowindow, map, Paisley, kmlLayer;
var text, pos
function initMap(){
infowindow = new google.maps.InfoWindow;
Paisley = { lat: 55.845890, lng: -4.423741 };
map = new google.maps.Map( document.getElementById('map'), {
zoom: 17,
center: Paisley
});
kmlLayer = new google.maps.KmlLayer({
url: 'https://firebasestorage.googleapis.com/v0/b/just-don-t.appspot.com/o/Project%20examples.kml?alt=media&token=65140cfc-de3a-4658-8b2b-0354f4909d38',
suppressInfoWindows: true,
map: map
});
kmlLayer.addListener( 'click', function( event ) {
text = event.featureData.description;
showInContentWindow( text );
});
if( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition( function( position ) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infowindow.setPosition( pos );
infowindow.setContent( 'Location found.' );
infowindow.open( map );
map.setCenter( pos );
console.info( 'Location found: %s, %s', pos.lat, pos.lng );
}, function() {
handleLocationError( true, infowindow, map.getCenter() );
});
} else {
handleLocationError( false, infowindow, map.getCenter() );
}
}
function showInContentWindow( text ) {
document.getElementById('content-window').innerHTML = text;
}
function handleLocationError( browserHasGeolocation, infowindow, pos ) {
infowindow.setPosition( pos );
infowindow.setContent( browserHasGeolocation ? 'Error: The Geolocation service failed.' : 'Error: Your browser doesn\'t support geolocation.');
infowindow.open( map );
}
</script>
<style>
body{ background:white; }
#container{
width: 90%;
min-height: 90vh;
height:auto;
box-sizing:border-box;
margin: auto;
float:none;
margin:1rem auto;
background:whitesmoke;
padding:1rem;
border:1px solid gray;
display:block;
}
#map {
width: 100%;
height: 100%;
clear:none;
display:block;
z-index:1!important;
background:white;
}
</style>
</head>
<body>
<div id='container'>
<div id='map'></div>
<div id='content-window'></div>
</div>
</body>
</html>

Related

Google Maps AutoComplete and Directions with fixed destination and variable origin

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

Google Maps SearchBox not searching in bounds

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

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

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

how to add my location button to google map

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

Info window showing empty / blank on Google Fusion Map layers

I'm trying to make a side by side Google Fusion Map and while that seems to be working OK, when I click on a polygon, the info window shows up as blank.
I'm trying to work out why it might not be picking up and displaying the information from the table, when the rest of the data seems to be showing up.
The map is here: http://clairemiller.net/blaenaupop.html
The code I'm using to display that is:
<!DOCTYPE html>
<html>
<head>
<style>
#map_canvas { width: 335px; height: 400px; float: left}
#map_canvas2 { width: 335px; height: 400px; }
#image {float: bottom}
body { margin: 0px}
p {color: white; font-family: arial; font-size: 12px; margin: 0px; position: relative; left: 4px; top: 3px }
#left { width: 335px; height: 20px; float: left; background-color: #007A8F}
#right { width: 335px; height: 20px; float: left; background-color: #005F70}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<script type="text/javascript">
var map;
var layer;
var layer2;
var secondMapMove = false;
var secondMapBounds = false;
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(51.787578, -3.204393),
zoom: 12,
mapTypeId: 'roadmap'
});
var layer = new google.maps.FusionTablesLayer({
center: new google.maps.LatLng(51.5021181, -3.17909),
query: {
select: 'geometry',
from: '1F3SbppvMyF-3lcT5zrYS8S1X8JD1G2-0aQkWLPw',
}
});
layer.setMap(map);
map2 = new google.maps.Map(document.getElementById('map_canvas2'), {
zoom: 12,
mapTypeId: 'roadmap'
});
var layer2 = new google.maps.FusionTablesLayer({
center: new google.maps.LatLng(53.13359,-1.955566),
query: {
select: 'geometry',
from: '1Hf9Z80JTCiq-zWwhhSPrbifO7q9dvA_DP_BN8IY',
}
});
layer2.setMap(map2);
google.maps.event.addListener(map,'zoom_changed',function(){
if(secondMapBounds!=true) {
var tmpZoom = map.getZoom();
map2.setZoom(tmpZoom);
} else {
secondMapBounds = false;
}
});
google.maps.event.addListener(map2,'zoom_changed',function(){
secondMapBounds = true;
var tmpZoom1 = map2.getZoom();
map.setZoom(tmpZoom1);
});
google.maps.event.addListener(map,'bounds_changed',function(){
if(secondMapMove!=true) {
var tmpBounds = map.getCenter();
map2.setCenter(tmpBounds);
} else {
secondMapMove=false;
}
});
google.maps.event.addListener(map2,'bounds_changed',function(){
secondMapMove = true
var tmpBounds2 = map2.getCenter();
map.setCenter(tmpBounds2);
});
}
</script>
</head>
<body onload="initialize();">
<div class="mapMap" id="map_canvas"></div>
<div class="mapMap" id="map_canvas2"></div>
</body>
</html>
The IDs for the two tables are in there, the infowindow appears to be showing up fine on them.
I'm wondering what I've missed that is causing the infowindows to show up blank.
It doesn't show blank, it shows white.
The contents of the infoWindows are inside <p/>-elements, the background of the infoWindows is white, and this is your CSS:
p {color: white;/*......*/}
change the color
.googft-info-window p{color:#000;}