HTML Geolocation
Antes, Web Storage recordaba cadenas clave/valor. Esta lección deja de guardar y presenta Geolocation: leer latitud/longitud aproximadas con navigator.geolocation — solo tras permiso. HTML carga un script que pide ubicación. Alcance práctico — lectura única, watch/clear y rechazo educado — no SDK de mapas ni geo BD.
Por qué geolocation en un curso HTML
Los principiantes suelen hacer un botón «cerca de mí». Geolocation es la primera API habitual. Tras web storage, la división es otra: HTML posee la cáscara y el botón; JS pide coordenadas. Bastan getCurrentPosition, conocer watchPosition y manejar el rechazo.
Respuesta directa
1) Llama getCurrentPosition. 2) Lee latitude/longitude. 3) Mejor tras un clic del usuario. 4) watchPosition solo para actualizaciones; clearWatch. 5) Ninguna etiqueta HTML. 6) Si niegan, mantén la página útil.
📊 getCurrentPosition vs watchPosition
| Topic | getCurrentPosition | watchPosition |
|---|---|---|
| Typical use | One-shot “where am I now” | Ongoing updates while watching |
| Callback pattern | success once (plus optional error) | success may fire repeatedly |
| Stop watching | Not needed (single read) | clearWatch(watchId) |
| Beginner fit | Share-location button | Live tracking demos (careful) |
| Permission | Still required | Still required |
| This course depth | Intro focus | Short demo + clearWatch only |
Mini demo getCurrentPosition
Un clic pide la posición e imprime coordenadas. Si falta la API o se niega, mensaje calmado.
<button id="loc" type="button">Share location</button>
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
document.getElementById("loc").onclick = function () {
if (!navigator.geolocation) {
out.textContent = "No geolocation support";
return;
}
out.textContent = "Waiting for permission…";
navigator.geolocation.getCurrentPosition(
function (pos) {
out.textContent =
pos.coords.latitude + ", " + pos.coords.longitude;
},
function () {
out.textContent = "Permission denied or unavailable";
}
);
};
</script>
Leer las llamadas getCurrentPosition
- navigator.geolocation es el punto de entrada
- getCurrentPosition pregunta una vez
- latitude/longitude son los números iniciales
- Detecta soporte primero
- El error cubre el rechazo
- Prefiere HTTPS
- A diferencia de Web Storage: lees, no guardas
watchPosition para actualizaciones continuas
El éxito puede dispararse al moverse. Guarda el id y usa clearWatch — no dejes watches eternos en la intro.
<button id="start" type="button">Watch location</button>
<button id="stop" type="button">Stop watching</button>
<pre id="live"></pre>
<script>
const live = document.getElementById("live");
let watchId = null;
document.getElementById("start").onclick = function () {
if (!navigator.geolocation) {
live.textContent = "No geolocation support";
return;
}
if (watchId !== null) {
return;
}
live.textContent = "Watching…";
watchId = navigator.geolocation.watchPosition(
function (pos) {
live.textContent =
pos.coords.latitude + ", " + pos.coords.longitude;
},
function () {
live.textContent = "Permission denied or unavailable";
watchId = null;
}
);
};
document.getElementById("stop").onclick = function () {
if (watchId !== null) {
navigator.geolocation.clearWatch(watchId);
watchId = null;
live.textContent = "Stopped watching";
}
};
</script>
Leer la idea watchPosition
- Mismo modelo de permiso
- El éxito puede repetirse
- clearWatch detiene — ofrece Stop
- No es una librería de mapas
- No es Web Storage
- Elige get vs watch por frecuencia
- Siguiente: drag and drop
Cuándo preguntar
- Clic en «Compartir ubicación»: buen momento
- Al cargar sin contexto: suele ser malo
- Movimiento continuo: watchPosition con parada
- Guardar tema: fue Web Storage
- Producto de mapas completo: fuera de esta intro
- Seguimiento silencioso: antipatrón
Práctica — pide un fix con cortesía
- Pega la demo getCurrentPosition y prueba el permiso.
- Confirma coordenadas o mensaje calmado.
- Prueba watch y luego Stop.
- Opcional: niega sin romper la página.
- Frase: Web Storage guarda cadenas; Geolocation lee con permiso.
- Sirve por http(s) si hace falta.
- Vista previa: drag and drop.
Errores fáciles
- Esperar una etiqueta geolocation
- Preguntar en cada carga
- Ignorar el callback de error
- Confundir con Web Storage
- Dejar watch sin clearWatch
- Asumir GPS preciso siempre
- Tomar la intro como curso de mapas
Resumen
- Geolocation es una API JS con permiso en navigator.geolocation
- getCurrentPosition una vez; watchPosition + clearWatch para actualizaciones
- HTML da la UI; pregunta tras una acción clara
- Gestiona el rechazo con amabilidad
- Web Storage eran cadenas; esta lección coordenadas permitidas
- Siguiente: drag and drop en HTML
🧠 Pon a Prueba tu Conocimiento
Pon a Prueba tu Conocimiento
Ponte a prueba con este cuestionario interactivo y descubre qué tan bien entiendes el tema
📝 Instrucciones
- Lee cada pregunta cuidadosamente
- Selecciona la mejor respuesta para cada pregunta
- Puedes repetir el quiz tantas veces como quieras
- Tu progreso se mostrará en la parte superior