Peter Peter - 5 months ago 23
Javascript Question

Creating a button that shows my current location using geolocation

I want to create a button which shows my current location using geolocation. Here is my code which I took from the developers page.

<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<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
}

</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>

<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see a blank space instead of the map, this
// is probably because you have denied permission for location sharing.

var map;

function initialize() {
var mapOptions = {
zoom: 16
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);

// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);

var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});

map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}

var centerControlDiv = document.createElement('div');
var centerControl = new CenterControl(centerControlDiv, map, chicago);

centerControlDiv.index = 1;
map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(centerControlDiv);

}

function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}

var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};

var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);


}






google.maps.event.addDomListener(window, 'load', initialize);




</script>
</head>
<body>
<div id="map-canvas"></div>



</body>
</html>


I found a post here on these forums saying to use this code:

var myloc = new google.maps.Marker({
clickable: false,
icon: new google.maps.MarkerImage('//maps.gstatic.com/mapfiles/mobile/mobileimgs2.png',
new google.maps.Size(22,22),
new google.maps.Point(0,18),
new google.maps.Point(11,11)),
shadow: null,
zIndex: 999,
map: // your google.maps.Map object
});

if (navigator.geolocation) navigator.geolocation.getCurrentPosition(function(pos) {
var me = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
myloc.setPosition(me);
}, function(error) {
// ...
});


But it doesn't seem to work for me. I don't know why. Can anyone try to explain me and tell me where to put the code for get it work?

I would rather use a "custom control" to show my current position, if someone can help me make one like that, this way I can put it wherever I want to.

Answer

Here is a simple example on how to create a custom control and bind a click event listener to it to geolocate the user.

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 google.maps.Marker({
                position: pos,
                draggable: true,
                animation: google.maps.Animation.DROP,
                map: map
            });

            map.setCenter(pos);
        });
    }
}

initialize();

JSFiddle demo