Creating a button that shows my current location using geolocation

15,746

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

Share:
15,746
Peter
Author by

Peter

Updated on June 22, 2022

Comments

  • Peter
    Peter almost 2 years

    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.

  • Peter
    Peter about 9 years
    thanks very much. maybe its a stupid question, but where in my code(the first one) do i put this code which you gave me?
  • MrUpsidown
    MrUpsidown about 9 years
    This is a complete working example. You don't need to insert it into your own code. Just use it. Keep your HTML and CSS and just use this instead of your javascript code. It is minimal though. You might want to keep the functions you have to handle errors, etc. Did you check the demo?
  • Peter
    Peter about 9 years
    yea i did, the problem is though that it doesnt show my corrent position when i enter the page(but my first code does). it finds my location and shows me where im, when i move away from it, i press the trigger and it moves me back to my own location. is it impossible to implement it in my first code?
  • MrUpsidown
    MrUpsidown about 9 years
    You didn't ask for that. You asked for a button to center the map on your current location. All you need to do is to call geolocate() at the end of the initialize() function if you want it to be centered at first.
  • Peter
    Peter about 9 years
    how hard is it to implement the code which you gave me to my code? I need to implement it to my code because i already have it the way i want to, so i only need to put the trigger in and thats it.
  • MrUpsidown
    MrUpsidown about 9 years
    jsfiddle.net/upsidown/19hjuh6s/3 updated with what you requested. Map will now center on user location at start and button will recenter map. Code is commented. You should be able to adapt it to your needs. Nobody's here to write code for you.
  • Peter
    Peter about 9 years
    Thank you vry much MrUpsidown. it works like a charm now. only suggestion is, it takes a little bit time before it finds my location. i dont know if its normal or not. but its not so important for now. :) Thanks again.
  • MrUpsidown
    MrUpsidown about 9 years
    This is normal. It is an asynchronous function and it will try to use different methods to locate the user. It can take some time.
  • MrUpsidown
    MrUpsidown about 9 years
    Don't forget to upvote/accept this answer when you can.
  • Peter
    Peter about 9 years
    i marked it as answer, but unfortunatly i cant upvote it because i dont have enough points. :/