HTML and CSS Reference
In-Depth Information
window.onload = function() {
}
3. Inside this function block, create an if statement that will check to see if the user's browser supports the
GeoLocation API.
window.onload = function() {
// Check to see if the user's browser supports GeoLocation.
if (navigator.geolocation) {
}
}
4. Now call the getCurrentPosition() method on the geolocation object by adding an empty func-
tion block between the parameters of the method call. Note the presence of the position parameter in the
function block below.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
});
}
5. Use the alert() function to display the latitude and longitude coordinates to the user. You will replace
this code later, but for now it is useful for checking that everything is working correctly.
navigator.geolocation.getCurrentPosition(function(position) {
alert(“Latitude: “ + position.coords.latitude + “ “ +
“Longitude: “ + position.coords.longitude);
});
6. Save the geolocation.js file.
How Does GeoLocation Work?
The GeoLocation API is somewhat of a black box from a developer's point of view. You can easily request a user's
location using the getCurrentPosition() method, but how does the device know where it is?
For devices like mobile phones, the answer is fairly intuitive. If the device has GPS, the browser can get the loca-
tion data from the GPS receiver. However, not all devices have built-in GPS.
Devices like desktop and laptop computers can use network information such as Wi-Fi triangulation to make a
guess at where they are in the physical world. This is not as accurate as the data obtained using GPS, but it will
generally return a fairly accurate location. Using network information is also a good backup when the device is in
an area where obtaining a good GPS signal can be difficult, such as indoors or in built-up areas. The IP address of
a device may also be used to determine its location, but this is notoriously inaccurate and will often return only the
nearest city.
You don't need to worry too much about the specifics of how the GeoLocation API obtains the location data you will
be using. Just be aware that the accuracy of this data can vary depending on the type of device being used.
Search WWH ::




Custom Search