- Agora a API do Geogrid faz a viabilidade apenas por caixas. - Retirado rotas iniciais de testes, mantive apenas a /viabilidade.
40 lines
1.3 KiB
JavaScript
40 lines
1.3 KiB
JavaScript
const apiConfig = require("../config/apiConfig.js")
|
|
const axios = require("axios");
|
|
|
|
|
|
// Geocodifica um endereço usando a API do Google Maps
|
|
|
|
async function geocodeWithGoogle(address) {
|
|
const key = apiConfig.googleApiKey;
|
|
if (!key) return null;
|
|
try {
|
|
const url = 'https://maps.googleapis.com/maps/api/geocode/json';
|
|
const r = await axios.get(url, {
|
|
params: { address, key },
|
|
timeout: 10000,
|
|
});
|
|
|
|
// Valida a resposta e extrai as coordenadas
|
|
if (!r || r.status !== 200) {
|
|
console.warn(`geocodeWithGoogle unexpected status for '${address}': ${r && r.status}`);
|
|
return null;
|
|
}
|
|
|
|
// Verifica se há resultados válidos
|
|
|
|
if (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;
|
|
const lat = loc && (loc.lat !== undefined ? Number(loc.lat) : NaN);
|
|
const lng = loc && (loc.lng !== undefined ? Number(loc.lng) : NaN);
|
|
if (!Number.isNaN(lat) && !Number.isNaN(lng)) {
|
|
return { lat, lon: lng };
|
|
}
|
|
}
|
|
return null;
|
|
} catch (e) {
|
|
console.warn(`geocodeWithGoogle error for '${address}': ${e && e.message}`, e && e.stack);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
module.exports = { geocodeWithGoogle }; |