Thursday, April 19, 2012

HTML5 Geolocation

Demo              Download

[sourcecode language="javascript"]
<!DOCTYPE html>
<html>
<head>

<script src="<a href="view-source:http://maps.googleapis.com/maps/api/js?sensor=false">http://maps.googleapis.com/maps/api/js?sensor=false</a>"></script>
<script>
// Integration with google maps
function loadMap(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);

var settings = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

var map = new google.maps.Map(document.getElementById('map_canvas'), settings);

var marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'Your Position!'
});

document.getElementById('status').innerHTML = 'Position Found!';
}

// Initialize geolocation
function initialize() {
if (navigator.geolocation) {
document.getElementById('status').innerHTML = 'Checking...';

navigator.geolocation.getCurrentPosition(
onSuccess,
onError, {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 120000
});
}
else {
document.getElementById('status').innerHTML = 'Geolocation not supported.';
}
}

// Map position retrieved successfully
function onSuccess(position) {
var data = '';

data += 'latitude: ' + position.coords.latitude + '<br/>';
data += 'longitude: ' + position.coords.longitude + '<br/>';
data += 'altitude: ' + position.coords.altitude + '<br/>';
data += 'accuracy: ' + position.coords.accuracy + '<br/>';
data += 'altitudeAccuracy: ' + position.coords.altitudeAccuracy + '<br/>';
data += 'heading: ' + position.coords.heading + '<br/>';
data += 'speed: ' + position.coords.speed + '<br/>';

document.getElementById('data').innerHTML = data;

loadMap(position.coords.latitude, position.coords.longitude);
}

// Error handler
function onError(err) {
var message;

switch (err.code) {
case 0:
message = 'Unknown error: ' + err.message;
break;
case 1:
message = 'You denied permission to retrieve a position.';
break;
case 2:
message = 'The browser was unable to determine a position: ' + error.message;
break;
case 3:
message = 'The browser timed out before retrieving the position.';
break;
}

document.getElementById('status').innerHTML = message;
}
</script>
</head>
<body onload="<a>initialize()</a>">
<div id="<a>status</a>"></div>
<div id="<a>data</a>"></div>
<div id="<a>map_canvas</a>" style="<a>width: 640px; height: 480px</a>"></div>
</body>
</html>

[/sourcecode]

1 comment:

  1. This is so awesome.

    I would like to change the layout so the map is at the top and coordinates are underneath, does anyone know how to do this as I have tried moving loadMap(position.coords.latitude, position.coords.longitude) but the screen remains blank. I have also tried moving document.getElementById('data').innerHTML = data; but doesn't work either.

    ReplyDelete

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...