HTML and CSS Reference
In-Depth Information
if (navigator.geolocation) {
// geolocation is supported.
The navigator object contains information about the browser such as its version number and the browser
vendor. Browsers that support the GeoLocation API will have a geolocation property on this navigator object.
If you wanted you could also add an else statement here that displays a message to the user informing him that his
browser does not support geolocation and therefore your application may not function correctly. However, for the
Locations page, you are going to stick with a simple if statement. Users who have browsers that don't support geo-
location will still be able to use the page; they will just have to figure out the nearest restaurant on their own.
Once you have determined that the user's browser supports geolocation, you can request his location using the
getCurrentPosition() function.
navigator.geolocation.getCurrentPosition(function(position) {
// Do something with the location data
As you can see, getCurrentPosition() takes a function (this is similar to how event listeners work). In the ex-
ample, a GeoPosition object will be passed into the function you create through the position variable. You
can then obtain the user's latitude and longitude coordinates by examining this GeoPosition object.
To get the latitude coordinate, you need to first select the coords property and then the latitude property, as I
have done here:
The same goes for obtaining the longitude coordinate:
Now let's put this all together. Time to add some JavaScript code that will get the user's location.
The code for this exercise can be found in folder 2.
Here are the steps:
1. Open the geolocation.js file in your text editor.
2. Add an empty function block that will execute when the window.onload event is fired.
Search WWH ::

Custom Search