33 lines
1000 B
JavaScript
33 lines
1000 B
JavaScript
|
|
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?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 };
|