Error loading data - google sheet app script, javascript, geohash

83 views Asked by At

I'm trying to calculate the geohash of a lat, long pair in a Google sheet. I've created this function in Apps Script:

    var base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
    
    function GEOHASH(lat, lon, len) {
      if (len === undefined) {
        len = 9; 
      }
      
      var geohash = [];
      
      lat = Number(lat);
      lon = Number(lon);
    
      var minLat = -90, maxLat = 90;
      var minLon = -180, maxLon = 180;
    
      var mid;
      var bits = 0;
      var evenBit = true;
    
      while (geohash.length < len) {
        if (evenBit) {
          mid = (minLon + maxLon) / 2;
          if (lon > mid) {
            minLon = mid;
            bits |= 1<<bits;
          } else { 
            maxLon = mid; 
          }
        } else {
          mid = (minLat + maxLat) / 2;
          if (lat > mid) { 
            minLat = mid;
            bits |= 1<<bits;  
          } else {
            maxLat = mid;
          }
        }
        evenBit = !evenBit;
        if (bits == parseInt("1".repeat(geohash.length), 2)) {  
          geohash.push(base32.charAt(bits));
          bits = 0; 
        }
      }
      return geohash.join("");  
    }

in the sheet, when calling GEOHASH([lat-cell],[lon-cell],10) I get either Error loading data or Exceeded maximum execution time (line 0).

I suppose the while loop could easily exceed the timelimit placed on scripts?

But I wondered if anyone could see other issues with the code, or suggest other reasons/solutions for the issue. Any other way to calculate the geohash in the sheet are very welcome too.

Here's a sample of the data being used: enter image description here

1

There are 1 answers

7
TheWizEd On BEST ANSWER

Using the class presented at MTS Geohash I created a custom function. I had to remove the keyword static from each method of the class. I guess its not recognized by the version of javascript implemented in Google App Script.

function GEOHASH(lat,lon,precision) {
  try {
    let geo = new Geohash();
    return geo.encode(lat,lon,precision);
  }
  catch(err) {
    console.log(err);
  }
}

enter image description here