-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse-geocode-rinks.js
More file actions
265 lines (212 loc) Β· 7.62 KB
/
reverse-geocode-rinks.js
File metadata and controls
265 lines (212 loc) Β· 7.62 KB
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
const { createClient } = require('@supabase/supabase-js');
const https = require('https');
const fs = require('fs');
// Load environment variables
require('dotenv').config();
// Initialize Supabase client
const supabaseUrl = process.env.SUPABASE_URL;
const supabaseKey = process.env.SUPABASE_KEY;
if (!supabaseUrl || !supabaseKey) {
console.error('β Missing required environment variables: SUPABASE_URL and SUPABASE_KEY');
process.exit(1);
}
const supabase = createClient(supabaseUrl, supabaseKey);
// Rate limiting: 1 request per second for OpenStreetMap Nominatim
const RATE_LIMIT_DELAY = 1000; // 1 second
// Sleep function for rate limiting
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// Reverse geocoding function using OpenStreetMap Nominatim API
async function reverseGeocode(latitude, longitude) {
return new Promise((resolve, reject) => {
const url = `https://nominatim.openstreetmap.org/reverse?lat=${latitude}&lon=${longitude}&format=json&addressdetails=1`;
const options = {
headers: {
'User-Agent': 'RinkWatch-Geocoder/1.0 (your-email@example.com)' // Replace with your email
}
};
https.get(url, options, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
try {
const result = JSON.parse(data);
if (result.error) {
reject(new Error(`Geocoding error: ${result.error}`));
return;
}
const address = result.address || {};
// Extract city from various possible fields
const city = address.city ||
address.town ||
address.village ||
address.municipality ||
address.county ||
address.hamlet ||
null;
// Extract province/state
const province = address.state ||
address.province ||
address.region ||
null;
resolve({
city: city,
province: province,
country: address.country || null,
full_address: result.display_name || null
});
} catch (parseError) {
reject(new Error(`Failed to parse geocoding response: ${parseError.message}`));
}
});
}).on('error', (error) => {
reject(new Error(`HTTP request failed: ${error.message}`));
});
});
}
// Function to fetch rinks with null city/province
async function fetchRinksToUpdate() {
try {
console.log('π Fetching rinks with missing city/province data...');
const { data, error } = await supabase
.from('rinks')
.select('id, name, latitude, longitude, city, province')
.or('city.is.null,province.is.null');
if (error) {
throw new Error(`Supabase query error: ${error.message}`);
}
console.log(`π Found ${data.length} rinks that need geocoding`);
return data;
} catch (error) {
console.error('β Error fetching rinks:', error.message);
throw error;
}
}
// Function to update a single rink
async function updateRink(rinkId, city, province) {
try {
const { error } = await supabase
.from('rinks')
.update({
city: city,
province: province,
updated_at: new Date().toISOString()
})
.eq('id', rinkId);
if (error) {
throw new Error(`Failed to update rink ${rinkId}: ${error.message}`);
}
return true;
} catch (error) {
console.error(`β Error updating rink ${rinkId}:`, error.message);
return false;
}
}
// Function to log progress to file
function logProgress(message) {
const timestamp = new Date().toISOString();
const logMessage = `[${timestamp}] ${message}\n`;
console.log(message);
fs.appendFileSync('geocoding-progress.log', logMessage);
}
// Main processing function
async function processRinks() {
const startTime = Date.now();
let processedCount = 0;
let successCount = 0;
let errorCount = 0;
const errors = [];
try {
// Fetch rinks that need updating
const rinks = await fetchRinksToUpdate();
if (rinks.length === 0) {
logProgress('β
No rinks need geocoding. All rinks already have city and province data.');
return;
}
logProgress(`π Starting geocoding process for ${rinks.length} rinks...`);
// Process each rink
for (let i = 0; i < rinks.length; i++) {
const rink = rinks[i];
processedCount++;
try {
logProgress(`π Processing rink ${processedCount}/${rinks.length}: "${rink.name}" (${rink.latitude}, ${rink.longitude})`);
// Perform reverse geocoding
const geocodeResult = await reverseGeocode(rink.latitude, rink.longitude);
// Only update if we got useful data
if (geocodeResult.city || geocodeResult.province) {
const updateSuccess = await updateRink(
rink.id,
geocodeResult.city || rink.city,
geocodeResult.province || rink.province
);
if (updateSuccess) {
successCount++;
logProgress(`β
Updated "${rink.name}": City="${geocodeResult.city || 'unchanged'}", Province="${geocodeResult.province || 'unchanged'}"`);
} else {
errorCount++;
}
} else {
logProgress(`β οΈ No city/province data found for "${rink.name}"`);
}
// Rate limiting: wait 1 second before next request
if (i < rinks.length - 1) {
await sleep(RATE_LIMIT_DELAY);
}
} catch (geocodeError) {
errorCount++;
const errorMsg = `β Failed to geocode "${rink.name}": ${geocodeError.message}`;
logProgress(errorMsg);
errors.push({ rink: rink.name, error: geocodeError.message });
// Continue processing other rinks even if one fails
continue;
}
}
} catch (error) {
logProgress(`π₯ Fatal error: ${error.message}`);
throw error;
}
// Final summary
const endTime = Date.now();
const duration = Math.round((endTime - startTime) / 1000);
logProgress('\nπ GEOCODING SUMMARY:');
logProgress(`β±οΈ Total time: ${duration} seconds`);
logProgress(`π Total processed: ${processedCount}`);
logProgress(`β
Successfully updated: ${successCount}`);
logProgress(`β Errors: ${errorCount}`);
if (errors.length > 0) {
logProgress('\nβ ERROR DETAILS:');
errors.forEach(error => {
logProgress(` β’ ${error.rink}: ${error.error}`);
});
}
logProgress('\nπ Geocoding process completed!');
}
// Main execution
async function main() {
try {
// Create log file
fs.writeFileSync('geocoding-progress.log', `Geocoding started at ${new Date().toISOString()}\n`);
logProgress('π RinkWatch Reverse Geocoding Script');
logProgress('=====================================');
// Test Supabase connection
logProgress('π Testing Supabase connection...');
const { data, error } = await supabase.from('rinks').select('count').single();
if (error) {
throw new Error(`Supabase connection failed: ${error.message}`);
}
logProgress('β
Supabase connection successful');
// Start processing
await processRinks();
} catch (error) {
logProgress(`π₯ Script failed: ${error.message}`);
process.exit(1);
}
}
// Handle process termination gracefully
process.on('SIGINT', () => {
logProgress('\nβΉοΈ Process interrupted by user');
process.exit(0);
});
// Run the script
main();