Search code examples
google-mapsgeolocation

Google Map not showing users location


I have a google map which i am trying to get to show the users location, if i add the latitude and Longitude its fine, but when i try and get the location dynamically it doesn't show the map.

This works

       function initMap() {

    var map = new google.maps.Map(document.getElementById('map'), {
      center: new google.maps.LatLng(-33.863276, 151.207977),
      zoom: 12
    });

But this doesn't

     function initMap() {

    var map = new google.maps.Map(document.getElementById('map'), {
      center: new google.maps.(position.coords.latitude, position.coords.longitude),
      zoom: 13
    });

Solution

  • You need an access to navigator.geolocation

    function initMap() {
    
        var map = new google.maps.Map(document.getElementById('map'), { zoom: 12 });
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };
            map.setCenter(pos);
         });
      }
    }