Spaces:
Runtime error
Runtime error
File size: 5,589 Bytes
a36f8c3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | /**
* Google Apps Script example for integrating with Kamlan KML Analyzer API
*
* Instructions:
* 1. Replace 'YOUR_API_BASE_URL' with your actual deployed app URL
* 2. Use this script in Google Sheets to analyze KML files automatically
* 3. The functions can be called from spreadsheet cells or triggered by events
*/
const API_BASE_URL = 'YOUR_API_BASE_URL'; // Replace with your deployed app URL
/**
* Analyzes a KML file and returns geometry metrics
* @param {string} kmlUrl - URL of the KML file to analyze
* @return {Array} Array containing [centroid_lat, centroid_lon, area_ha, perimeter_m]
*/
function analyzeKML(kmlUrl) {
try {
const apiUrl = `${API_BASE_URL}/api/analyze_kml?file_url=${encodeURIComponent(kmlUrl)}`;
const response = UrlFetchApp.fetch(apiUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
muteHttpExceptions: true
});
const responseText = response.getContentText();
const data = JSON.parse(responseText);
if (data.success) {
return [
data.data.centroid_lat,
data.data.centroid_lon,
data.data.area_ha,
data.data.perimeter_m
];
} else {
throw new Error(`API Error: ${data.error}`);
}
} catch (error) {
console.error('Error analyzing KML:', error);
return [`Error: ${error.toString()}`, '', '', ''];
}
}
/**
* Get only the centroid coordinates from a KML file
* @param {string} kmlUrl - URL of the KML file to analyze
* @return {Array} Array containing [latitude, longitude]
*/
function getCentroid(kmlUrl) {
const result = analyzeKML(kmlUrl);
if (typeof result[0] === 'string' && result[0].startsWith('Error:')) {
return result.slice(0, 2);
}
return [result[0], result[1]];
}
/**
* Get area in hectares from a KML file
* @param {string} kmlUrl - URL of the KML file to analyze
* @return {number} Area in hectares
*/
function getArea(kmlUrl) {
const result = analyzeKML(kmlUrl);
if (typeof result[0] === 'string' && result[0].startsWith('Error:')) {
return result[0];
}
return result[2];
}
/**
* Get perimeter in meters from a KML file
* @param {string} kmlUrl - URL of the KML file to analyze
* @return {number} Perimeter in meters
*/
function getPerimeter(kmlUrl) {
const result = analyzeKML(kmlUrl);
if (typeof result[0] === 'string' && result[0].startsWith('Error:')) {
return result[0];
}
return result[3];
}
/**
* Batch analyze multiple KML files
* @param {Array} kmlUrls - Array of KML URLs
* @return {Array} Array of analysis results
*/
function batchAnalyzeKMLs(kmlUrls) {
const results = [];
for (let i = 0; i < kmlUrls.length; i++) {
const url = kmlUrls[i];
if (url && url.trim() !== '') {
const result = analyzeKML(url);
results.push([url, ...result]);
// Add small delay to avoid rate limiting
Utilities.sleep(500);
}
}
return results;
}
/**
* Check if the API is healthy
* @return {string} API health status
*/
function checkAPIHealth() {
try {
const response = UrlFetchApp.fetch(`${API_BASE_URL}/api/health`);
const data = JSON.parse(response.getContentText());
return data.status;
} catch (error) {
return `Error: ${error.toString()}`;
}
}
/**
* Example function to populate a Google Sheet with KML analysis data
* This function assumes:
* - Column A contains KML URLs
* - Results will be written starting from Column B
*/
function analyzeKMLsInSheet() {
const sheet = SpreadsheetApp.getActiveSheet();
const lastRow = sheet.getLastRow();
// Get KML URLs from column A (starting from row 2, assuming row 1 has headers)
const urlRange = sheet.getRange(2, 1, lastRow - 1, 1);
const urls = urlRange.getValues().flat();
// Set up headers if they don't exist
const headers = ['KML URL', 'Latitude', 'Longitude', 'Area (ha)', 'Perimeter (m)', 'Status'];
sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
// Analyze each KML and populate results
for (let i = 0; i < urls.length; i++) {
const url = urls[i];
const rowNum = i + 2; // +2 because we start from row 2
if (url && url.trim() !== '') {
sheet.getRange(rowNum, 6).setValue('Processing...');
const result = analyzeKML(url);
// Write results to columns B, C, D, E
sheet.getRange(rowNum, 2, 1, 4).setValues([result]);
// Update status
const status = typeof result[0] === 'string' && result[0].startsWith('Error:') ? 'Error' : 'Complete';
sheet.getRange(rowNum, 6).setValue(status);
// Add delay to avoid overwhelming the API
Utilities.sleep(1000);
}
}
}
/**
* Custom menu function to add KML Analysis menu to Google Sheets
*/
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu('KML Analysis')
.addItem('Analyze KMLs in Column A', 'analyzeKMLsInSheet')
.addItem('Check API Health', 'showAPIHealth')
.addToUi();
}
/**
* Show API health status in a dialog
*/
function showAPIHealth() {
const status = checkAPIHealth();
const ui = SpreadsheetApp.getUi();
ui.alert('API Health Status', `Status: ${status}`, ui.ButtonSet.OK);
}
// Usage examples in spreadsheet formulas:
// =analyzeKML("https://example.com/your-file.kml") - Returns all metrics
// =getCentroid("https://example.com/your-file.kml") - Returns only lat, lon
// =getArea("https://example.com/your-file.kml") - Returns only area in hectares
// =getPerimeter("https://example.com/your-file.kml") - Returns only perimeter in meters |