Google Map API set marker to current user location

Google Map API set marker to current user location

How to get current user location using Google map API and set the google map marker to the current user location with Info window.  Yes, it is possible to get the current user location using Google map API.

Let’s how we can get the current user location using Google map API.

<style> #map { height: 500px; width : 500px; } </style>

Let’s create the javascript code for getting the current user location and set the marker to user location with the address.

      // Note: This example requires that you consent to location sharing when
      // prompted by your browser. If you see the error "The Geolocation service
      // failed.", it means you probably did not give permission for the browser to
      // locate you.
      var map, infoWindow, geocoder;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 6
        geocoder = new google.maps.Geocoder;
        infoWindow = new google.maps.InfoWindow;

        // Try HTML5 geolocation.
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var latlng = {
              lat: position.coords.latitude,
              lng: position.coords.longitude

            geocoder.geocode({'location': latlng}, function(results, status) {
              if (status === 'OK') {
                if (results[0]) {
                  var marker = new google.maps.Marker({
                    position: latlng,
                    map: map
        , marker);
                } else {
                  window.alert('No results found');
              } else {
                window.alert('Geocoder failed due to: ' + status);

          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, infoWindow, map.getCenter());

      function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setContent(browserHasGeolocation ?
                              'Error: The Geolocation service failed.' :
                              'Error: Your browser doesn\'t support geolocation.');;

Just set your Google map API key for the access to the Google geolocation API.

I hope the Google map API code is helpful for you.