Geolocation Example
by Alex Azuero
HTML
<h1>Geolocation Example</h1>
<div id="controls">
<button onclick="loc.getLocation()">Get/Update my location</button>
</div>
<h2>Your Location</h2>
<div id="locdetails">
<label>Latitude:</label>
<input type="text" id="mylat" />
<label>Longitude:</label>
<input type="text" id="mylon" />
<button onclick="loc.updateCoords()">Update Coordinates</button>
</div>
<div id="mymap"></div>
<button onclick="loc.showOnMap('mymap')">Show me my location on a map</button>
CSS
body {
font-family: sans-serif;
padding: 10px;
}
h1 {
font-weight: bold;
}
h2 {
margin: 10px 0 0 10px;
}
label {
font-size: small;
}
#controls {
padding-bottom: 5px;
border-bottom: 1px solid #000;
}
#controls, #locdetails {
margin: 10px;
}
#mymap {
height: 300px;
width: 400px;
margin: 10px;
border: 2px solid #000;
}
JavaScript
//Location object constructor
function Location() {
//Private Instance Variables, can only be accessed or modified from within the object
var myCoords = {
lat: "",
lon: ""
},
self = this;
//PRIVATE FUNCTIONS/METHODS
//This function is private and can only be called from within the scope of the object, it is passed a location object as its only parameter
//this location object is used to update the object instance's stored latitude and longitude
var setLocation = function(position) {
myCoords.lat = position.coords.latitude;
myCoords.lon = position.coords.longitude;
//Update the lat and lon form fields with the users location
self.updateFields(myCoords.lat, myCoords.lon);
};
//This function is also private and can only be called from within the scope of the object, it is called if the users location could not be ascertained by the Geolocation API, it is passed an error object as its only parameter
var locationError = function(error) {
//Examine the error object to determine its type, display an appropriate error message to the user
switch (error.code) {
case error.PERMISSION_DENIED:
alert("Request for Geolocation denied by the user.");
break;
case error.POSITION_UNAVAILABLE:
alert("Your location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get your location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
};
//PUBLIC FUNCTIONS/METHODS
//This function makes the request to the Geolocation API to determine the user's location
this.getLocation = function() {
//Check for support for the Geolocation API in the user's browser
if (navigator.geolocation) {
//Display a confirmation dialog to the user...