Thursday, May 24, 2018

Google Maps API


Summary

In this post I'll show a very simple use-case of the Maps API.  I'll display a map with markers on a simple web page.

Code

Below is a simple javascript array of markers to be added to the map.  This array is stored in a file named markers.js.

  1. 'use strict';
  2. 'use esversion 6';
  3. const sites = [
  4. { lat: 39.016683491757995, lng: -106.31219892539934, label: 'Site 1' },
  5. { lat: 39.01841939481699, lng: -106.31966973052391, label: 'Site 2' },
  6. { lat: 38.816564618651974, lng: -106.243267861874, label: 'Site 3' },
  7. { lat: 38.970910463727286, lng: -106.40428097049143, label: 'Site 4' }
  8. ];

Simple HTML + javascript code to display the map and markers below.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <style>
  6. #map {
  7. height: 800px;
  8. width: 100%;
  9. }
  10. </style>
  11. <title>Fabulous Sites</title>
  12. <script type="text/javascript" src="markers.js"></script>
  13. </head>
  14. <body>
  15. <div id="map"></div>
  16. <script>
  17. function markMap() {
  18. const center = {lat: 38.8, lng: -106.24};
  19. const map = new google.maps.Map(document.getElementById('map'), {
  20. zoom: 10,
  21. center: center
  22. });
  23. for (let i=0; i < sites.length; i++)
  24. var marker = new google.maps.Marker({
  25. position: {lat: sites[i].lat, lng: sites[i].lng},
  26. label: sites[i].label,
  27. map: map
  28. });
  29. }
  30. </script>
  31. <script async defer
  32. src="https://maps.googleapis.com/maps/api/js?key=yourkey&callback=markMap">
  33. </script>
  34. </body>
  35. </html>

Results


Copyright ©1993-2024 Joey E Whelan, All rights reserved.