Google maps API
by thakkar
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Where am I?</title>
<script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript"></script>
</head>
<body>
<div id="location">
Your location will go here.
</div>
<div id="distance">
Distance from WickedlySmart HQ will go here.
</div>
<div id="map">
</div>
</body>
</html>
CSS
/*
* myLoc.css
*
*/
body {
font-family: Arial, Helvetica, sans-serif;
margin: 10px;
}
form, div#location, div#distance {
padding: 5px;
}
div#map {
margin: 5px;
width: 400px;
height: 400px;
border: 1px solid black;
}
/*
* Use this CSS to make the map full screen
*
html, body, div#map {
width: 100%;
height: 100%;
margin: 0px;
}
form {
position: absolute;
top: 40px;
right: 10px;
z-index: 2;
}
div#location, div#distance {
display: none;
}
*/
JavaScript
window.onload = getMyLocation;
function getMyLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation, displayError);
} else {
alert("oops, no geolocation support");
}
}
function displayLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var div = document.getElementById("location");
div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
var km = computeDistance(position.coords, ourCoords);
var distance = document.getElementById("distance");
distance.innerHTML = "You are " + km + " km from the WickedlySmart HQ";
showMap(position.coords);
}
function showMap(coords) {
var googleLatAndLong = new google.maps.LatLng(coords.latitude, coords.longitude);
var mapOptions = {
zoom: 10,
center: googleLatAndLong,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mapDiv = document.getElementById("map");
map = new google.maps.Map(mapDiv, mapOptions);
}
function displayError(error) {
var errorTypes = {
0: "Unknown error",
1: "Permission denied by user",
2: "Position is not available",
3: "Request timed out"
};
var errorMessage = errorTypes[error.code];
// in the case of errors zero or two, there is sometimes additional information in the error.message property
if (error.code == 0 || error.code == 2) {
errorMessage = errorMessage + " " + error.message;
}
var div = document.getElementById("location");
div.innerHTML = errorMessage;
}
var ourCoords = {
latitude: 47.624851,
longitude: -122.52099
};
/************************************* calculate distance functions *******************/
function computeDistance(startCoords, destCoords) {
var startLatRads = degreesToRadians(startCoords.latitude);
var startLongRads = degreesToRadians(startCoords.longitude);
var...