document.addEventListener("DOMContentLoaded", function () {
const boton = document.getElementById("buscar-iglesia");
if (!boton) return;
boton.addEventListener("click", function (e) {
e.preventDefault();
if (!navigator.geolocation) {
alert("Tu navegador no permite geolocalización.");
return;
}
navigator.geolocation.getCurrentPosition(function (position) {
const userLat = position.coords.latitude;
const userLon = position.coords.longitude;
function distancia(lat1, lon1, lat2, lon2) {
const R = 6371;
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLon = (lon2 - lon1) * Math.PI / 180;
const a =
Math.sin(dLat/2) ** 2 +
Math.cos(lat1 * Math.PI / 180) *
Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon/2) ** 2;
return 2 * R * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
let masCercana = null;
let distanciaMin = Infinity;
IPUE_IGLESIAS.forEach(iglesia => {
if (!iglesia.lat || !iglesia.lng) return;
const d = distancia(
userLat,
userLon,
parseFloat(iglesia.lat),
parseFloat(iglesia.lng)
);
if (d < distanciaMin) {
distanciaMin = d;
masCercana = iglesia;
}
});
if (masCercana) {
window.location.href = masCercana.url;
} else {
alert("No se encontró ninguna iglesia.");
}
}, function () {
alert("No se pudo obtener tu ubicación.");
});
});
});