SharedMap.vue

This is where the user can see a map shared to them.

import

// Importing Axios for making HTTP requests and MarkerClusterer for clustering markers on Google Maps
import axios from "axios";
import { MarkerClusterer } from "@googlemaps/markerclusterer";

Above, we are importing the "axios" package which is used to make API call to the backend (Laravel). It is important because this is like the key that allows us to communicate with the backend.

Finally, is the "MarkerClusterer" package. This package is used to make clusters in the map when there are too many markers in the map. This makes the map less messy and reduces lag.

export default

// Exporting the Vue component
export default {}

Inside this is where we define data, methods, computed properties, and lifecycle hooks.

data

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

The data method is used to initialize and define the data properties for this component. See the source code to know what each variable is used for.

mounted

// Lifecycle hook: Executed when the component is mounted to the DOM
mounted() {
  // Scroll to the top of the window when the component is mounted
  window.scrollTo(0, 0);
  // Setting backend domain from the Vuex store
  this.domainBackend = this.$store.state.domainBackend;
  // Load and display the shared map data
  this.getSharedMap();
}

This is called mounted lifecycle hook. The mounted hook is called after the component has been added to the DOM, making it a good place to perform initial setup and actions.

To explain what this mounted hook does:

  1. It scrolls the window to the top so the user sees the content at the beginning of the page.

  2. It gets the backend domain from what is defined in the Vuex.

  3. It gets the shared map.

methods

// Methods of the component
methods: {}

The methods option is used to define methods that can be called or triggered within a Vue component. These methods are typically used to define the behavior and functionality of the component

getSharedMap

// Method to initiate the process of fetching and displaying a shared map based on the route parameters
getSharedMap() {
  // Prepare the request data with the fileName from the route parameters
  const request = {
    fileName: this.$route.params.fileName,
  };
  // Make a POST request to the server API to get shared map data
  axios
    .post(this.domainBackend + "/api/getSharedMap", request)
    .then((response) => {
      // Check if the server response indicates success (SUCCESS == 1)
      if (response.data.SUCCESS == 1) {
        // Initialize the map
        this.initMap();
        // Add markers to the map based on the received data
        this.addMarkers(response.data.DATA["DATA"]);
      } else if (response.data.SUCCESS == 0) {
        // If the server response indicates failure, show an alert for an invalid URL
        alert("INVALID URL.");
      }
    });
}

To explain what this getSharedMap method does:

  1. It will send the file name of the JSON file that contains the shared map to the backend. The file name is present in the URL to the shared map.

  2. If the file exists, the backend will respond with the JSON representation of the map data. It will just initialize an empty map to display. It will add the markers in the map.

  3. If the file does not exist, it will alert the user with a message.

initMap

// Method to initialize the Google Map and handle the server response for shared map data
initMap() {
  // Create a new Google Map instance and assign it to the component's 'map' property
  this.map = new google.maps.Map(document.getElementById("map"), {
    // Set the initial center of the map to latitude 0 and longitude 0
    center: { lat: 0, lng: 0 },
    // Set the initial zoom level of the map to 2
    zoom: 2,
    // Initialize an empty array to store markers on the map
    markers: [],
  });
}

To explain what this initMap method does:

  1. It initializes a Google Map on the page.

addMarkers

// Method to add markers to the Google Map based on the received data
addMarkers(data) {
  // Check if there is data to display
  if (data.length != 0) {
    // Reset the map and initialize a new one
    this.map = null;
    this.initMap();
    // Initialize an array to store markers
    const markers = [];
    let currentInfoWindow = null;
    // Iterate through the provided data to create markers on the map
    data.forEach((place) => {
      // Create a new Google Maps marker for each place in the data
      const marker = new google.maps.Marker({
        position: {
          lat: parseFloat(place.LATITUDE),
          lng: parseFloat(place.LONGITUDE),
        },
        map: this.map,
        title: place.NAME,
      });
      // Add a click event listener to each marker
      marker.addListener("click", () => {
        // Close the current info window if it exists
        if (currentInfoWindow) {
          currentInfoWindow.close();
        }
        // Create a custom info window for the clicked marker
        const mainDiv = document.createElement("div");
        const titleHolderDiv = document.createElement("div");
        titleHolderDiv.setAttribute("class", "titleHolder");
        titleHolderDiv.innerHTML =
          '<strong style="color:black;">' + place.NAME + "</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>";
        const iconsHolderDiv = document.createElement("div");
        iconsHolderDiv.setAttribute("class", "iconsHolder");
        const bookmarkButtonDiv = document.createElement("div");
        bookmarkButtonDiv.setAttribute("class", "icon");
        bookmarkButtonDiv.style.backgroundColor = "white";
        bookmarkButtonDiv.style.borderColor = "white";
        bookmarkButtonDiv.addEventListener("click", () =>
          this.bookmarkRow(place)
        );
        bookmarkButtonDiv.innerHTML =
          '<i id="myBookmark" class="fa fas fa-bookmark" aria-hidden="true"></i><span class="tooltiptext">Bookmark</span>';
        iconsHolderDiv.appendChild(bookmarkButtonDiv);
        mainDiv.appendChild(titleHolderDiv);
        mainDiv.appendChild(coordinateHolderDiv);
        mainDiv.appendChild(iconsHolderDiv);
        // Create a new info window with the custom content and open it
        const infowindow = new google.maps.InfoWindow({
          content: mainDiv,
        });
        infowindow.open(this.map, marker);
        currentInfoWindow = infowindow;
      });
      // Add the marker to the array
      const map = this.map;
      markers.push(marker);
      this.map = map;
    });
    // Set the center and zoom level of the map based on the first data point
    const map = this.map;
    map.setCenter({
      lat: parseFloat(data[0].LATITUDE),
      lng: parseFloat(data[0].LONGITUDE),
    });
    map.setZoom(10);
    // Create a marker clusterer and add markers to it
    const markerCluster = new MarkerClusterer({
      map: map,
    });
    markers.forEach((marker) => {
      markerCluster.addMarker(marker);
    });
    // Store the markers array in the map object
    map.markers = markers;
    this.map = map;
  } else {
    // If there is no data, reset the map
    this.map = null;
    this.initMap();
  }
}

To explain what this addMarkers method does:

  1. if the map data is not empty, it proceeds with the following steps; otherwise, it initializes the map and sets it to null.

  2. It initializes a Google Map and creates an empty array to hold markers.

  3. It iterates through each item in the map data, creating a marker on the map for each place listed in the map data. Each marker has a title, a click event listener, and an info window that displays additional information about the place when clicked.

  4. It sets up icons and event listeners for buttons within the info window, allowing action like bookmarking the place.

  5. The markers are clustered together for better visualization when there are multiple markers in close proximity.

bookmarkRow

// Method triggered when the user clicks the bookmark button for a map location, handling bookmark addition
bookmarkRow(itemForBookmark) {
  // Check if the user is logged in by verifying the availability of a user ID cookie
  if (!this.$cookie.isCookieAvailable("L_userId")) {
    // If not logged in, alert the user that login is required
    alert("LOGIN REQUIRED.");
  } else {
    // If logged in, proceed to fetch the user's bookmarks
    const request = {
      userId: this.$cookie.getCookie("L_userId"),
    };
    axios
      .post(this.domainBackend + "/api/getBookmark", request)
      .then((response) => {
        // Check if the request to fetch bookmarks was successful
        if (response.data.SUCCESS == 1) {
          // Extract bookmark data from the response
          const data = response.data.DATA;
          // Check if the current item is already in the user's bookmarks
          var isExist = false;
          data.forEach((item) => {
            if (
              item.LATITUDE.toString() ===
                itemForBookmark.LATITUDE.toString() &&
              item.LONGITUDE.toString() ===
                itemForBookmark.LONGITUDE.toString()
            ) {
              isExist = true;
              return;
            }
          });
          // If the item is already bookmarked, alert the user
          if (isExist == true) {
            alert("BOOKMARK ALREADY EXISTS.");
          } else {
            // If the item is not bookmarked, add it to the bookmarks array
            data.push(itemForBookmark);
            // Prepare a request to update the user's bookmarks on the server
            const request = {
              jsonData: JSON.stringify({
                USER_ID: this.$cookie.getCookie("L_userId"),
                DATA: data,
              }),
            };
            // Make a request to update the user's bookmarks on the server
            axios
              .post(this.domainBackend + "/api/storeBookmark", request)
              .then((response) => {
                // Check if the update was successful and alert the user
                if (response.data.SUCCESS == 1) {
                  alert("BOOKMARK UPDATED.");
                }
              });
          }
        }
      });
  }
}

To explain what this bookmarkRow method does:

  1. If the user is not logged in, it displays an alert, indicating that the user must be logged in to use this feature.

  2. it sends the user's ID to the backend to retrieve the data in the user's bookmark file.

  3. It then checks if the going-to-be-added bookmark item already exists in the user's bookmark data.

  4. If the item already exists in the user's bookmark data, displays an alert, indicating that the bookmark already exists.

  5. If the item does not exist in the user's bookmark data, it adds the item to the user's bookmark data and sends the bookmark data to update the user's bookmark file.

Last updated