How add circle Shape in Google maps custom icon? - google-maps

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.

Related

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 :)

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>

Google Map marker text

I have found this icon: http://chart.apis.google.com/chart?cht=mm&chs=60x102&chco=ffffff,70a3c1,70a3c1&ext=.png
I'm wondering if it's possible to place text on this icon. Basically what I'm looking for is an icon with a dynamic color and text. A simple PHP script that dynamically generates an icon based on a images and text would also be great.
You can create image from png (using PHP GD )
$yourimage = imagecreatefrompng($originalImage);
Add in your html page this tag
<img src="test_icon.php?text=yourtext">
and the add the text you need
this way using test_icon.php
test_icon.php
<?php
header("Content-type: image/png");
$yourOrigImage = "group_icon.png";
if(file_exists($yourOrigImage)) {
$newImage = imagecreatefrompng($yourOrigImage);
imagesavealpha($newImage, true); // this for keep the png's transparency important
if(!$newImage) {
die("im is null");
}
$black = imagecolorallocate($newImage, 0, 0, 0);
$width = 36; // the width of the image
$height = 36; // the height of the image
$font = 4; // font size
$text = $_GET['text']; // text
$leftTextPos = 4;
$outputImage = "group_icon_".$text.".png";
imagestring($newImage, $font, $leftTextPos, 9, $text, $black);
imagepng($newImage, $outputImage, 0);
imagedestroy($newImage);
}
?>
Two options:
The third party MarkerWithLabel library.
fiddle
code snippet:
var map;
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new MarkerWithLabel({
position: map.getCenter(),
map: map,
icon: "http://chart.apis.google.com/chart?cht=mm&chs=60x102&chco=ffffff,70a3c1,70a3c1&ext=.png",
labelContent: "A",
labelAnchor: new google.maps.Point(15, 90),
labelClass: "labels", // the CSS class for the label
labelInBackground: false
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
.labels {
color: black;
font-family: "Lucida Grande", "Arial", sans-serif;
font-size: 30px;
text-align: center;
width: 30px;
white-space: nowrap;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerwithlabel/src/markerwithlabel.js"></script>
<div id="map_canvas"></div>
Add a label to the native google.maps.Marker
fiddle
code snippet::
var map;
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
icon: "http://chart.apis.google.com/chart?cht=mm&chs=60x102&chco=ffffff,70a3c1,70a3c1&ext=.png",
label: "A"
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>

Google maps custom control always appears below the default controls

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>