sothis-contratacao-api/src/services/googleService.js

37 lines
1.2 KiB
JavaScript
Raw Normal View History

const apiConfig = require("../config/apiConfig.js")
const axios = require("axios");
// Geocode using Google Geocoding API. Returns { lat, lon } or null
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,
});
// ensure HTTP 200
if (!r || r.status !== 200) {
console.warn(`geocodeWithGoogle unexpected status for '${address}': ${r && r.status}`);
return null;
}
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 };