Forked from strongwave/watchPosition_demo.html
Last active
November 21, 2015 20:29
-
-
Save UlisesGascon/db903fd3b2e79f06b086 to your computer and use it in GitHub Desktop.
A Demo Drawing Google Map using watchPosition API for HTML5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="es"> | |
<head> | |
<title>Geo_Watch</title> | |
<meta charset=utf-8> | |
<style> | |
#mapa { | |
width: 400px; | |
height: 300px; | |
margin-top: 10px; | |
margin-bottom: 120px; | |
} | |
</style> | |
</head> | |
<body> | |
<div> | |
<div id="botones"> | |
<button id="watchPositionBtn">Sigueme!</button> | |
<button id="stopWatchBtn">Deja de seguirme</button> | |
</div> | |
<div id="mapa"></div> | |
<div id="datos"></div> | |
</div> | |
<script type='text/javascript' src="http://maps.googleapis.com/maps/api/js?sensor=false&extension=.js&output=embed"></script> | |
<script> | |
// Variables | |
var watchProcess = null; | |
var debugMode = true; | |
var opciones = { | |
enableHighAccuracy: true | |
}; | |
// Funciones | |
function initiate_watchlocation() { | |
if (watchProcess === null) { | |
watchProcess = navigator.geolocation.watchPosition(handle_geolocation_query, handle_errors, opciones); | |
if (debugMode) { | |
console.info("Proceso Iniciado!"); | |
} | |
} else { | |
if (debugMode) { | |
console.warn("ERROR: Proceso Iniciado previamente!"); | |
} | |
} | |
} | |
function stop_watchlocation() { | |
if (watchProcess !== null) { | |
navigator.geolocation.clearWatch(watchProcess); | |
watchProcess = null; | |
if (debugMode) { | |
console.warn("Proceso Detenido!"); | |
} | |
} | |
} | |
function handle_errors(error) { | |
switch (error.code) { | |
case error.PERMISSION_DENIED: | |
alert("El usuario no desea compartir los datos relativos a la geolocalización"); | |
break; | |
case error.POSITION_UNAVAILABLE: | |
alert("No se ha podido detectar la posición actual"); | |
break; | |
case error.TIMEOUT: | |
alert("No se ha podido resolver la posición en el tiempo esperado."); | |
break; | |
default: | |
alert("Error desconocido"); | |
break; | |
} | |
} | |
function handle_geolocation_query(position) { | |
var latitudAlternativa = dec2gms(position.coords.latitude, "latitud"); | |
var longitudAlternativa = dec2gms(position.coords.longitude, "longitud"); | |
var text = "<b>Latitud: </b>" + position.coords.latitude.toFixed(4) + "<br/>"; | |
text += "<b>Longitud: </b>" + position.coords.longitude.toFixed(4) + "<br/>"; | |
text += "<b>Precisión (m): </b>" + position.coords.accuracy + "<br/>"; | |
if (position.coords.altitude && position.coords.altitude !== null) { | |
text += "<b>Altitud: </b>" + position.coords.altitude.toFixed(2) + " - Precisión (" + position.coords.altitudeAccuracy.toFixed(2) + "m) <br/>"; | |
} | |
if (position.coords.heading && position.coords.heading !== null) { | |
text += "<b>Rumbo: </b>" + position.coords.heading + "<br/>"; | |
} | |
text += "<b>Posición: </b>" + latitudAlternativa.valor + ", " + longitudAlternativa.valor + "<br/>"; | |
if (position.coords.speed && position.coords.speed !== null) { | |
text += "<b>Velocidad: </b>" + position.coords.speed + "<br/>"; | |
} | |
text += "<b>Última Conexión: </b>" + new Date(position.timestamp).toLocaleTimeString(); | |
var image_url = "http://maps.google.com/maps/api/staticmap?maptype=satellite&sensor=false&zoom=18¢er=" + position.coords.latitude + ',' + position.coords.longitude + | |
"&zoom=14&size=300x400&markers=color:red|label:Tú|" + position.coords.latitude + ',' + position.coords.longitude; | |
document.querySelector("#mapa").innerHTML = "<img src='" + image_url + "' alt='Tu posición' />"; | |
document.querySelector("#datos").innerHTML = text; | |
} | |
/** | |
* Convierte una coordenada en formato decimal a su correspondiente | |
* versión en formato grados-minutos-segundos. | |
* | |
* Desarrollado por Jorge Iván Meza Martinez y modificado por Ulises Gascón | |
* Más info en http://blog.jorgeivanmeza.com/2011/06/convertir-coordenadas-geograficas-grados-minutos-segundos-a-notacional-decimal-3/ | |
* | |
* @param {float} valor de Coordenada. | |
* @param {string} tipo de dato - "latitud" o "longitud". | |
* @return {object} - 'grados', 'minutos', 'segundos', 'direccion', 'valor'. | |
*/ | |
function dec2gms(valor, tipo) { | |
var grados = Math.abs(parseInt(valor)); | |
var minutos = (Math.abs(valor) - grados) * 60; | |
var segundos = minutos; | |
minutos = Math.abs(parseInt(minutos)); | |
segundos = Math.round((segundos - minutos) * 60 * 1000000) / 1000000; | |
var signo = (valor < 0) ? -1 : 1; | |
var direccion = (tipo === "latitud") ? ((signo > 0) ? 'N' : 'S') : ((signo > 0) ? 'E' : 'O'); | |
if (isNaN(direccion)) { | |
grados = grados * signo; | |
} | |
return { | |
'grados': grados, | |
'minutos': minutos, | |
'segundos': segundos, | |
'direccion': direccion, | |
'valor': grados + "° " + minutos + "\' " + segundos.toFixed(2) + | |
"\"" + ((isNaN(direccion)) ? (' ' + direccion) : '') | |
}; | |
} | |
if ("geolocation" in navigator) { | |
// Eventos | |
document.querySelector("#watchPositionBtn").addEventListener("click", function() { | |
initiate_watchlocation(); | |
}); | |
document.querySelector("#stopWatchBtn").addEventListener("click", function() { | |
stop_watchlocation(); | |
}); | |
} else { | |
document.body.innerHTML = "<h1>Geolocation no soportado :-( </h1>"; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment