Get User Current Location On Google Maps JavaScript

Google Maps API Javascript

1. Create an API key from Google Cloud Platform that you will need to access Google Maps API.

2. Replace your API key inside Google Maps JavaScript script tag at the bottom of the HTML code below.

Hey, Like what you're reading?

🔥 1,750+ students already enrolled!
4.5 ⭐️⭐️⭐️⭐️⭐️ (86+ ratings) BEST SELLER

3. Define div element with an ID of map.

         #map {
         height: 100%;
         body {
         height: 100%;
         margin: 0;
         padding: 0;
      <div id="map"></div>
   <script async defer
   <script src="app.js"></script>

4. Get the user’s location in the form of Latitude and Longitude using getCurrentPoistion() method, which is a part of the HTML5 Geolocation JavaScript API.

   function (position) {
      initMap(position.coords.latitude, position.coords.longitude)
   function errorCallback(error) {

5. Inside the success callback function, invoke initMap() with Latitude and Longitude values as arguments.

function initMap(lat, lng) {

   var myLatLng = {

   var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 15,
      center: myLatLng

   var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,