Google Maps API in Vue

This explores the initialization of map, adding and clearing of markers in the map in a Vue page.

index.html

<script src='https://maps.googleapis.com/maps/api/js?key=AIzaSyAOVYRIgupAurZup5y1PRh8Ismb1A3lLao&callback=initMap'
        async defer></script>

In index.html, load the Google Maps JavaScript API

Map.vue

<template>

<template>
  <html>
    <body>
      <div id="map"></div>
      <button id="clearMarkers" @click="clearMarkers">Clear</button>
    </body>
  </html>
</template>

Then, create a <div> container and name the id attribute as "map" in the Vue page.

<style>

<style scoped>
html,
body {
  height: 950px;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
#map {
  width: 1000px;
  height: 500px;
  margin: auto;
  display: flex;
  justify-content: center;
  align-items: center;
}
#clearMarkers {
  margin-left: 10px;
  padding: 10px;
}
</style>

Add the required CSS styling.

<script>

export default {
  // Data properties of the component
  data() {
    return {
      map: null,
    };
  }
}

Initialize a variable called map and set it as null

export default {
  // Lifecycle hook: Executed when the component is mounted to the DOM
  mounted() {
    const places = [
      { TITLE: "Australia", LATITUDE: -26.4390917, LONGITUDE: 133.281323 },
      { TITLE: "Malaysia", LATITUDE: 4.140634, LONGITUDE: 109.6181485 },
      { TITLE: "Hong Kong", LATITUDE: 22.3700556, LONGITUDE: 114.1535941 },
      { TITLE: "India", LATITUDE: 21.1289956, LONGITUDE: 82.7792201 },
      { TITLE: "Thailand", LATITUDE: 13.03887, LONGITUDE: 101.490104 },
      { TITLE: "Singapore", LATITUDE: 1.3146631, LONGITUDE: 103.8454093 },
    ];
    this.initMap();
    this.addMarkers(places);
  }
}

Initialize an array that contains the data of places. Then, call the initMap and addMarkers methods.

export default {
  // Methods of the component
  methods: {
    // Method to initialize the Google Map with default settings
    initMap() {
      // Create a new Google Map instance.
      // 'document.getElementById("map")' refers to the HTML element where the map will be displayed.
      // This requires an HTML element with the ID 'map' to be present in the DOM.
      this.map = new google.maps.Map(document.getElementById("map"), {
        // Set the initial center of the map. Here, it's set to latitude 0 and longitude 0 (the geographical center of the Earth).
        center: { lat: 0, lng: 0 },
        // Set the initial zoom level of the map. '2' is quite zoomed out, showing a large portion of the globe.
        zoom: 2,
        // Initialize an empty array for markers.
        // This suggests that the application might add markers to the map later on.
        markers: [],
      });
    }
  }
}
  1. Method Purpose: The initMap method is designed to initialize a Google Map with default settings.

  2. Create Map Instance: It creates a new instance of a Google Map.

  3. Target Map Element: The map instance is associated with the HTML element having the ID "map." This requires an HTML element with the specified ID to be present in the DOM.

  4. Set Initial Center: The initial center of the map is set to latitude 0 and longitude 0, representing the geographical center of the Earth.

  5. Set Initial Zoom Level: The initial zoom level of the map is set to 2, which is quite zoomed out, showing a large portion of the globe.

  6. Initialize Empty Markers Array: An empty array is initialized to hold markers. This implies that the application may add markers to the map later on.

export default {
  // Methods of the component
  methods: {
    // Method to add markers to the map based on the provided data
    addMarkers(data) {
      // Check if the data is not empty or null. If so, proceed with adding markers.
      if (data.length != 0 || data == null) {
        // Reinitialize the map.
        this.initMap();
        // Initialize an array to hold the marker objects.
        const markers = [];
        let currentInfoWindow = null; // Variable to keep track of the currently open info window.
        // Loop through each place in the data array.
        data.forEach((place) => {
          // Create a new marker for each place.
          const marker = new google.maps.Marker({
            position: {
              lat: parseFloat(place.LATITUDE), // Parse the latitude.
              lng: parseFloat(place.LONGITUDE), // Parse the longitude.
            },
            map: this.map, // Set the map where the marker should be added.
            title: place.TITLE, // Set the title for the marker.
          });
          // Add a click listener to each marker.
          marker.addListener("click", () => {
            // Close the currently open info window, if there is one.
            if (currentInfoWindow) {
              currentInfoWindow.close();
            }
            // Create the content for the info window.
            // This includes creating HTML elements dynamically and setting their properties.
            // Elements include a title, coordinates display, and interactive buttons like share, locate, edit, and bookmark.
            const mainDiv = document.createElement("div");
            const titleHolderDiv = document.createElement("div");
            titleHolderDiv.setAttribute("class", "titleHolder");
            titleHolderDiv.innerHTML =
              '<strong style="color:black;">' + place.TITLE + "</strong>";
            const coordinateHolderDiv = document.createElement("div");
            coordinateHolderDiv.setAttribute("class", "coordinateHolder");
            coordinateHolderDiv.innerHTML =
              "<p><b>LATITUDE:</b>" +
              place.LATITUDE +
              "</p><p><b>LONGITUDE:</b>" +
              place.LONGITUDE +
              "</p>";
            mainDiv.appendChild(titleHolderDiv);
            mainDiv.appendChild(coordinateHolderDiv);
            // Create a new info window with the created content.
            const infowindow = new google.maps.InfoWindow({
              content: mainDiv,
            });
            // Open the info window on the map at the marker's position.
            infowindow.open(this.map, marker);
            currentInfoWindow = infowindow;
          });
          const map = this.map;
          // Add the created marker to the markers array.
          markers.push(marker);
          this.map = map;
        });
        // Center the map on the first marker's location and set a zoom level.
        const map = this.map;
        map.setCenter({
          lat: parseFloat(data[0].LATITUDE),
          lng: parseFloat(data[0].LONGITUDE),
        });
        map.setZoom(10);
        // Create a MarkerClusterer instance to manage the markers.
        const markerCluster = new MarkerClusterer({
          map: map,
        });
        // Add all the markers to the marker cluster.
        markers.forEach((marker) => {
          markerCluster.addMarker(marker);
        });
        // Save the markers to the map object for future reference.
        map.markers = markers;
        this.map = map;
      } else {
        // If data is empty or null, reinitialize it without markers.
        this.initMap();
      }
    }
  }
}
  1. Method Purpose: The addMarkers method is responsible for adding markers to the map based on the provided data.

  2. Check Data Validity: It checks if the provided data is not empty or null before proceeding with adding markers.

  3. Reinitialize Map: It reinitializes the map using the initMap method.

  4. Markers Array Initialization: An array called markers is initialized to hold marker objects.

  5. Marker Click Listener: For each place in the data array, a marker is created. A click listener is added to each marker.

  6. Info Window Handling: When a marker is clicked, it closes the currently open info window (if any) and creates a new info window with dynamically generated content, including the title, latitude, and longitude.

  7. Map Centering: The map is centered on the location of the first marker and set to a zoom level of 10.

  8. Marker Clustering: A MarkerClusterer instance is created to manage the markers, and all markers are added to the marker cluster.

  9. Save Markers to Map Object: The markers are saved to the map object for future reference.

  10. Reinitialize Map for Empty Data: If the data is empty or null, it reinitializes the map without markers.

export default {
  // Methods of the component
  methods: {
    // Method to clear markers from the map
    clearMarkers() {
      this.initMap();
    }
  }
}
  1. Method Purpose: The clearMarkers method is designed to clear markers from the map.

  2. Reinitialize Map: It calls the initMap method, which reinitializes the map with default settings.

  3. Effect of Reinitialization: This effectively removes all existing markers from the map, providing a way to clear the map of any previously added markers.

  4. Use Case: This method is typically used in response to a user action, such as clicking a "Clear" button, to reset the map and remove any markers that may have been added.

Download

6KB
Open

Last updated