Save Map Instance outside of Google Maps - html

I've made a google maps API (HTML) script that created markers when the user clicks on the map. I've also integrated Google+ login functions so users are unique and have profiles. I now want to make it so users can create their markers on their desired positions and then save the map so they can come back to it later. I however don't want them to use this "https://developers.google.com/maps/documentation/javascript/examples/save-widget" provided function because then the markers are synched to their google+. In other words I only want the markers to save to my website, not to their personal google maps. How would I go about saving the state of the map only on my site?
Heres the fiddle of my code: https://jsfiddle.net/hgvsurt5/
Heres the code:
<head>
<style>
#map-canvas {
width: 900px;
height: 600px;
}
.controls {
margin-top: 16px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
</style>
<title>Places search box</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<script>
// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
function initialize() {
var marker = []
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
map.fitBounds(defaultBounds);
// Create the search box and link it to the UI element.
var input = /** #type {HTMLInputElement} */
(
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(
/** #type {HTMLInputElement} */
(input));
// [START region_getplaces]
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
</script>
<script>
var map;
var myCenter = new google.maps.LatLng(51.508742, -0.120850);
function initialize() {
var mapProp = {
center: myCenter,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
draggable: true,
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() + '<br>Longitude: ' + location.lng()
});
infowindow.open(map, marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:900px;height:600px;"></div>
</body>

You must somehow bring the desired data into a format which may be sended and stored. A good approach would be to use a Data-layer to draw the features on the map, you may easily use the method toGeoJson of the Data-layer to convert the data into a geoJson and send it to a server(where you store the data).
A simple implementation:
function initialize() {
var map = new google.maps.Map(document.getElementById("googleMap"), {
center: new google.maps.LatLng(51.508742, -0.120850),
zoom: 5,
noClear: true
}),
//this may be the stored data
data = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-0.120850, 51.508742]
},
"properties": {}
}]
},
win = new google.maps.InfoWindow,
//some buttons for interaction
ctrl = document.getElementById('datactrl'),
fx = {
'data-save': {
click: function() {
//use this method to store the data somewhere,
//e.g. send it to a server
map.data.toGeoJson(function(json) {
data = json;
});
}
},
'data-show': {
click: function() {
alert('you may send this JSON-string to a server and store it there:\n\n' +
JSON.stringify(data))
}
},
'data-load': {
click: function() {
//use this method to load the data from somwhere
//e.g. from a server via loadGeoJson
map.data.forEach(function(f) {
map.data.remove(f);
});
map.data.addGeoJson(data)
},
init: true
},
'data-clear': {
click: function() {
//use this method to clear the data
//when you also want to remove the data on the server
//send a geoJSON with empty features-array to the server
map.data.forEach(function(f) {
map.data.remove(f);
});
data = {
type: "FeatureCollection",
features: []
};
}
}
};
for (var id in fx) {
var o = ctrl.querySelector('input[id=' + id + ']');
google.maps.event.addDomListener(o, 'click', fx[id].click);
if (fx[id].init) {
google.maps.event.trigger(o, 'click');
}
}
map.controls[google.maps.ControlPosition.TOP_CENTER].push(ctrl);
function placeMarker(location) {
var feature = new google.maps.Data.Feature({
geometry: location
});
map.data.add(feature);
}
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
google.maps.event.addListener(map.data, 'click', function(e) {
if (e.feature.getGeometry().getType() === 'Point') {
win.setOptions({
content: 'Latitude: ' + e.feature.getGeometry().get().lat() +
'<br>Longitude: ' + e.feature.getGeometry().get().lng(),
pixelOffset: new google.maps.Size(0, -40),
map: map,
position: e.feature.getGeometry().get()
});
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#googleMap {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="googleMap">
<div id="datactrl">
<input type="button" id="data-save" value="save" />
<input type="button" id="data-show" value="show saved data" />
<input type="button" id="data-load" value="load saved data" />
<input type="button" id="data-clear" value="remove all data" />
</div>
</div>

Related

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 turn off the Bicycling layer after it gets turned on by the DirectionsRenderer

In the documentation on Layers in the Google Maps API, the following is stated:
The Bicycling layer object renders a layer of bike paths and/or bicycle-specific overlays into a common layer. This layer is returned by default within the DirectionsRenderer when requesting directions of travel mode BICYCLING.
How would one turn off this Bicycling Layer after it got turned on by the DirectionsRenderer? I do want to show the biking route, but don't want all the green lines of the Bicycling Layer mess up the clarity of the map.
Is there a way to 'get' the current Bicycling Layer, and turn it off/unbind it from the map that way?
Just disable the display of the bicyclingLayer by the DirectionsRenerer, per the documentation for the DirectionsRendererOptions you can suppress the BicycleLayer by using the suppressBicyclingLayer option in the DirectionsRendererOptions:
suppressBicyclingLayer | Type: boolean | Suppress the rendering of the BicyclingLayer when bicycling directions are requested.
proof of concept fiddle
code snippet:
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
suppressBicyclingLayer: true
});
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {
lat: 41.85,
lng: -87.65
}
});
directionsDisplay.setMap(map);
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
calculateAndDisplayRoute(directionsService, directionsDisplay);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
travelMode: 'BICYCLING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
#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;
}
<div id="floating-panel">
<b>Start: </b>
<input id="start" value="New York, NY" />
<br><b>End: </b>
<input id="end" value="Newark, NJ" />
</div>
<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?callback=initMap">
</script>
You can just use layer.setMap(null).
Something like:
var map = new google.maps.Map(document.getElementById('myMap')
var bikeLayer = new google.maps.BicyclingLayer();
document.getElementById("showBikeLayer").addEventListener("click", function(){
bikeLayer.setMap(map);
});
document.getElementById("hideBikeLayer").addEventListener("click", function(){
bikeLayer.setMap(null);
});

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

Google Map Event listener

I have a problem in event listener. I created 'click' event listener in 'map', every time the user clicks on the map a new marker is created. Each marker has it's own infobox that contains a link to remove the marker.
The problem is when i click the remove link inside the infobox, the map's click event is always triggered. The marker is successfully removed but the it creates a new marker. How can i fix this? I just want to remove the marker.
here's the code:
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=123456778&sensor=true"></script>
<script type="text/javascript" src="infobox.js"></script>
<script type="text/javascript">
var map;
var markers = [];
var infowindows = [];
var marker_cnt = 0;
var marker_icons = { 'mall' : 'mall.png', 'train_station': 'train.png','park' : 'park.png', 'bank':'bank.png'};
var infoWindow;
var places = [
['Central','mall',1.2892612468505713,103.84759068489075,'central mall'] ,
['Dhoby Ghaut','train_station',1.298550049775337,103.84589552879333,'Dhoby Ghaut'] ,
['Outram Station', 'train_station',1.2812595487889478, 103.83896470069885,'Outram Station'],
['City Hall', 'bank', 1.2932084559435784, 103.85241866111755,'City Hall Station'],
['Little India Station', 'train_station', 1.3071308997488136, 103.84971499443054,'Little India Station'],
['Emily Park', 'park', 1.3071308997488136, 103.84971499443054,'Emily Park']
];
var myOptions = {
content: 'loading...'
,boxStyle: {
background: "#ccc"
,opacity: 1
,width: "280px"
,height: "100px"
,padding: "10px"
}
,closeBoxMargin: "10px 2px 2px 2px"
,closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif"
,pane: "floatPane"
,enableEventPropagation: false
};
var infowindow = new InfoBox(myOptions);
google.maps.event.addListener(infowindow, 'click', function () {
console.log('aaaa');
});
function initialize()
{
var myLatlng = new google.maps.LatLng(1.2892826990902386,103.84409308433533);
var myOptions = {
zoom: 16,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', function(event){
placeMarker(event.latLng,event.getPosition);
});
loadMarkers();
}
function loadMarkers()
{
for(var i = 0 ; i < places.length; i++)
{
var spot = places[i];
var spot_latlng = new google.maps.LatLng(spot[2],spot[3]) ;
var marker = new google.maps.Marker({
map:map,
draggable:false,
position: spot_latlng,
title: spot[0],
icon: marker_icons[spot[1]],
html: '<h1>'+spot[4]+'</h1> website '
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
}
function unloadMarkers()
{
for(var i = 0; i < markers.length; i++)
{
markers[i].setMap(null);
}
}
function setMapCenter(index)
{
var spot = places[index];
var spot_latlng = new google.maps.LatLng(spot[2],spot[3]);
infowindow.setContent(markers[index].html = spot[4]);
infowindow.open(map, markers[index]);
map.setCenter(spot_latlng);
}
function placeMarker(location,position)
{
marker = new google.maps.Marker({
map:map,
draggable:true,
animation: google.maps.Animation.DROP,
position: location,
html: 'delete marker <br/> '+ location
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
google.maps.event.addListener(marker,'dragend',function(){
var html_content = 'delete marker <br/>'+ this.position;
this.html=html_content;
infowindow.setContent(this.html);
infowindow.open(map,this);
});
google.maps.event.addListener(marker,'dragstart',function(){
infowindow.close(map,this);
});
}
function removeMarker(index)
{
markers[index].setMap(null);
infowindow.close(map, markers[index]);
infowindows[index].close();
return false;
}
</script>
<style type="text/css">
html{
font:12px Arial, Helvetica, sans-serif;
color:#333;
padding:0;
margin:0;
}
.listmenu{
height:300px;
}
.listmenu ul {
margin: 0 0 5px 0;
padding: 0 0 2px 0;
list-style-type: none;
width:185px;
}
.listmenu li a {
color: #333;
display: block;
height: 16px;
padding: 4px 0 4px 14px;
text-decoration: none;
font-weight:bold;
background-color:#fff;
}
.listmenu li a:hover {
background-color: #666;
color:#fff;
}
</style>
<body onload="initialize()">
<div id="map_canvas" style="width:1000px; height:300px; border: 3px solid #666"></div>
pass the click-event as argument to removeMarker()
marker = new google.maps.Marker({
map:map,
draggable:true,
animation: google.maps.Animation.DROP,
position: location,
html: '<a href="#" onclick="removeMarker('+ (markers.length) +',event)">\
delete marker</a> <br/> '+ location
});
Then you'll be able to stop the propagation of the event:
function removeMarker(index,event)
{
try{event.cancelBubble=true;}//IE
catch(e){event.stopPropagation();}//others
markers[index].setMap(null);
infowindow.close(map, markers[index]);
return false;
}
Thanks for the reply. I already solved this problem. I fixed it by removing "onclick" and placing javascript to href <a href='javascript: removeMarker(index)'> remove </a>