Maps API v3 Custom Control and geolocation
http://stackoverflow.com/questions/28998743
by Alex Azuero
HTML
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=drawing "></script>
<div id="map-canvas"></div>
CSS
body {
margin:0;
padding:0;
}
#map-canvas {
height: 400px;
}
JavaScript
var map;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(10, 10),
zoom: 5
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Create the DIV to hold the control and call the constructor passing in this DIV
var geolocationDiv = document.createElement('div');
var geolocationControl = new GeolocationControl(geolocationDiv, map);
map.controls[google.maps.ControlPosition.TOP_CENTER].push(geolocationDiv);
}
function GeolocationControl(controlDiv, map) {
// Set CSS for the control button
var controlUI = document.createElement('div');
controlUI.style.backgroundColor = '#444';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '1px';
controlUI.style.borderColor = 'white';
controlUI.style.height = '28px';
controlUI.style.marginTop = '5px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to center map on your location';
controlDiv.appendChild(controlUI);
// Set CSS for the control text
var controlText = document.createElement('div');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '10px';
controlText.style.color = 'white';
controlText.style.paddingLeft = '10px';
controlText.style.paddingRight = '10px';
controlText.style.marginTop = '8px';
controlText.innerHTML = 'Center map on your location';
controlUI.appendChild(controlText);
// Setup the click event listeners to geolocate user
google.maps.event.addDomListener(controlUI, 'click', geolocate);
}
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Create a marker and center map on user location
marker = new...