Author: Stasyuk Eugene 200 Tags: , 26.02.2024

Today let’s see how to make a google map with a list of addresses. The important feature is that when you click on any of the addresses, a marker with this address should appear in the center of the map.

The fully finished and working version can be seen here: https://codepen.io/jecosjmecos/pen/rNRgrgg

And in the article itself we will already analyze the work step by step.

1) Styles

Set the size of the map on the page:

<style>
  #map {
    height: 400px;
    width: 100%;
  }
</style>

2) Marking up a list with addresses

The list wrap should have id='address'

<ul id="address">
  <li>
    <a href="#"
       data-lat="51.52997244138653"
       data-lng="-0.1721165694782623">
      <span class="address">
        St John's Wood Rd, London NW8 8QN, Great Britain
      </span>
      <span class="link">Directions</span>
    </a>
 </li>

  <li>
    <a href="#"
       data-lat="13.731994255241341"
       data-lng="100.54166799585914">
      <span class="address">
        Lumphini, Pathum Wan, Bangkok 10330, Thailand
      </span>
      <span class="link">Directions</span>
    </a>
  </li>

  <li>
    <a href="#"
       data-lat="35.72016405570121"
       data-lng="139.76076052276977">
      <span class="address">
        1 Chome-28-9 Nezu, Bunkyo City, Tokyo 113-0031, Japan
      </span>
      <span class="link">Directions</span>
    </a>
  </li>
</ul>

An important point! Link (tag <a>) has two attributes: data-lat и data-lng . In these attributes we use coordinates, which will then be displayed on the map.

To get them, just right-click on a point on an open google map, and then a window with options will be available, the first item of which is the coordinates.

3) Area with map

Add an element with id='map‘. The contents of the block will be filled with the map

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

4) Main script

This script:

  • Reads the coordinates of the addresses in our list
  • Adds markers of these addresses to the map
  • When you click on one of the addresses, displays it in the center of the map

To make the script work, you need to create an api key in the google console and insert it in the reference instead of YOUR_API_KEY in script.src in the initMap() function. You can see how to create a key here:

<script>
  document.addEventListener('DOMContentLoaded', async function(){

      const mapList = document.querySelectorAll('#address li a');

      if(mapList.length){
          await initMap(mapList);

          mapList.forEach((item) => {

              item.addEventListener('click', function(e){
                  e.preventDefault();

                  addMarker(+this.dataset.lat, +this.dataset.lng);
              });

          });
      }
  });

  async function initMap(coordinates) {
      return new Promise((resolve, reject) => {
          const script = document.createElement('script');
          script.src = `https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMapCallback`;
          script.defer = true;
          script.async = true;
          window.initMapCallback = function() {
              const map = new google.maps.Map(document.getElementById("map"), {
                  center: { lat: -10.397, lng: 155.644 },
                  zoom: 16,
                  mapTypeControl: false,
                  streetViewControl: false,
              });

              window.map = map;

              coordinates.forEach((coordinate) => {
                  addMarker(+coordinate.dataset.lat, +coordinate.dataset.lng, map);
              });

              resolve();
          };

          document.head.appendChild(script);
      });
  }

  function addMarker(lat, lng, map = false) {
      map = map ? map : window.map;

      const marker = new google.maps.Marker({
          position: { lat: lat, lng: lng },
          map: map,
      });

      map.setCenter({ lat: lat, lng: lng });
  }
</script>

Other articles

FAQ question

FAQ

FAQ

How to remove the prefix “Category, Label …” from archive pages? Place the filter in the functions.php file in our theme folder How to remove the scale of images when uploading to media? Place the filter in the functions.php file in our theme folder How to style scrollbar (css)? Why doesn’t search work on a […]

ACF fields in the Gutenberg text editor

ACF fields in the Gutenberg text editor

ACF fields in the Gutenberg text editor

Gutenberg – has been used in WordPress as the main text editor for quite some time now. I, probably like most developers, wasn’t too keen on using it. Especially since you could download the Classic Editor plugin as an alternative and continue to use the old editor. But, as I used Gutenberg, I saw a […]