viabilidade/services/geocodeService.js

36 lines
1005 B
JavaScript
Raw Normal View History

const dotenv = require("dotenv");
dotenv.config();
const axios = require("axios");
// 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;
}
}
module.exports = { geocodeWithGoogle };