In this tutorial you will learn more HTML and look at using the geolocation API. This will allow you to write a simple HTML site that you can then view in a web browser of your choice
About this Tutorial
Objectives
Delegates will learn to develop applications using HTML5/CSS3 and JS. After completing this course, delegates will be able to:
Use Visual Studio 2012 effectively
Create commercial HTML5 Web Applications
Develop Websites that may use web sockets, animations and geolocation
Audience
This course has been designed primarily for programmers new to the .Net development platform. Delegates experience solely in Windows application development or earlier versions of HTML/CSS and JavaScript will also find the content beneficial.
Prerequisites
No previous experience in web programming is required. But any experience you do have in programming will help. Also no experience in browser IDE’s is required. But again any experience you do have with programming development environments will be a valuable.
Experience using a contemporary OO language such as C++ or C# would be useful but is not required.
Not what you are looking? Try the next tutorial – Web Storage
Key Concepts
HTML5 is being actively adopted by mobile platforms
The iPhone, Android, Nokia, and Windows Phone 7 are all based on the open-source Webkit browser engine
These phones account for ~65% of smart phones sold
Location awareness is a key feature in many web applications
HTML5’s Geolocation API satisfies this requirement
Checking for Support
You can check whether your browser supports the Geolocation API function testForGeolocationSupport() {
if (navigator.geolocation) {
alert("Your browser supports the Geolocation API.");
}
else {
alert("Sorry pal, your browser doesn't support the Geolocation API.");
}
}
Types of Information Available
The HTML5 Geolocation API supports two types of position request
One-shot position request
Repeated position updates
Typical uses of the Geolocation API:
Locate the user’s current position, and give the user instructions on how to get to a new location
Track a user’s movement (like RunKeeper) to see how far they’ve travelled in a certain time
The HTML5 Geolocation API asks the browser on the underlying device to provide location information
The location is provided as latitude/longitude coordinates
As decimal numbers
Latitude
0 degrees = Equator
+ve = Northern hemisphere
-ve = Southern hemisphere
Longitude
0 degrees = Greenwich Meridian
+ve = East of Greenwich
-ve = West of Greenwich
Additional Geolocation Information
HTML5 Geolocation also provides the accuracy of the location coordinates
Accuracy can vary dramatically, depending on how the underlying device obtained the geolocation info
Additional metadata may also be provided, depending on the underlying device (null if not supported by device)
altitude
altitudeAccuracy
heading
speed
Geolocation Architecture
Lab 1: Sources of geolocation information
Lab 1: Sources of geolocation information
Overview
The HTML5 Geolocation API doesn’t mandate which technology a device must to use to obtain location info
It just exposes an API for retrieving location info
It’s up to the device to choose the best way to retrieve the info
Accuracy can vary greatly, depending on how the device retrieved the info
The following describe the options, and summarise the pros and cons of each approach
IP Address Geolocation Information
This is a rudimentary mechanism, can be wildly inaccurate
The user’s IP address is looked up, and the physical address of the registrant is retrieved
If you have an ISP that provides you with an IP address, your location is often to the physical address of your service provider
Pros:
Available everywhere
Can be useful for localised
advertising in a web site
Cons:
Can be very inaccurate
GPS Geolocation Information
Popular technique with mobile applications
A GPS position is acquired by acquiring from multiple GPS satellites
Pros:
Typically very accurate
Can be useful for localised
advertising in a web site
Cons:
Doesn’t work well indoors
Acquiring a GPS signal can be slow (so GPS lookup is often performed asynchronously)
May require additional hardware
Wi-Fi Geolocation Information
Based on Wi-Fi access points
Determined by triangulating the location based on the user’s distance from a number of known Wi-Fi access points
Mostly used in urban areas
Pro:
Quite accurate
Work indoors
Quick and easy
Cons:
Not good in rural areas (too few Wi-Fi access points)
Mobile Phone Geolocation Information
Based on mobile phone towers
Determined by triangulating the location based on the user’s distance from a number of mobile phone towers
Often used in conjunction with WiFi– and GPS-based geolocation
Pros:
Reasonably accurate
Works indoors
Quick and easy
Cons:
Requires a device with access
to a mobile phone or modem
Not good in rural areas (too few mobile phone towers
User-Defined Geolocation Information
Based on information entered manually by the user
An application can ask the user to enter their address, post code, or some other details
The application can then use that information to provide location-aware services
Pros:
User might be able to supply
more accurate location data
than other methods
User-entry might be faster
than detection
Cons:
Can be very inaccurate, especially if the user is on the move
Lab
In this lab, you’ll see how to use the geolocation API to determine the user’s current location as longitude/latitude values. You’ll then see how to use this information in conjunction with the Google Maps API, to display the user’s location on a map in the browser window.
The download is located at the top of the page and inside is a final and initial folder. The initial folder is what you will be using and the final folder you can refer to if stuck.
Getting geolocation information
In the initial folder, open UsingGoogleMaps.html in a text editor. The page contains a <div> named mapContainer, which will eventually display a map (obtained via the Google Maps API).
The first step is to obtain geolocation information. Follow these steps:
In the init() function, test whether the browser supports geolocation. If it does, call the geolocation getCurrentPosition() function to get geolocation information. if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition()
else {
....
Write a callback function to receive the geolocation information. In this function, display the current longitude and latitude values in an alert box for now. navigator.geolocation.getCurrentPosition(currentPositionCallback);
You might also want to implement an “error callback” in case the geolocation request fails. alert("Geolocation API is not supported in your browser.");
Open the web page in the browser. As soon as the page opens, the browser should attempt to get geolocation information (it might ask you if you want to allow this request to happen, in which case you should say “yes”). Verify that the application displays meaningful longitude/latitude values.
Lab 2: One-off position requests
Lab 2: One-off position requests
Overview
To make a one-off position request: navigator.geolocation.getCurrentPosition( "params, see below " );
Function callback, called by browser when location data is available
i.e. location retrieval is an asynchronous task why is this so?
Optional parameter:
PositionErrorCallback
Function callback, called by browser is any error occurs
You are strongly advised to handle this eventuality
PositionOptions
Allows you to fine-tune the way data is gathered
Defining a Position Callback Function
As soon as the browser has geolocation data available, it calls your position callback function
The functionreceives an object that provides the geolocation data function myPositionCallbackFunction(geolocationData) {
...
}
Main properties on the geolocation data object:
latitude
longitude
accuracy (in metres)
Additional properties that might be available:
altitude (in metres)
altitudeAccuracy (in metres)
heading (direction of travel, in degrees relative to N)
speed (ground speed, in m/s)
Defining an Error Callback Function
If an error occurs during a Geolocation API call, the browser calls your error callback function
The function receives an object that has an error code function myPositionErrorCallbackFunction(errorObject) {
...
}
Position error codes:
PositionError.PERMISSION_DENIED
PositionError.POSITION_UNAVAILABLE
PositionError.TIMEOUT
You can observe errors by simply refusing the browser permission to get your position
Specifying Position Options
When you make a call to the Geolocation API, you can specify the following options to fine-tune the lookup
enableHighAccuracy (default is false)
Hint to use the highest accuracy-detection mode
Might not make any difference, or might consume more time / power
timeout (default is infinity)
Maximum time (ms) the browser is allowed to get location data
If data isn’t available in this time, the error callback is called
maximumAge (default is 0ms)
How old location data can be (ms) before browser must try to refresh
You set these options using shorthand object notation: navigator.geolocation.getCurrentPosition(myPositionCallbackFunction,
myPositionErrorCallbackFunction,
{timeout:500, maximumAge:10000} );
Worked Example
Open the demo project in Visual Studio from the solution at the top of the tutorial
Run the app, and click the Get Current Position link
Then click the Get Current Position button
Lab
Displaying a map –
The next step is to display a map showing the user’s current location. The Google Maps API provides a rich programming model for getting map images, based on various coordinate systems.
To use the Google Map API, add a <script> tag to your web page (in the section) to pull in the Google Map API JavaScript file (see the comment in the code for the appropriate URL). <script src="https://maps.google.com/maps/api/js?sensor=false"></script>
Now add the following code in your geolocation callback function, to get a map from Google and to display it in the web page:
Create a new google.maps.LatLng coordinate object. The constructor requires two parameters: latitude and longitude var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
Create a new JavaScript map options object (using the regular JavaScript object syntax, i.e. {}), and set the following properties on the object:
zoom: the zoom factor for the map (specify a value such as 15)
center: the coordinate object you created just now
mapTypeControl: true
navigationControlOptions: an object that configures the navigation icon. Set the object’s style
propertygoogle.maps.NavigationControlStyle.SMALL.
mapTypeId: the map type, e.g. google.maps.MapTypeId.SATELLITE var mapOptions = {
zoom: 17,
center: coords,
mapTypeControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.SATELLITE
};
Create a new google.maps.Map object. The constructor requires two parameters:
The element where you want to display the map specify the mapContainerelement here (note you must pass in the actual element, e.g. as obtained via the document.getElementById() function).
The map options object you just created. var map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions);
That’s it! Just by creating the google.maps.Map object, Google Maps will create a map and display it in the target element you specified. If you refresh the web page in the browser, you should see that it displays your current location in a map.
Lab 3: Repeated position updates
Lab 3: Repeated position updates
Overview
To make a request for repeated location updates: var watchId = navigator.geolocation.watchPosition( "same params as before ");
The Geolocation service will call your position callback function repeatedly, as the position changes
To stop getting position updates: navigator.geolocation.clearWatch(watchId);
Worked Example
Open the demo project in Visual Studio
Run the app, and click the Watch Position link
Then click the Watch Position and Clear Watch buttons
Lab
Adding a marker to indicate the current location
In your geolocation callback function, add code to display a marker on the map to indicate your current location. To do this, you must create a google.maps.Marker object take a look at the Google Maps API documentation online to see what parameters are needed var marker = new google.maps.Marker({
position: coords,
map: map,
title: "Your current location!"
});
You might also want to experiment with other features in the Google Maps API, see the documentation and try them out in your web page.
Well done. You have completed the tutorial in the HTML5/CSS3/JS course. The next tutorial is
If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Manage cookie consent
You can view this website without consenting to extra cookies. However you will need to accept the 'marketing' cookies to send messages via the contact forms & see any maps displayed on the site
Functional
Always active
Cookies necessary for the website to work.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.Cookies used to track user interaction on the site, which helps us to evaluate & improve the website.
Marketing: Forms & additional content (Marketing)
We need your permission to place ‘marketing’ cookies, so you are able to use the contact forms & see embedded content e.g. videos and maps. - - - - We have added protection to our contact forms to help prove that a human (rather than a spambot) is filling
If you would like to see more content like this in the future, please fill-in our quick survey.