Display information from a Google Sheet onto a leaflet map based on specified categories

I am currently facing some challenges while creating a map with markers using data from Google Sheet and leaflet. Despite my efforts, I have encountered a few bugs that are proving to be difficult to resolve:

  1. Group Filtering - Although I can successfully filter by group, only one marker is displayed for each selected group even when there are multiple data points within the same group. You can view the output in the attached photo https://i.stack.imgur.com/uGM8e.png.
  2. Marker Replacements - My intention was for the map to display markers corresponding to the selected group exclusively. However, if I select a group (e.g., Male) and then try to switch to another group (Female), the marker representing the previous group remains visible. Check out the issue illustrated here: https://i.stack.imgur.com/wrQsG.png.

Here is a glimpse of the sample data retrieved from Google Sheet https://i.stack.imgur.com/BXnll.png.

Presented below is an excerpt of my code:

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('map');
}

function getAddress(group) {
  var ss= SpreadsheetApp.getActiveSpreadsheet();
  var groupSheet = ss.getSheetByName("Sheet1"); 
  var getLastRow = groupSheet.getLastRow();  
  var return_array = [];
  if (group === 'All'){
    return groupSheet.getRange(2, 1, getLastRow - 1, 5).getValues();  
  } else {
    for (var i = 2; i<= getLastRow; i++){
      if (groupSheet.getRange(i,3).getValue() === group){
        return_array.push(groupSheet.getRange(i,1,1,5).getValues());
      }
    }
    return return_array;
  }
}

HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Document</title>
    <link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="741811151218110034455a435a45">[email protected]</a>/dist/leaflet.css"
        integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
        crossorigin="" />
    <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="036f6662656f667743322d342d32">[email protected]</a>/dist/leaflet.js"
        integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
        crossorigin=""></script>
</head>
...Continued...
</style>

Your assistance in resolving these issues would be greatly appreciated!

Answer №1

Trying out maps for the first time and seeing success.

Make necessary changes to your files.

HTML_TestMap

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Document</title>
    <link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f69a9397909a9382b6c7d8c1d8c7">[email protected]</a>/dist/leaflet.css"
        integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
        crossorigin="" />
    <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6cac3c7c0cac3d2e69788918897">[email protected]</a>/dist/leaflet.js"
        integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
        crossorigin=""></script>
    <style>
      body {
          margin: 0;
          padding: 0;
      }

      #viewmap {
          width: 100%;
          height: 100vh;
      }

      #text {
        font-family:Georgia,'Times New Roman', Times, serif;
      }
    </style>
  </head>
  <body>
    <div id="divfilter" class="col12" onchange="onSelect()">
      Select a group:  
        <div class="col4">
            <input type="radio" name="filGroup" value="All" checked>All
        </div>
        <div class="col4">
            <input type="radio" name="filGroup" value="Male" >Male
        </div>
        <div class="col4">
            <input type="radio" name="filGroup" value="Female" >Female
        </div>
    </div>
    <div id="viewmap"></div>
    
    <script>
      var map_init = null;
      var basemap = null;
      var map_markers = [];

      (function () {
        try {
          map_init = L.map('viewmap',{
            center: [4.042649, 103.624396],
            zoom:8
          });
          basemap = L.tileLayer ('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          }).addTo (map_init);
        }
        catch(err) {
          alert(err);
        }
      })();

      function onSelect(){
        var map = map_init;
        var group = document.querySelector('input[name="filGroup"]:checked').value;
    
        google.script.run.withSuccessHandler(
          function(ar){
            try {
              map_markers.forEach( marker => marker.remove() );
              map_markers = [];
              ar.forEach(function(item, index){
                var group = document.querySelector('input[name="filGroup"]:checked').value;

                var marker = L.marker([item[0], item[1]]).addTo(map);
                marker.bindPopup('<div class="mapFlag" id="text"><p>Name: ' + item[3] + '<br>DOB: ' + item[4] + '</p></div>' );
                map_markers.push(marker);
              });
            }
            catch(err) {
              alert(err);
            }
          }
        ).getAddress(group);  
      }
    </script>
  </body>
</html>

Code.gs

function getAddress(group) {
  try {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var groupSheet = ss.getSheetByName("Sheet1");
    let values = groupSheet.getDataRange().getValues();
    values.shift(); // remove headers
    if( group !== 'All' ) {
      values = values.filter( row => row[2] === group )
    }
    return values;
  }
  catch(err) {
    Logger.log(err);
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to ensure unique results when using DFS for Combination Sum?

I am currently tackling the challenge of solving LeetCode #49 Combination Sum. The objective here is to identify all the distinct combinations that add up to the specified target. While it's relatively straightforward to find permutations that result ...

Converting Promises to Observables

Struggling with the syntax as I delve into learning Angular, I need to transform a promise into an Observable. Let me share what I've encountered: In the function getCountries (subscribed by another utility), there is a call required to fetch a list ...

Error in line 36: firebase.auth function is undefined

Snippet of index.html code <html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" ...

Issue encountered while trying to download Jade through npm (npm install -g jade)

I am having trouble downloading jade via npm on my Mac (Yosemite). After downloading node and updating npm, I tried to install jade but encountered a series of errors that I cannot resolve. Even attempting to use sudo did not help, as it only displayed s ...

"Execute asynchronous tasks in Javascript and receive the returned

Currently, I am utilizing JSF ajax within my application and unfortunately, we are unable to make any changes to that. In the process of waiting for user action, I find it necessary to prompt the user before executing the ajax method. Specifically, I need ...

Bring in the content to Notepad utilizing jQuery

How can I export data to Notepad? I have fields for Name, Age, and WorkingStatus that are input as text and textarea. Is there a demo or code available to help me insert this data into Notepad? ...

Transforming ajax code into node.js

After mastering ajax calls for client-server interaction, I am facing a challenge in converting my code to a server-side node compatible JS using http requests. Despite reading various tutorials, I am struggling to adapt them to fit with my current code st ...

Having trouble with Vue component registration repeatedly failing

Currently, I am working on a front-end project using [THIS VUE TEMPLATE][https://www.creative-tim.com/product/vue-material-dashboard-pro] The issue I am facing involves trying to register a component locally and encountering the following error: "1 ...

Switch the visibility of a div tag using Next.js

Script export default function Navigation(){ let displayMenu = false; function toggleMenu() { displayMenu = !displayMenu; } return ( <> <button onClick={toggleMenu}>Toggle Navigation</button> {/*This code sh ...

Identify the nested Object within the Json data

I am looking to add and name a nested object within my Json data structure. The current structure of my Json is as follows: { "MH": [ { "MHF46": "Ledig", "MHF60": "60", }, ...

What could be the reason for the failure of the async await implementation in this particular code sample?

While attempting to follow a tutorial on YouTube, I encountered an issue where the code didn't work as expected. Can anyone lend a hand in helping me figure out what might be going wrong? let posts = [ {name: '1', data: 'Hi1'}, ...

Preventing Vue.js SPA from accessing cached version when JWT expires: the solution

I'm encountering an issue with my Vue.js / Express application that I can't seem to resolve. Here's how the process unfolds: An unauthenticated user logs into the app and is presented with the login page. Once successfully authenticated, t ...

Send a request to templateUrl

After experimenting with AngularJS, I decided to create a dynamic route system that funnels all routes through a single PHP file. This was motivated by my desire to prevent users from accessing raw templateUrl files and seeing unstyled partial pages. Prio ...

Access to data retrieval was restricted by CORS policies on my Node.js/Express REST API server

I am currently running a localhost node/express server that is designed to accept any post request with a body and then return the same body along with a message. To enable Cross-Origin Resource Sharing (CORS), I have integrated the cors node package into ...

I encountered an issue while constructing a React application. An error message popped up indicating: "Warning: Can't execute a React state update on a component that is not mounted"

Having difficulty pinpointing the source of the error message displayed below. Should I focus my investigation on the specific lines mentioned in the console, such as Toolbar.js:15? Is the console indicating that the error lies there? Additionally, what i ...

Creating a conditional statement in jQuery that will append text to a specific DIV element after a form has been successfully

I currently have a form set up that is functioning properly, but I am looking to make some changes. Instead of redirecting the user to a new page with a success message upon submitting the form, I want the success message to be displayed in a div next to t ...

Error with WooCommerce checkout causing input values to disappear upon clicking or submitting

I am facing an issue where I need to set #billing-postcode to a specific value using a JS script. When I input jQuery('#billing-postcode').val('2222') on the checkout page, the input displays the value 2222 with the Postcode label abov ...

Searching for specific data within an embedded documents array in MongoDB using ID

While working with mongodb and nodejs to search for data within an embedded document, I encountered a strange issue. The query functions as expected in the database but not when implemented in the actual nodejs code. Below is the structure of my data obje ...

Error: The property 'parentNode' cannot be read because it is null

I wanted to test if my laptop can handle WebGL by loading examples from my instructor's webpage. The examples on the webpage worked fine, just showing a square within a square. I then decided to copy the exact codes into a notepad text editor, saved t ...

Crop images in a canvas using a customized rectangle with the help of JQuery

I am trying to crop an image inside a Canvas element using a selection rectangle. My project utilizes jQuery and I am in search of a plugin that can help me implement this custom selection rectangle on the canvas itself, not just on images. Are there any ...