Author: Stasyuk Eugene 91 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

Date range in WP_Query – output posts by meta_query wordpress

Date range in WP_Query – output posts by meta_query

Date range in WP_Query – output posts by meta_query

WP_Query class is one of the WordPress tools that helps to display posts according to the required parameters: categories, sorting, date range, etc. The list of parameters is pretty decent. You can read more about them in the documentation here: https://developer.wordpress.org/reference/classes/wp_query/ . Some parameters are quite extensive and sometimes it’s much easier to understand them […]

Position sticky doesn’t work position: sticky

Position sticky doesn’t work

Position sticky doesn’t work

Position sticky doesn’t work – to my surprise this is a fairly common request that I myself have encountered in my time. Sticky is a pretty simple and versatile solution for placing sticky blocks on a page. At the very least, it doesn’t require you to do a decent amount of javascript code, which did […]