Client Side, Server Side, API

Notes

Getting Started with Google Maps

  1. Get API Key
  2. Getting started with Google Maps Platform
  3. Google Maps Javascript API Getting Started : has tutorials, and API reference, and Code Samples
Notes

Google Map 01

01_googlemap.html: displaying map in div element
  <html lang="en">
  <head>
    <title>Simple Map</title>

  <script>
      // linking google maps API: copy and paste and add your own key
      // put your own key in the key section
      // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).  
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
      key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      v: "weekly",
      });
      </script>


    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }

      /* Optional: Makes the sample page fill the window. */
      html,
      body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
      </head>
  <body>
    
    <div id="map"></div>
     
    <script>
    
      let map;
     
      // Define an asynchronous function to initialize the Google Map.
      // The "async" keyword indicates that this function will perform asynchronous operations, 
      // allowing us to use await inside it to wait for the loading of the Google Maps library.
          async function initMap() {
      
        // Request libraries when needed, not in the script tag.
            const { Map } = await google.maps.importLibrary("maps");
	  
        // make a map inside the div with id "map"
        // with center, and zoom setting, mapTypeID
           map = new Map(document.getElementById("map"), {
           center: { lat: -34.397, lng: 150.644 },
           zoom: 8,
           mapId: "DEMO_MAP_ID",   // so you can control how a map looks via the cloud interface and save the setting as mapID

        });
      }

      
      initMap();
      
    </script>
  </body>
  </html>
 
Notes

02 Changing/Setting Values

[02_googlemap.html]

Changing values and getting Values using javascript

<!DOCTYPE html>
<html lang="en">
<head>
<title>Simple Map</title>
	
 <script>
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
	  key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx",
	  v: "weekly",
      });
      
</script>
	
<style>
body {
  font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
  font-size: small;
  background: #fff;
}

#map {
  width: 100%;
  height: 500px;
  border: 1px solid #000;
}
</style>

</head>

<body>
<h1> Hello, My First Google Map </h1>

<input type="button" value="getValues" id="getValues" />
<input type="button" value="changeValues" id="changeValues" />

<div id="map"></div>





<script>
  let map;
  
  async function initMap() {

      // Request needed libraries.
      const { Map } = await google.maps.importLibrary("maps");

      // you can isolate the options into an object literal like this
      var options = {
	  	center: {lat: 37.09, lng: -95.71},
	  	zoom: 3,
		mapId: "DEMO_MAP_ID",   // so you can control how a map looks via the cloud interface and save the setting as mapID
      }

	  
      // create new map into div with id "map" with optios
      map = new Map(document.getElementById("map"), options);


      //event handler for button 1
      document.getElementById('getValues').onclick = function(){
	  	alert("Current Zoom level is " + map.getZoom());
	  	alert("Current Center is " + map.getCenter());    // BTW, this is a convenient way to get lat & lang
	  	alert("The current mapType is " + map.getMapTypeId());
      }

      //event handler for button 2
      document.getElementById("changeValues").onclick = function(){
	  var options = {
	      center: {lat: 45.4809680038112, lng: -122.63033866882324},
	      zoom: 18,
	  }
	  map.setOptions(options);
	  }
  }

  initMap();
  
</script>

</body>
</html>


Notes

03 Markers

03_marker_googlemapv1_marker.html

Here we are creating a map and creating a marker

<!--
setting marker in a map
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Simple Map</title>
  
    <script>
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
	  key: "XXXXXXXXXXXXXXXXXXXXXXXX",
	  v: "weekly",
      });
      
    </script>
  
  <style>
    body {
      font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
      font-size: small;
      background: #fff;
    }

    #mapdiv {
      width: 100%;
      height: 500px;
      border: 1px solid #000;
    }
</style>
</head>

<body>
<h1> My First Google Map </h1>


<div id="mapdiv"></div>



    
<script>

  var map;
  
  async function initMap() {
    // Request needed libraries.
    const { Map } = await google.maps.importLibrary("maps");
    const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");


      var options = {
        zoom: 16,
	    center: {lat: 45.481, lng: -122.6303},
            mapId: "DEMO_MAP_ID",   // so you can control how a map looks via the cloud interface
      };

    
      map = new Map(document.getElementById('mapdiv'), options);

    
     // Add a marker to the map 
      const marker = new AdvancedMarkerElement({
        position: { lat: 45.481, lng: -122.6303 },
        map: map, // Attach the marker to the map
      });
  }

  initMap();
</script>

</body>
</html>

03_marker_googlemapv2_marker_htmlcss.html

Here we are creating a marker created through html and css

<!--
add a marker. marker is described using html and css 
-->

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Simple Map</title>
    
    <script>
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
	  key: "AIzaSyCMesXxnNB-W70Kbw0y0-LS98UN798W1_w",
	  v: "weekly",
      });
      
    </script>

    <style>
        body {
          font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
          font-size: small;
          background: #fff;
        }

        #mapdiv {
          width: 100%;
          height: 500px;
          border: 1px solid #000;
        }


          /* HTML marker styles */
        .reedcss {
          background-color: #A70E16;
          border-radius: 8px;
          color: #FFFFFF;
          font-size: 14px;
          padding: 10px 15px;
          position: relative;
        }

          /* adds a small triangle below the .reedcss element */
         .reedcss::after {
          content: "";
          position: absolute;
          left: 50%;   /* from left 50% so middle */
          top: 100%;   /* from top 100% so bottom */
          transform: translate(-50%, 0);
          width: 0;
          height: 0;
          border-left: 8px solid transparent;   /* left triangle */
          border-right: 8px solid transparent;  /*  right triangle */
          border-top: 8px solid #A70E16;  /* top of triangle */
        }
    </style>
</head>

<body>
<h1> My First Google Map </h1>


<div id="mapdiv"></div>

<script>

  var map;
  
  async function initMap() {
    // Request needed libraries.
    const { Map } = await google.maps.importLibrary("maps");
    const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");


      var options = {
        zoom: 16,
	    center: {lat: 45.481, lng: -122.6303},
        mapId: "DEMO_MAP_ID",   // so you can control how a map looks via the cloud interface
      };

    
      map = new Map(document.getElementById('mapdiv'), options);

     // create a new DIV element and store in reedDiv
      const reedDiv = document.createElement("div");
      // set content
      reedDiv.innerHTML = "welcome to Reed";
      // apply CSS class "reedcss" to div object
      reedDiv.className = "reedcss"; // css style name

          
     // Add a marker using the traditional Marker class
      const marker = new AdvancedMarkerElement({
        position: { lat: 45.481, lng: -122.6303 },
        map: map, // Attach the marker to the map
        content: reedDiv,
      });

  }

  initMap();
</script>

</body>
</html>

03_marker_googlemapv3_marker_img.html

Creating a marker with an image file

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Simple Map</title>
  <script>
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
	  key: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
	  v: "weekly",
      });
      
  </script>
  <style>
      body {
        font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
        font-size: small;
        background: #fff;
      }

      #mapdiv {
        width: 100%;
        height: 500px;
        border: 1px solid #000;
      }
  </style>
</head>

<body>
<h1> My First Google Map </h1>


<div id="mapdiv"></div>


<script>

  var map;
  
  async function initMap() {
    // Request needed libraries.
    const { Map } = await google.maps.importLibrary("maps");
    const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");


      var options = {
        zoom: 16,
	    center: {lat: 45.481, lng: -122.6303},
        mapId: "DEMO_MAP_ID",   // so you can control how a map looks via the cloud interface
      };

      map = new Map(document.getElementById('mapdiv'), options);

    
    // create <img> element 
    const beachFlagImg = document.createElement("img");
    // set the src attribute to a png image file
    beachFlagImg.src =
    "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png";


          
    // A marker with a with a URL pointing to a PNG.
      const marker = new AdvancedMarkerElement({
        position: { lat: 45.481, lng: -122.6303 },
        map: map, // Attach the marker to the map
        content: beachFlagImg,
        title: "A marker using a custom PNG Image",
      });

  }

  initMap();
</script>

</body>
</html>
    



03_marker_googlemapv4_clickable.html

Creating two clickable markers


<html lang="en">
<head>
  <title>Simple Map</title>
  
  <script>
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
	  key: "AIzaSyCMesXxnNB-W70Kbw0y0-LS98UN798W1_w",
	  v: "weekly",
      });
      
  </script>
  
  <style>
      body {
        font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
        font-size: small;
        background: #fff;
      }

      #mapdiv {
        width: 100%;
        height: 500px;
        border: 1px solid #000;
      }
    
    
        /* HTML marker styles */
        .artcss {
          background-color: #A70E16;
          border-radius: 8px;
          color: #FFFFFF;
          font-size: 14px;
          padding: 10px 15px;
          position: relative;
        }
  </style>
</head>

<body>
<h1> My First Google Map </h1>


<div id="mapdiv"></div>

<script>
  async function initMap() {
    // Request needed libraries.
    const { Map, InfoWindow } = await google.maps.importLibrary("maps");
    const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary(
      "marker",
    );
    
    const map = new Map(document.getElementById("mapdiv"), {
      zoom: 15,
      center: {lat: 45.4809680038112, lng: -122.63033866882324},
      mapId: "DEMO_MAP_ID",   // so you can control how a map looks via the cloud interface and save the setting as mapID
    });

     // Create the marker pin element.
    const pin = new PinElement({
      glyph: "E", // Label for the pin
      scale: 1.5,
    });
    
    
     // Create the marker.
    const marker = new AdvancedMarkerElement({
      position:{lat: 45.4809680038112, lng: -122.63033866882324},
      map,
      title: "Eliot",
      content: pin.element,
      gmpClickable: true, // Ensures the marker is clickable
    });

      // Create an info window to share between markers.
    const infoWindow = new InfoWindow();
    
    
     // Add a click listener for the marker.
    marker.addListener("click", function (event) {
      infoWindow.close();
      infoWindow.setContent(marker.title); // Set the content to the marker's title
      infoWindow.open(map, marker); // Open the info window anchored to the marker
  });
    
    /*** marker two ***/
    
         // Create the marker pin element.
    const pin2 = new PinElement({
      glyph: "S", // Label for the pin
      scale: 2,
    });
    

         // Create the marker.
    const marker2 = new AdvancedMarkerElement({
      position:{lat: 45.480546023521846, lng: -122.62529827164177},
      map,
      title: "Studio Art",
      content: pin2.element,
      gmpClickable: true, // Ensures the marker is clickable
    });

    
    
      // Create an info window to share between markers.
    const infoWindow2 = new InfoWindow();
    
    
      // create a new DIV element and store in reedDiv
      const artDiv = document.createElement("div");
    
      //  idea was to to the below but not elegant so creating elements dynamically below
      //  artDiv.innerHTML = "<h1>Art Dept here!<h1><img style='width:50%' src='https://www.reed.edu/assets-main/images/feature-panels/reed-home-reedies-students-laughing.jpg'>";

      // Create elements dynamically
      const heading = document.createElement("h1");
      heading.textContent = "Art Dept here!";
      const image = document.createElement("img");
      image.style.width = "50%";
      image.src = "https://www.reed.edu/assets-main/images/feature-panels/reed-home-reedies-students-laughing.jpg";
      artDiv.appendChild(heading);
      artDiv.appendChild(document.createElement("br")); // Optional line break
      artDiv.appendChild(image);
      artDiv.className = "artcss";     // apply CSS class "artcss" to div object

    
     // Add a click listener for the marker.
    marker2.addListener("click", function (event) {
      infoWindow2.close();
      infoWindow2.setContent(artDiv); // Set the content to the marker's title
      infoWindow2.open(map, marker2); // Open  info window2 anchored to  marker2
  });
 
  }

initMap();
  
  
  </script>


</body>
</html>

Notes

06 (geolocation)

You need to have location services turned on, on your computer (at least Macs) or smartphone.



HTML5's geolocation feature. You may need to use https (secure encrypted http protocol) on Chrome.
<script>
var myDiv;

window.onload = function(){

  myDiv = document.getElementById('myDiv');

  if (navigator.geolocation){
          navigator.geolocation.getCurrentPosition(showPosition);
  }
  else {
    myDiv.innerHTML = "Geolocation is not supported by this browser.";
  }
}



function showPosition(position){
  myDiv.innerHTML = "Latitude: " + position.coords.latitude + "Longitude: " + position.coords.longitude;
}
</script>
08_simple_geolocation_html5.html: Getting location and print into a DIV

08_geolocation_html5.html: Getting location and sending the coordinate to Google Maps

Notes