Skip to content

Google Maps

sachin soman edited this page Jun 25, 2020 · 1 revision

Getting the API Key

  1. Visit developer dashboard
  2. Sign in with your Google.
  3. Click on "Select a Project" and then "Create a Project" in the upper right side of the screen.
  4. Click the "Create" button.
  5. Click on the "Google Maps JavaScript API" under "Google Maps APIs"
  6. Click the “Credentials” menu item on the left of the screen
  7. Click the “Create Credentials” button
  8. Select the “Browser Key” button 9 Name your API Key.
  9. Click the “Create” button

Hello,World!

var options = {
    zoom:13,
    center:{lat:53.3498,lng:-6.2603}
}

function initMap(){
    //Map options
    var map = new google.maps.Map(document.getElementById('map'),options)

}


<script async defer
src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initMap" >

</script>

Looking at callback we see we call initMap function once the scrip loads. The loading occurs in async which means the dom loading is no affeccted by js script loading.

External Example

<!DOCTYPE html>
<html>
  <head>
    <style>
      html,
      body {
        font-family: Arial, sans-serif;
        height: 100%;
        margin: 0;
        padding: 0;
      }

      #map {
        height: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      var map;
      function initMap() {
        // Constructor creates a new map - only center and zoom are required.
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 40.7413549, lng: -73.9980244},
          zoom: 13
        });
      }
    </script>

    <script async defer
        src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&v=3&callback=initMap">
    </script>

  </body>
</html>

Marker Example

For marker to appear we use the Marker class and here is an example

        var dublin= {lat: 53.3498, lng: -6.2603};
        var marker = new google.maps.Marker({
          position: dublin,
          map: map,
          title: 'First Marker!'
        });

We pass an object to Marker class it has position, map specify which map instance it want to show the marker on and title which shows title when we hover over the marker. Notice that we used the same map object for new Marker when I tried creating a new map instance it created a reload which is not what we need.