Google maps custom control always appears below the default controls - google-maps

I'd like to add a custom map control to a Google Maps v3 map. My custom control is the grayed-out 'location' icon in the screenshot below.
The problem is that I need the custom control to be below the pan ('arrows') control, but above the pegman / street view control. I have tried setting "index = -3" on the div I'm using for the control (see the v3 custom control positioning docs), with no luck.
wrapperDiv = document.createElement('div');
/* Some code appends an image to wrapperDiv in my actual code */
wrapperDiv.index = -3;
map.controls[google.maps.ControlPosition.LEFT_TOP].push( wrapperDiv );
Any ideas?
Update - solution found
Using the answer, provided by geocodezip, my custom control is now between the pan control and pegman control:
Most of the controls are now further over to the left than normal, but there doesn't seem to be a way to work around that, as far as I can tell.
Follow-up question
Now that my custom control is in the right place, is there a way to make the pegman and zoom controls centered below the pan control, like they are in the first screenshot?

One idea/option (not optimal but does sort of what you want).
Put the pan control in the TOP_LEFT controls position.
Put the custom control at index -1 (before all the normal controls) in LEFT_TOP
from the documentation: Positioning Custom Controls:...snip...
The API places controls at each position by the order of an index property; controls with a lower index are placed first. For example, two custom controls at position BOTTOM_RIGHT will be laid out according to this index order, with lower index values taking precedence. By default, all custom controls are placed after placing any API default controls. You can override this behavior by setting a control's index property to be a negative value. Custom controls cannot be placed to the left of the logo or to the right of the copyrights.
var mapOptions = {
zoom: 12,
center: chicago,
disableDefaultUI: true,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.RIGHT_TOP
},
scaleControl: true,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT
},
streetViewControl: true,
streetViewControlOptions: {
position: google.maps.ControlPosition.LEFT_TOP
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_TOP
}
}
map = new google.maps.Map(mapDiv, mapOptions);
var homeControl = new HomeControl(homeControlDiv, map);
map.controls[google.maps.ControlPosition.LEFT_TOP].push(homeControlDiv);
example
A second option, would be to create a custom zoom control, then you can control the order (I couldn't figure out how to access the pre-defined Google Maps controls, only to put the custom control(s) before or after them).
example custom zoom/pan control from this question on SO
var PanControl = new geocodezip.web.PanControl(map);
PanControl.index = -2;
var homeControl = new HomeControl(homeControlDiv, map);
homeControlDiv.index = -1;
map.controls[google.maps.ControlPosition.LEFT_TOP].push(PanControl);
map.controls[google.maps.ControlPosition.LEFT_TOP].push(homeControlDiv);
Example with a modified ZoomPanControl (just the pan control)
code snippet with code from above example:
var map = null;
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
/**
* The HomeControl adds a control to the map that simply
* returns the user to Chicago. This constructor takes
* the control DIV as an argument.
* #constructor
*/
function HomeControl(controlDiv, map) {
// Set CSS styles for the DIV containing the control
// Setting padding to 5 px will offset the control
// from the edge of the map
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('div');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to set the map to Home';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('div');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '12px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = '<b>Home</b>';
controlUI.appendChild(controlText);
// Setup the click event listeners: simply set the map to
// Chicago
google.maps.event.addDomListener(controlUI, 'click', function() {
map.setCenter(chicago)
});
}
function initialize() {
// Create the DIV to hold the control and
// call the HomeControl() constructor passing
// in this DIV.
var homeControlDiv = document.createElement('div');
var mapDiv = document.getElementById('map-canvas');
var mapOptions = {
zoom: 12,
center: chicago,
disableDefaultUI: true,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.RIGHT_TOP
},
scaleControl: true,
panControl: false,
streetViewControl: true,
streetViewControlOptions: {
position: google.maps.ControlPosition.LEFT_TOP
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_TOP
}
}
map = new google.maps.Map(mapDiv, mapOptions);
var PanControl = new geocodezip.web.PanControl(map);
PanControl.index = -2;
var homeControl = new HomeControl(homeControlDiv, map);
homeControlDiv.index = -1;
map.controls[google.maps.ControlPosition.LEFT_TOP].push(PanControl);
map.controls[google.maps.ControlPosition.LEFT_TOP].push(homeControlDiv);
}
google.maps.event.addDomListener(window, 'load', initialize);
/**
* #param {string} tagName
* #param {Object.<string, string>} properties
* #returns {Node}
*/
function CreateElement(tagName, properties) {
var elem = document.createElement(tagName);
for (var prop in properties) {
if (prop == "style")
elem.style.cssText = properties[prop];
else if (prop == "class")
elem.className = properties[prop];
else
elem.setAttribute(prop, properties[prop]);
}
return elem;
}
/**
* #constructor
* #param {google.maps.Map} map
*/
function PanControl(map) {
this.map = map;
this.originalCenter = map.getCenter();
var t = this;
var panContainer = CreateElement("div", {
'style': "position: relative; padding: 5px;"
});
//Pan Controls
var PanContainer = CreateElement("div", {
'style': "position: relative; left: 2px; top: 5px; width: 56px; height: 56px; padding: 5px; overflow: hidden;"
});
panContainer.appendChild(PanContainer);
var div = CreateElement("div", {
'style': "width: 56px; height: 56px; overflow: hidden;"
});
div.appendChild(CreateElement("img", {
'alt': ' ',
'src': 'http://maps.gstatic.com/intl/en_ALL/mapfiles/mapcontrols3d5.png',
'style': "position: absolute; left: 0px; top: -1px; -moz-user-select: none; border: 0px none; padding: 0px; margin: 0px; width: 59px; height: 492px;"
}));
PanContainer.appendChild(div);
div = CreateElement("div", {
'style': "position: absolute; left: 0px; top: 19px; width: 18.6667px; height: 18.6667px; cursor: pointer;",
'title': 'Pan left'
});
google.maps.event.addDomListener(div, "click", function() {
t.pan(PanDirection.LEFT);
});
PanContainer.appendChild(div);
div = CreateElement("div", {
'style': "position: absolute; left: 37px; top: 19px; width: 18.6667px; height: 18.6667px; cursor: pointer;",
'title': 'Pan right'
});
google.maps.event.addDomListener(div, "click", function() {
t.pan(PanDirection.RIGHT);
});
PanContainer.appendChild(div);
div = CreateElement("div", {
'style': "position: absolute; left: 19px; top: 0px; width: 18.6667px; height: 18.6667px; cursor: pointer;",
'title': 'Pan up'
});
google.maps.event.addDomListener(div, "click", function() {
t.pan(PanDirection.UP);
});
PanContainer.appendChild(div);
div = CreateElement("div", {
'style': "position: absolute; left: 19px; top: 37px; width: 18.6667px; height: 18.6667px; cursor: pointer;",
'title': 'Pan down'
});
google.maps.event.addDomListener(div, "click", function() {
t.pan(PanDirection.DOWN);
});
PanContainer.appendChild(div);
div = CreateElement("div", {
'style': "position: absolute; left: 19px; top: 19px; width: 18.6667px; height: 18.6667px; cursor: pointer;",
'title': 'Reset center'
});
google.maps.event.addDomListener(div, "click", function() {
t.map.setCenter(t.originalCenter);
});
PanContainer.appendChild(div);
return panContainer;
}
/** #param {PanDirection} direction */
PanControl.prototype.pan = function(direction) {
var panDistance = 50;
if (direction == PanDirection.UP || direction == PanDirection.DOWN) {
panDistance = Math.round(this.map.getDiv().offsetHeight / 2);
this.map.panBy(0, direction == PanDirection.DOWN ? panDistance : -1 * panDistance);
} else {
panDistance = Math.round(this.map.getDiv().offsetWidth / 2);
this.map.panBy(direction == PanDirection.RIGHT ? panDistance : -1 * panDistance, 0);
}
}
/** #enum */
var PanDirection = {
LEFT: 0,
RIGHT: 1,
UP: 3,
DOWN: 4
}
window["geocodezip"] = window["geocodezip"] || {};
window["geocodezip"]["web"] = window["geocodezip"]["web"] || {};
window["geocodezip"]["web"]["PanControl"] = PanControl;
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map-canvas"></div>

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>

How add circle Shape in Google maps custom icon?

I have problem with custom images on map.
For example:
My icons generated this way, and icon contains image:
var ic = { //icon
url: icon, // url
scaledSize: new google.maps.Size(30, 30), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0), // anchor
//define the shape
//define the shape
shape:{coords:[17,17,18],type:'circle'},
//set optimized to false otherwise the marker will be rendered via canvas
//and is not accessible via CSS
optimized:false,
title: 'spot'
};
var marker = new google.maps.Marker({
map: map, title: name , position: latlngset, icon: ic
});
I want make my icons like css 50% radius (circle shape).
How I can do it?
Related question: JS Maps v3: custom marker with user profile picture
Using code from there, and changing the border-radius to 50%, gives me a circular icon with the image in the circle.
proof of concept fiddle
//adapted from http://gmaps-samples-v3.googlecode.com/svn/trunk/overlayview/custommarker.html
function CustomMarker(latlng, map, imageSrc) {
this.latlng_ = latlng;
this.imageSrc = imageSrc;
// Once the LatLng and text are set, add the overlay to the map. This will
// trigger a call to panes_changed which should in turn call draw.
this.setMap(map);
}
CustomMarker.prototype = new google.maps.OverlayView();
CustomMarker.prototype.draw = function() {
// Check if the div has been created.
var div = this.div_;
if (!div) {
// Create a overlay text DIV
div = this.div_ = document.createElement('div');
// Create the DIV representing our CustomMarker
div.className = "customMarker"
var img = document.createElement("img");
img.src = this.imageSrc;
div.appendChild(img);
var me = this;
google.maps.event.addDomListener(div, "click", function(event) {
google.maps.event.trigger(me, "click");
});
// Then add the overlay to the DOM
var panes = this.getPanes();
panes.overlayImage.appendChild(div);
}
// Position the overlay
var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
if (point) {
div.style.left = point.x + 'px';
div.style.top = point.y + 'px';
}
};
CustomMarker.prototype.remove = function() {
// Check if the overlay was on the map and needs to be removed.
if (this.div_) {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
}
};
CustomMarker.prototype.getPosition = function() {
return this.latlng_;
};
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 17,
center: new google.maps.LatLng(37.77088429547992, -122.4135623872337),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var data = [{
profileImage: "http://www.gravatar.com/avatar/d735414fa8687e8874783702f6c96fa6?s=90&d=identicon&r=PG",
pos: [37.77085, -122.41356],
}, {
profileImage: "http://placekitten.com/90/90",
pos: [37.77220, -122.41555],
}]
for (var i = 0; i < data.length; i++) {
new CustomMarker(new google.maps.LatLng(data[i].pos[0], data[i].pos[1]), map, data[i].profileImage)
}
.customMarker {
position: absolute;
cursor: pointer;
background: #424242;
width: 100px;
height: 100px;
/* -width/2 */
margin-left: -50px;
/* -height + arrow */
margin-top: -110px;
border-radius: 50%;
padding: 0px;
}
.customMarker:after {
content: "";
position: absolute;
bottom: -10px;
left: 40px;
border-width: 10px 10px 0;
border-style: solid;
border-color: #424242 transparent;
display: block;
width: 0;
}
.customMarker img {
width: 90px;
height: 90px;
margin: 5px;
border-radius: 50%;
}
<script src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map" style="width: 640pxpx; height: 480px;">map div</div>
After some google, I found this simple and easiest way for making a marker circle shape. Anyone can also customize it easily.
Here is a sample code -
<script>
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 15,
center: { lat: 23.8178689, lng: 90.4213642 },
});
const your_img_url = "https://avatars.githubusercontent.com/u/22879378?v=4";
var icon = {
url: your_img_url + '#custom_marker', // url + image selector for css
scaledSize: new google.maps.Size(32, 32), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0) // anchor
};
const marker = new google.maps.Marker({
position: { lat: 23.8178689, lng: 90.4213642 },
map,
icon: icon,
});
}
</script>
And your CSS style are -
<style>
img[src$="#custom_marker"]{
border: 2px solid #900 !important;
border-radius:50%;
}
</style>
Output:
If you want to make a circular marker just check the documentation This is faster and more lightweight.
Otherwise, just make your actual icon into a circular shape.

Google map api - autocomplete for hotels

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.

How I can left align the google maps

How to left align the google maps, I mean the marker positions. Here is my JS
function showGoogleMaps() {
var latLng = new google.maps.LatLng(position[0], position[1]);
var mapOptions = {
zoom: 16,
zoomControl:false,
mapTypeControl:false,
streetViewControl: false, // hide the yellow Street View pegman
scaleControl: true, // allow users to zoom the Google Map
mapTypeId:ROADMAP,
center: latLng,
scrollwheel: false,
styles: styles
};
map = new google.maps.Map(document.getElementById('googlemaps'),
mapOptions);
// Show the default red marker at the location
marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: false,
title: 'Hello',
animation: google.maps.Animation.DROP
});
}
Here are the screenshots
The default marker location
How I want this to be
The marker or location is centered by default. I want that either to the left or right by default.
Thanks
A simple approach:
Initially set the width of the map to e.g 30%.
The center of the map now will be in the middle of these 30%.
Once the map is loaded set the width of the map to 100%.
function initialize() {
var goo = google.maps,
map = new goo.Map(document.getElementById('googleMap'), {}),
markers = [{
pos: new goo.LatLng(26.1445169, 91.7362)
}, {
pos: new goo.LatLng(26.2571285, 92.05991)
}, {
pos: new goo.LatLng(26.3143518, 91.0497609)
}, ],
bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; ++i) {
new google.maps.Marker({
map: map,
position: markers[i].pos
});
bounds.extend(markers[i].pos);
}
map.fitBounds(bounds);
goo.event.addListenerOnce(map, 'idle', function() {
this.getDiv().style.width = '100%';
goo.event.trigger(this, 'resize');
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_wrapper,
#googleMap {
height: 100%;
margin: 0;
padding: 0;
width: 100%;
}
#googleMap {
width: 30%;
}
<div id="map_wrapper">
<div id="googleMap"></div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
To align the markers on the right additionally use the panBy-method:
function initialize() {
var goo = google.maps,
map = new goo.Map(document.getElementById('googleMap'), {}),
markers = [{
pos: new goo.LatLng(26.1445169, 91.7362)
}, {
pos: new goo.LatLng(26.2571285, 92.05991)
}, {
pos: new goo.LatLng(26.3143518, 91.0497609)
}, ],
bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; ++i) {
new google.maps.Marker({
map: map,
position: markers[i].pos
});
bounds.extend(markers[i].pos);
}
map.fitBounds(bounds);
goo.event.addListenerOnce(map, 'idle', function() {
this.getDiv().style.width = '100%';
this.panBy(-(this.getDiv().offsetWidth/1.5),0);
goo.event.trigger(this, 'resize');
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_wrapper,
#googleMap {
height: 100%;
margin: 0;
padding: 0;
width: 100%;
}
#googleMap {
width: 30%;
}
<div id="map_wrapper">
<div id="googleMap"></div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>

Where to add the Weather Layer on this custom map?

I need some help in figuring out where to put any of the weather layer code to a custom Google Map (API v3), any input would be greatly appreciated :)
We have created a custom Google Map, and on it we have 2 Fusion Table layers with a simple toggle. From the developer documentation, and what I have found here on this site, I can see I need to add this bit of code:
var weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.FAHRENHEIT
});
weatherLayer.setMap(map);
but I am totally clueless as to where to place this, as each time I have tried adding it (2 days now) the code breaks and I am shown a blank white page with all kinds of errors in the F12 Console window.
Where do we need to add that, and how can we add it to the toggle? Here is what we have working:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=weather"></script>
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
var map;
var layer1;
var tableid = '';
var layer2;
var tableid2 = 'xxxxx';
var layer3;
var tableid3 = 'xxxxx';
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(31.499, -111.202),
zoom: 10,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_CENTER
},
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.LEFT_CENTER
},
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.BOTTOM_LEFT
},
streetViewControl: false,
streetViewControlOptions: {
position: google.maps.ControlPosition.LEFT_TOP
}
});
var styledMapType = new google.maps.StyledMapType({
map: map,
name: 'Styled Map'
});
map.mapTypes.set('map-style', styledMapType);
map.setMapTypeId('map-style');
layer1 = new google.maps.FusionTablesLayer({
query: {
select: '',
from: tableid
},
map: map
});
layer2 = new google.maps.FusionTablesLayer({
query: {
select: 'LOC',
from: tableid2
},
map: map
});
layer3 = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: tableid3
},
suppressInfoWindows:true,
map: map
});
}
function changeMap(layerNum) {
if (layerNum == 2) {
update(layer2);
}
if (layerNum == 3) {
update(layer3);
}
}
function update(layer) {
var layerMap = layer.getMap();
if (layerMap) {
layer.setMap(null);
} else {
layer.setMap(map);
}
}
</script>
<style type="text/css">
#toggle_box {
position: absolute;
top: 7px;
right: 7px;
padding: 3px;
border: 1px solid #707735;
background: #DED9C6;
font-family: 'Coda', cursive;
}
body {
margin: 0px;
padding: 0px;
font-family: 'Coda', cursive;
}
#map_canvas {
position: absolute;
right: 0;
top: 0;
width: 100%;
height: 100%;
font-family: 'Coda', cursive;
}
</style>
</head>
<body onload="initialize();">
<div id="map_canvas"></div>
<div id="toggle_box"><input type="checkbox" value="2" onclick="changeMap(this.value)" checked="checked" />REFERENCE POINTS
<input type="checkbox" value="3" onclick="changeMap(this.value)" checked="checked" />AZ COUNTIES</div>
</body>
</html>
Place it somewhere where the map is initialized, e.g. before that line:
var styledMapType = new google.maps.StyledMapType({