Simple geolocation demo using JavaScript
Answering the question: Are you at PBC right now?
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<title>geolocation</title> | |
<script src="http://maps.google.com/maps/api/js?sensor=true"></script> | |
<style> | |
body { | |
margin: 0; | |
padding: 0; | |
} | |
#map { | |
width: 960px; | |
height: 450px; | |
} | |
</style> | |
</head> | |
<body> | |
<noscript> | |
<h2><noscript>This app won't work for you.</h2> | |
<h4>To fix the problem, please enable JavaScript in your browser (in content settings, preferences or something similar).</h4> | |
</noscript> | |
<div id="map"></div> | |
<div id="caption"></div> | |
<script> | |
var lon = -77.0703, lat = 38.9043; // Lat & Lon of PBC | |
var caption = document.getElementById("caption"); | |
// Create the Google Map | |
var map = new google.maps.Map(document.getElementById("map"), { | |
zoom: 11, | |
center: new google.maps.LatLng(lat, lon), | |
mapTypeId: google.maps.MapTypeId.TERRAIN | |
}); | |
// Plot PBC on the map | |
var marker = new google.maps.Marker({ | |
position: new google.maps.LatLng(lat,lon), | |
map: map, | |
title: "PBC" | |
}); | |
// Geolocate and plot the browser location | |
caption.innerHTML = "<h2> Trying to find you. Just a second...</h2>"; | |
getLocation(); | |
function getLocation() { | |
if (navigator.geolocation) { | |
navigator.geolocation.getCurrentPosition(geo_success, geo_error, geo_options); | |
} else { | |
caption.innerHTML = "Your browser does not support geolocation."; | |
} | |
} | |
function geo_error() { | |
caption.innerHTML = "<h2> Please allow this app to track your location." | |
+ " Check your browser settings and try again.</h2>"; | |
} | |
var geo_options = { | |
timeout: 15000 | |
}; | |
function geo_success(position) { | |
var myLat = position.coords.latitude, | |
myLon = position.coords.longitude, | |
distance = planarDistanceFromPBC(myLon, myLat); | |
console.log("Lat: " + myLat + ", Lon: " + myLon); | |
myLat = Math.round( myLat*10000 )/10000; | |
myLon = Math.round( myLon*10000 )/10000; | |
if (distance < 1000) { | |
caption.innerHTML = "<h2> You're about " + distance | |
+ " meters from PBC at Lat = " + myLat + ", Lon = " + myLon +"</h2>"; | |
} else { | |
caption.innerHTML = "<h2> You're about " + Math.round( distance/100 )/10 | |
+ " Km from PBC at Lat = " + myLat + ", Lon = " + myLon +"</h2>"; | |
} | |
var marker = new google.maps.Marker({ | |
position: new google.maps.LatLng(myLat,myLon), | |
map: map, | |
title: "You" | |
}); | |
} | |
function planarDistanceFromPBC(myLon, myLat) { | |
dLon = myLon - lon; | |
dLat = myLat - lat; | |
return Math.round( 3.14159*Math.sqrt(dLon*dLon + dLat*dLat)*6371000/180 ); // Distance in meters | |
} | |
</script> | |
</body> | |
</html> |