- Criada função que consulta o endereço utilizando lat e lon. - Alterada a função que lê o CSV de upload para que ignore linhas vazias.
42 lines
1.7 KiB
JavaScript
42 lines
1.7 KiB
JavaScript
const dotenv = require('dotenv');
|
|
const axios = require('axios');
|
|
dotenv.config();
|
|
|
|
// Geocode using Google Geocoding API. Returns { lat, lon } or null
|
|
async function geocodeWithGoogle(address) {
|
|
const key = process.env.GOOGLE_API_KEY;
|
|
if (!key) return null;
|
|
try {
|
|
const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(address)}&key=${encodeURIComponent(key)}`;
|
|
const r = await axios.get(url, { timeout: 10000 });
|
|
if (r && r.data && Array.isArray(r.data.results) && r.data.results.length > 0) {
|
|
const loc = r.data.results[0].geometry && r.data.results[0].geometry.location;
|
|
if (loc && loc.lat !== undefined && loc.lng !== undefined) {
|
|
return { lat: Number(loc.lat), lon: Number(loc.lng) };
|
|
}
|
|
}
|
|
return null;
|
|
} catch (e) {
|
|
console.warn(`geocodeWithGoogle error for '${address}': ${e.message}`);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
async function addressWithGoogle(lat, lon) {
|
|
const key = process.env.GOOGLE_API_KEY;
|
|
if (!key) return null;
|
|
try {
|
|
const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${encodeURIComponent(lat)},${encodeURIComponent(lon)}&key=${encodeURIComponent(key)}`;
|
|
const r = await axios.get(url, { timeout: 10000 });
|
|
if (r && r.data && Array.isArray(r.data.results) && r.data.results.length > 0) {
|
|
console.log(`Google Reverse Geocoding result for ${lat},${lon}: ${r.data.results[0].formatted_address}`);
|
|
return r.data.results[0].formatted_address || null;
|
|
}
|
|
return null;
|
|
} catch (e) {
|
|
console.warn(`addressWithGoogle error for '${lat},${lon}': ${e.message}`);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
module.exports = { geocodeWithGoogle, addressWithGoogle }; |