D7net
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
var
/
www
/
html
/
crsys_ant
/
Filename :
distanciacep.php
back
Copy
<!DOCTYPE html> <html> <head> <title>Distância entre CEPs</title> <style> body { font-family: Arial, sans-serif; margin: 40px; } input { margin: 5px; padding: 8px; width: 150px; } button { padding: 8px 12px; margin: 10px; } #resultado { margin-top: 20px; font-weight: bold; } </style> </head> <body> <h2>Calcular distância entre dois CEPs</h2> <input type="text" id="cep1" placeholder="CEP de origem"> <input type="text" id="cep2" placeholder="CEP de destino"> <button onclick="consultarDistancia()">Calcular</button> <div id="resultado"></div> <script> function formatarCEP(valor) { const cepLimpo = valor.replace(/\D/g, ''); return cepLimpo.replace(/^(\d{5})(\d{3})$/, '$1-$2'); } async function consultarCep(cep) { const response = await fetch(`https://cep.awesomeapi.com.br/json/${cep}`); return await response.json(); } async function consultarDistancia() { const cepOrigem = document.getElementById("cep1").value.trim(); const cepDestino = document.getElementById("cep2").value.trim(); try { const origem = await consultarCep(cepOrigem); const destino = await consultarCep(cepDestino); if (origem.lat && origem.lng && destino.lat && destino.lng) { const distancia = haversine(+origem.lat, +origem.lng, +destino.lat, +destino.lng); document.getElementById("resultado").innerHTML = `Distância aproximada: ${distancia.toFixed(2)} km`; } else { document.getElementById("resultado").innerText = "Coordenadas não disponíveis para um dos CEPs."; } } catch (erro) { document.getElementById("resultado").innerText = "Erro ao consultar os CEPs."; console.error(erro); } } function haversine(lat1, lon1, lat2, lon2) { const R = 6371; // Raio da Terra em km 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; const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return R * c; } </script> </body> </html>