Last active
December 28, 2015 06:48
-
-
Save webapprentice/7459169 to your computer and use it in GitHub Desktop.
Simple example of using geolocation in HTML5
This file contains 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
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDPlbegz3bhu9AnJDCLWsOZM8jF3Hpp8tI&sensor=false"></script> | |
<script> | |
$(document).ready(function() { | |
if(navigator.geolocation) { | |
navigator.geolocation.getCurrentPosition(function(position) { | |
var str = 'Latitude: ' + position.coords.latitude.toString() + ' deg<br>' + | |
'Longitude: ' + position.coords.longitude.toString() + ' deg<br>'; | |
str += "Accuracy: " + position.coords.accuracy.toString() + ' meters<br>'; | |
if(position.coords.altitude) { | |
str += "Altitude: " + position.coords.altitude.toString() + ' meters<br>' + | |
"Altitude Accuracy: " + position.coords.altitudeAccuracy.toString() + ' meters<br>'; | |
} else { | |
str += "Altitude: undefined<br>" ; | |
} | |
str += "Heading: " + (position.coords.heading ? position.coords.heading.toString() + ' deg<br>' : 'undefined<br>'); | |
str += "Speed: " + (position.coords.speed ? position.coords.speed.toString() + ' m/s<br>' : 'undefined<br>'); | |
var d = new Date(position.timestamp); | |
str += " <br>Timestamp " + d.toLocaleTimeString() + ' ' + d.toLocaleDateString(); | |
$('#coordinates').html(str); | |
drawMap(position.coords.latitude, position.coords.longitude); | |
}, function() { | |
$('#coordinates').html('Error: The Geolocation service failed.'); | |
}); | |
} else { | |
$('#coordinates').html('Error: Your browser does not support Geolocation.'); | |
} | |
}); | |
function drawMap(latitude, longitude) { | |
var pos = new google.maps.LatLng(latitude, longitude); | |
var mapOptions = { | |
zoom: 16, | |
center: pos, | |
mapTypeId: google.maps.MapTypeId.ROADMAP | |
}; | |
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions); | |
var marker = new google.maps.Marker({ | |
position: pos, | |
map: map, | |
title: 'You are here' | |
}); | |
} | |
</script> | |
<style> | |
#map_canvas { | |
width: 300px; | |
height: 300px; | |
} | |
</style> | |
<div id='coordinates'></div> | |
<br> | |
<div id='map_canvas'></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment