<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>xxx</title>
<script>
function getLocation() {
if (navigator.geolocation) {
var positionOptions = {
timeout : Infinity,
maximumAge : 0,
enableHighAccuracy : true
}
navigator.geolocation.getCurrentPosition(getPosition, catchError, positionOptions);
// watchID = navigator.geolocation.watchPosition(getPosition, catchError, positionOptions);
}
else {
alert("Tu navegador no soporta la geolocalización");
}
}
function getPosition(position) {
document.getElementById("location").innerHTML =
"Latitud: " + position.coords.latitude + "<br>" +
"Longitud: " + position.coords.longitude;
}
function catchError(positionError) {
switch(positionError.code) {
case positionError.TIMEOUT:
alert("La respuesta para obtener la localizacion ha sido abortada porque ha tardado mucho tiempo");
break;
case positionError.POSITION_UNAVAILABLE:
alert("La información de la localizacion no esta disponible");
break;
case positionError.PERMISSION_DENIED:
alert("Permiso para compartir la informacion de localizacion ha sido denegado. Seguramente tengas desactivada ubicacion en tu movil");
break;
default:
alert("Error desconocido ha ocurrido");
}
}
</script>
</head>
<body>
<button onclick="getLocation()">Pulsar para localizar</button>
<p id="location"></p>
</body>
</html>
Mostrar el resultado de la posición en Google Maps:
Solo habría que cambiar:
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
function showPosition(position) {
lat = position.coords.latitude;
lon = position.coords.longitude;
latlon = new google.maps.LatLng(lat, lon)
mapholder = document.getElementById('zona_mostrar')
mapholder.style.height = '250px';
mapholder.style.width = '500px';
var myOptions = {
center:latlon,zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP,
mapTypeControl:false,
navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}
}
var map = new google.maps.Map(document.getElementById("zona_mostrar"), myOptions);
var marker = new google.maps.Marker({position:latlon,map:map,title:"You are here!"});
}
Uso en dispositivos en movimiento
Para dispositivos en movimiento (como un móvil o el GPS de un coche) es prácticamente igual solo que se utiliza watchPosition en vez de getCurrentPosition.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";}
}
function showPosition(position) {
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
---------------------------------------------------------------------------------------------Más información: http://www.w3schools.com/html/html5_geolocation.asp
