Ian Devlin – HTML5 Doctor http://html5doctor.com helping you implement HTML5 today Wed, 27 Apr 2016 12:02:21 +0000 en-US hourly 1 The woes of date input https://stevefaulkner.github.io/html5doctored/the-woes-of-date-input/ https://stevefaulkner.github.io/html5doctored/the-woes-of-date-input/#comments Tue, 19 Jan 2016 14:39:31 +0000 http://html5doctor.com/?p=5961

Related Posts:

]]>
One of the many new input types that HTML5 introduced is the date input type which, in theory, should allow a developer to provide the user with a simple, usable, recognisable method of entering a date on a web page. But sadly, this input type has yet to reach its full potential.

Briefly, the date input type is a form element that allows the capture of a date from a user, usually via a datepicker. The implementation of this datepicker is up to the browser vendor, as the HTML5 specification does not tell vendors how to implement the input’s UI.

The input itself can of course be used without using any of its available attributes:

<label for="when">Date:</label>
<input id="when" name="when" type="date">

Or you can specify minimum and maximum date values via the min and max attributes, ensuring that a user can only choose dates within a specific range:

<label for="when">Date:</label>
<input id="when" name="when" type="date" min="2016-01-01" max="2016-12-01">

You can also use the step attribute to specify, in days, how a date can increment. The default is 1.

This of course is the theory and a fine reality it would be, if it were so but alas it is not.

Features

Rather than talk about browser support for the date input type, I will instead talk about the various features that are part of this input type:

The input field

Neither Firefox nor Safari support this input type; it is treated as a simple text field with no formatting and no special interaction.

Microsoft Edge has no special interactions and in fact the input field appears to be read-only.

Chrome and Opera have the same implementations which display a date placeholder (or date value if the input’s value attribute has been set) using the user’s system settings’ date format. There are also some controls that allow the user to clear the input field, some arrows to cycle up and down between values, and an arrow that will open a datepicker (see Figure 1). There are some WebKit prefixed pseudo selectors available that allow you to change the appearance of the various bits within the input date field.

Screenshot of WebKit's native date input on Chrome

Figure 1. – WebKit’s date input field as seen on Chrome

The min and max attributes

All of those browsers that support the date input type also support the min and max attributes.

Chrome and Opera both work fine if both the min and max attributes are set, but the UI is poor when only one of them is set. In these browsers, the date input displays up and down arrows for the user to change each value (day, month, and year). If a date input has a minimum value set at today’s date, then if the user highlights the year and then clicks the down arrow, the year will change to 275760 as the arrows cycle between the valid values and, since no maximum has been set, the default maximum is used (see Figure 2). This has been reported as a bug but has been marked as “won’t fix” as apparently it is the desired behaviour, I disagree.

Screenshot of WebKit's native date input on Chrome showing the year cycling to 275760

Figure 2. – WebKit’s buggy date input field with a min value set but no max

Something similar happens when only a max value is set in that pressing the up arrow will cycle around to the year 0001, which is the default minimum. Again this leads to a very confusing UX for the user, so please use both min and max where possible.

With Android, the setting of these attributes can cause some weird quirks with the datepicker.

The step attribute

None of the browsers tested support the step attribute.

The datepicker

Firefox and Safari do not support the date input type and therefore do not open a datepicker on desktop. But they do open a device’s native datepicker on mobile devices when the date input field receives focus.

Microsoft Edge opens a datepicker, but its UI is very poor (see Figure 3).

Screenshot of the the Edge's datepicker, which displays a list of selectable dates with one highlighted and two buttons at the bottom, once with a tick and the other with an X

Figure 3. – Microsoft Edge’s native datepicker

Chrome and Opera open a fairly decent datepicker on desktop but you cannot style it at all. It looks how it looks (see Figure 4), and there’s nothing that you can do about it, no matter what your designer says. With these browsers you can disable the native datepicker if you want and implement your own, but this will not work with mobile devices. This gives you the best of both worlds: you can implement a nicer datepicker for desktop and let a device use its own native datepicker.

Screenshot of WebKit's native datepicker and date input on Chrome

Figure 4. – WebKit’s native datepicker and date input field as seen on Chrome

All the native datepickers that I tested on Android displayed some sort of confusing display quirks when valid min and max attribute are set. A user is correctly restricted from selecting a date outside of the specified range, but the visual datepickers often display “previous”, “current”, and “next” values for day, month, and year, and the values displayed for “previous” are either empty (in the case of the month) or set to 9999 (in the case of the year, see Figure 5).

Screenshot of the native datepicker on Android 4.3, with a selected date and the previous year set to 9999

Figure 5. – The native datepicker on Android 4.3

Events

Like most of the other input fields, the date input supports the input and changed events. The input event is fired every time a user interacts with the input field, while the change event is usually only fired when the value is committed, i.e. the input field loses focus.

For those browsers mentioned above that support the native date input field, no specific events are fired that will allow you to determine if the user has done anything “date specific” such as opened or closed the datepicker, or cleared the input field. You can work out if the field has been cleared by listening for the input or change events and then checking the input field’s value.

If you have an event listener set up for the change event and one for the input event, changed will never actually fire as input takes precendence.

Conclusion

So, what can we deduce from all this? Should we use the input date type or not? And as usual the answer is “it depends” as only you know what you’re building and how and where it will be used, so it might fit perfectly for your needs or it might not.

I think in general it’s safe to use the input date type on occasions where a min and max does not need to be set as the quirks when these attributes are used are too irritating to ignore. Since not all browsers support a datepicker and you will have to get one from somewhere else to support these browsers, I would also recommend turning off the datepicker for all desktop browsers (using the method linked to above) as this will still allow devices to use their own.

Have fun!

The woes of date input originally appeared on HTML5 Doctor on January 19, 2016.

]]>
https://stevefaulkner.github.io/html5doctored/the-woes-of-date-input/feed/ 11
The progress element https://stevefaulkner.github.io/html5doctored/the-progress-element/ https://stevefaulkner.github.io/html5doctored/the-progress-element/#comments Tue, 12 Feb 2013 14:30:16 +0000 http://html5doctor.com/?p=4927

Related Posts:

]]>
When building web sites and web applications, we often need to provide essential feedback to a user informing them of the progress of their request or task, be it uploading a file, playing a video, or importing data.

HTML5 makes life easier for us by defining an element whose sole purpose is just that: the <progress> element.

The HTML5 specification describes it best:

The progress element represents the completion progress of a task.

The task itself is irrelevant, but displaying its progress is not.

Attributes

There are four attributes that are specified for the <progress> element: max, value, position, and labels. Before taking a look at each of theses attributes in turn, here are a few important notes on them:

  • If the value attribute exists, then the progress bar is considered to be determinate (i.e., it has exact limits). Otherwise it is considered to be indeterminate.
  • If the max attribute is not included, the default acceptable range for the progress bar is between 0.0 and 1.0 inclusive.
  • Authors are encouraged always to include the current value and the maximum value (if used) as inline text to the <progress> element so that the information is still visible to users of legacy browsers.

And now let’s take a closer look at the attributes themselves:

Max
The max attribute is a floating point number that indicates how much work the relevant task requires in total before it can be considered complete. The default value is 1.0.
Value
This is a floating point number that represents the current progress of the relevant task. Its value must be greater than or equal to 0.0 and less than or equal to 1.0 or the value of the max attribute if present.
Position
This is a read-only attribute that returns the current position of the <progress> element. This value is equal to value / max for a determinate progress bar and -1 for an indeterminate progress bar (as the position can’t accurately be determined).
Labels
This is also a read-only attribute that returns a list of the <progress> element’s labels (if there are any).

Examples

Let’s now take a look at some examples of how the <progress> element might be used, including how it might be updated via JavaScript.

Simple Indeterminate Progress Bar

<progress id='p'></progress>

Since we have no idea how long the task in hand will take, the browser will simply display the progress bar until the task is complete and we either hide it or replace it with a ‘task complete’ message.

Simple Determinate Progress Bar

<progress id='p' max='70'><span>0</span>%</progress>

And the JavaScript for updating it:

var pBar = document.getElementById('p');
var updateProgress = function(value) {
  pBar.value = value;
  pBar.getElementsByTagName('span')[0].innerHTML = Math.floor((100 / 70) * value);
}

Note that here the progress bar can have a maximum value of 70, so calls to updateProgress will have values between 0 and 70 and that the value is also displayed within the <progress> element so that it is visible as a simple percentage string for users of legacy browsers.

Using <progress> with HTML5 Video

A good example of using the <progress> element is with an HTML5 video, informing the user how much of the video has been played. This won’t be a full example but will just show the necessary HTML and JavaScript.

Given a <video> element with an id of ‘v’:

<progress id='p' max='100' value='0'><span>0</span>% played</progress>

Use this JavaScript:

var video = document.getElementById('v');
var pBar = document.getElementById('p');
video.addEventListener('timeupdate', function() {
  var percent = Math.floor((100 / video.duration) * video.currentTime);
  pBar.value = percent;
  pBar.getElementsByTagName('span')[0].innerHTML = percent;
}, false);

The JavaScript uses the timeupdate event, which is constantly triggered as the video is being played. The value is converted into a percentage value using the video’s duration (full length) and currentTime (where in the video it currently is).

Using <progress> with the File API

Another useful example is how the <progress> element might be used with the File API. Again, this is not a complete example, assuming the existence of a file input and upload button and <progress> element, and code for reading the file. The specification itself has some good code examples of this.

var p = document.getElementById('p');
// 'reader' is of type FileReader
reader.addEventListener('loadstart', function(evt) {
  if (evt.lengthComputable) p.max = evt.total;
}, false);
reader.addEventListener('progress', function(evt) {
  if (evt.lengthComputable) p.value = evt.loaded;
}, false);

Here the loadstart event is used to set the max attribute of the <progress> element, and then the progress event is used to update the <progress> element’s value attribute.

Browser Support

The <progress> element is fairly well-supported in today’s major browsers, although only in version 6+ of Safari (so not on Windows, as the last version there was 5.1) and only in version 10+ of Internet Explorer.

Styling

As is usual with such elements, browsers have their own unique styling for the <progress> element. You can, however, override this to a certain extent using simple CSS.

The default styling tends to consist of an element with rounded corners, a grey background colour, and a green gradient for the actual progress marker.

A screenshot of the progress element in Firefox

The default styling for the progress element in Firefox 18.0.2.

Let’s say we want to style our progress bar for the HTML5 Doctor website, so that it fits in with the design. We’ll remove the bevel and the gradients using only solid colours. The code below will almost do that:

progress {
  color: #0063a6;
  font-size: .6em;
  line-height: 1.5em;
  text-indent: .5em;
  width: 15em;
  height: 1.8em;
  border: 1px solid #0063a6;
  background: #fff;
}

This, however, won’t change the colour of the progress bar itself, which will remain a green colour. We can change this in Firefox, Internet Explorer 10, Chrome, and Safari using a variety of methods which are outlined below.

Firefox

All we need to use here is:

progress::-moz-progress-bar { background: #0063a6; }

and Firefox will display the colour correctly.

A screenshot of the progress bar after custom styling

The progress bar as it appears in Firefox 18.0.2 after being styled.

Chrome and Safari

For Chrome and Safari, we need to use progress::-webkit-progress-value to specify the progress bar colour and progress::-webkit-progress-bar to specify the background colour of the <progress> element itself:

progress::-webkit-progress-bar { background: #fff; }
progress::-webkit-progress-value { background: #0063a6; }

Internet Explorer 10

Actually the CSS above will be fine to style the <progress> element in IE10, but it’s worth noting that this browser interprets the <progress> element’s color value as the colour of the progress bar.

I’ve uploaded some working examples of determinate and indeterminate progress bars for you to see.

Summary

The <progress> element may seem very similar to the <meter> element — which was also introduced in HTML5 — but it can be seen as a more specific kind of <meter> element that’s only used to measure progress of a task. It’s worth bearing this in mind when deciding which one to use.

Since browser support is pretty good, it’s definitely worth using the <progress> element where appropriate, but you should also ensure that you provide textual fallback for legacy browsers as has been outlined above.

The progress element originally appeared on HTML5 Doctor on February 12, 2013.

]]>
https://stevefaulkner.github.io/html5doctored/the-progress-element/feed/ 21
Multimedia Troubleshooting https://stevefaulkner.github.io/html5doctored/multimedia-troubleshooting/ https://stevefaulkner.github.io/html5doctored/multimedia-troubleshooting/#comments Tue, 31 Jul 2012 13:30:51 +0000 http://html5doctor.com/?p=4711 While I was researching HTML5 multimedia-related topics for my book, HTML5 Multimedia: Develop and Design, I noticed a number people struggling to get HTML5 audio and video working in different scenarios. From Twitter to Stack Overflow, the same questions kept cropping up, so I've put together a list of the most common problems (and some not so common) and their solutions (if there is one!).

]]>
While I was researching HTML5 multimedia-related topics for my book, HTML5 Multimedia: Develop and Design, I noticed a number people struggling to get HTML5 audio and video working in different scenarios. From Twitter to Stack Overflow, the same questions kept cropping up, so I’ve put together a list of the most common problems (and some not so common) and their solutions (if there is one!).

In most cases, the problems and solutions apply to both audio and video. I’ll note when something is specific to one or the other.

Before I go any further, if you aren’t aware of how you can actually go about adding audio and video to your website via HTML5, you can read a number of other articles on this site to get you up to speed. covered the video element, and Mark Boas covered native audio in the browser and HTML5 Audio – The State of Play.

In addition, I covered the same topics, video and audio, as part of a series over on the .

Browser Support

This is one of the first things you should check: Does the browser you’re using actually support the type of media file you’re trying to play? It’s simple enough to forget which browsers support which file types, so I’ll refresh your memory here.

Audio

  • Firefox supports Ogg Vorbis and WAV
  • Opera supports Ogg Vorbis and WAV
  • Safari supports MP3, AAC, and MP4
  • Chrome supports Ogg Vorbis, MP3, WAV, AAC, and MP4
  • Internet Explorer 9+ supports MP3, AAC, and MP4
  • iOS supports MP3, AAC, and MP4
  • Android supports AAC and MP3

In order to support all of the browsers mentioned above, it’s advisable to serve your audio file in Ogg Vorbis, and MP3. For example:

<audio controls> 
   <source src="myAudio.ogg" type="audio/ogg">
   <source src="myAudio.mp3" type="audio/mp3">
</audio>

Video

  • Firefox supports Theora Ogg and WebM
  • Opera supports Theora Ogg and WebM
  • Safari supports MP4
  • Chrome supports Theora Ogg, MP4, and WebM
  • Internet Explorer 9+ supports MP4 and WebM (requires a plugin)
  • iOS supports MP4
  • Android supports MP4 and WebM (2.3+)

In order to support all of the browsers mentioned above, you should serve your video file in both WebM and MP4 using the source element. For example:

<video controls>
   <source src="myVideo.mp4" type="video/mp4">
   <source src="myVideo.webm" type="video/webm">
</video>

MIME Types

Even if you have the correct media file for the browser, it’s possible that your server doesn’t have the correct MIME type set up. MIME types tell the server how to handle the different file types. If you’re using something akin to Apache and you know your stuff, head to the .htaccess file and add the following for audio support:

AddType audio/ogg ogg AddType audio/ogg oga AddType audio/wav wav AddType audio/mpeg mp3 AddType audio/mp4 mp4 AddType audio/mp4 mpa

And similarily for video support:

AddType video/webm webm AddType video/mp4 mp4 AddType video/ogg ogg AddType video/ogg ogv

If you don’t have access to your server’s .htaccess file, your control panel should have an option somewhere that allows you to view and add MIME types.

If you have a Windows server, then you may need to add the MIME types to IIS, either using the IIS Manager or in the web.config file.

File Conversion

It’s quite possible that a client has sent you a media file and you’ve determined its MIME type from its file extension. It’s possible, however, that the file wasn’t encoded correctly. It could, for example, be a perfectly valid MP4 file, but for some reason some browsers have trouble playing it. If this happens, you’re better off encoding the file yourself using a tool such as Miro Video Converter or Media Converter so you can be sure of the correct encoding.

Additionally, some files, especially MP4 files, don’t always play in a browser that is supposed to support them. This is due to the fact that MP4 (also known as H.264) files can be encoded according to different “profiles”. If the file in question is encoded in a profile that the browser doesn’t support, then naturally it won’t work. If this happens to you, try to ensure that the file is encoded according to the Baseline profile which is more likely to be supported than any of the more advanced ones. In my experience, using a tool like Miro ensures that the MP4 file will work just fine in supporting browsers.

If you need to support Firefox 3.6 and lower, you’ll also need to convert your audio files to Ogg and add them as an extra <source> for the <audio> element.

MP4 Files That Don’t Start Playing Until Fully Downloaded

Usually HTML5 audio and video players will allow the user to start playing a media file before it has fully downloaded (as long as it actually has something to play!). Sometimes this isn’t the case with an MP4 file, where the browser waits to download the entire file before making it available to play. This is due to an encoding issue.

Sometimes MP4 files are encoded with the file index (which contains information on the file such as it’s duration) placed at the end of the media file rather than at the beginning. This index contains the metadata that the browser requires in order for it to offer progressive download. If this index is at the end, it knows nothing at all about the file and therefore has to wait until it receives the index.

If this happens to you, there’s a simple fix called the QTIndexSwapper by Renaun Erickson that you download to your computer and run on the file that simply moves the index to the start of the file and saves it.

Getting Your Attributes Right

This might seem a little obvious, but it’s amazing how many questions I see on Stack Overflow where people are wondering why a certain function isn’t working when they’re using attributes that no longer exist. A prime example of this is the autobuffer attribute on both the <audio> and <video> elements, which was replaced by the preload attribute as far back as .

People seem to forget that HTML5 is not yet finalised (although large parts of it are quite stable) and that anything you read might be out of date. It’s worth checking the W3C HTML5 specification and also When Can I Use? to view browser support.

Volume Control in Firefox 11+

This is an problem that has cropped up recently. Some of you may have noticed that the volume controls have disappeared from the audio player in Firefox 11+. True, you can mute it, and the volume controls are still controllable via the keyboard’s up and down keys, but the volume slider itself was removed due to two bugs. I assume this will return in the future, but for now, in case you were wondering what happened to them, it’s not your fault. (You can, of course, use the Media API to build your own set of custom controls.)

Plugins Required

One of the biggest selling points of HTML5 audio and video is that no third-party plugins — such as Flash — are required in order to play multimedia files, as long as the browser in question supports it.

Unfortunately, this is not strictly true, as both Internet Explorer (9+) and Safari do require Microsoft Media Player and Apple QuickTime, respectively, to be installed in order for them to be able to play HTML5 audio and video files.

Video and Fullscreen

An oft-requested requirement for HTML5 video is the ability to play in fullscreen mode. The HTML5 specification has nothing to say on this, but a separate specification for a Fullscreen API is currently under work, with experimental versions available in some of the major browsers.

The following browsers go some way to supporting the Fullscreen API, albeit using their own vendor specific versions:

  • Chrome 19+
  • Firefox 12+
  • Safari 5.1+

There is also the screenfull.js JavaScript polyfill that enables this functionality for a limited number of browsers.

Internet Explorer 9+ Ignores Your Poster Image

If you have a HTML5 video defined with a poster image (using the poster attribute), you might be surprised when Internet Explorer 9 completely ignores it unless you have set the preload attribute to be none.

Since Internet Explorer was one of the last browsers to support HTML5, we all grew accustomed to the other browsers’ treatment of the poster attribute: if it’s specified, display that image until the user starts to play the video. Internet Explorer 9 doesn’t do this. It only displays the image contained within the poster attribute if it has nothing else to show, so if the first frame of the video has been loaded (with preload set to auto — the default value — or metadata), then it uses this regardless of what’s in the poster attribute.

This appears to be a case of Internet Explorer interpreting the specification in its own way and doing something different to all other browsers. Internet Explorer 10 also currently exhibits the same (mis)behaviour.

Accessing Webcams and Microphones

The ability to access peripheral devices such as microphones and webcams was always in the minds of the HTML5 specification writers when they added the <device> element. This has since been removed and replaced with the more thorough getUserMedia API, which allows access to such media devices.

The API itself is easy to use, but browser support is currently quite limited. Opera is currently the only browser with an implementation, supporting only video, but you can already see what it can do. Internet Explorer 10 will follow suit, and it will soon appear in Firefox Nightly.

Summary

This ends my round up of gotchas that you may encounter when working with HTML5 audio and video. Of course, it doesn’t cover everything, and I’m sure there are issues that you may have come across that haven’t been mentioned here. If you have, please do add them below in the comments, with their solution if possible, or if not, I or one of the other HTML5 Doctors will try to help.

Multimedia Troubleshooting originally appeared on HTML5 Doctor on July 31, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/multimedia-troubleshooting/feed/ 23
Finding your position with Geolocation https://stevefaulkner.github.io/html5doctored/finding-your-position-with-geolocation/ https://stevefaulkner.github.io/html5doctored/finding-your-position-with-geolocation/#comments Tue, 14 Jun 2011 14:35:07 +0000 http://html5doctor.com/?p=3324 The Geolocation API provides a method to locate the user's exact (more or less - see below) position. This is useful in a number of ways ranging from providing a user with location specific information to providing route navigation.

]]>
The Geolocation API provides a method to locate the user’s exact (more or less – see below) position. This is useful in a number of ways ranging from providing a user with location specific information to providing route navigation.

Although it’s not actually part of the HTML5 specification, as it was developed as a separate specification by the W3C, rather than the WHATWG, if the esteemed HTML5 Doctors Remy Sharp and Bruce Lawson felt it was fitting enough to include in their book, then it’s perfectly ok to write about it here.

The API is actually remarkably simple to use and this article aims to introduce the API and show just how easy it is.

Browser Compatibility

Currently the W3C Geolocation API is supported by the following desktop browsers:

  • Firefox 3.5+
  • Chrome 5.0+
  • Safari 5.0+
  • Opera 10.60+
  • Internet Explorer 9.0+

There is also support for the W3C Geolocation API on mobile devices:

  • Android 2.0+
  • iPhone 3.0+
  • Opera Mobile 10.1+
  • Symbian (S60 3rd & 5th generation)
  • Blackberry OS 6
  • Maemo

Data Protection

The specification explicitly states that since the nature of the API also exposes the user’s location and therefore could compromise their privacy, the user’s permission to attempt to obtain the geolocation information must be sought before proceeding. The browser will take care of this, and a message will either appear as a popup box, or at the top of the browser (implementation is browser specific) requesting the user’s permission.

Screenshot of Safari's popup box asking for Geolocation permission
Safari asking the user for permission to obtain their Geolocation information

Geolocation sources

A number of different sources are used to attempt to obtain the user’s location, and each has their own varying degree of accuracy. A desktop browser is likely to use WiFi (accurate to 20m) or IP Geolocation which is only accurate to the city level and can provide false positives. Mobile devices tend to use triangulation techniques such as GPS (accurate to 10m and only works outside), WiFi and GSM/CDMA cell IDs (accurate to 1000m).

Using the API

Before you actually attempt to use the Geolocation API, you first need to check if the browser actually supports it. The API usefully provides a function for this which can be called as follows:

if (navigator.geolocation) {
  // do fancy stuff
}

Obviously if this returns false, you should optionally inform the user of the inferiority of their browser and laugh in their face (not really).

Through the API, there are two functions available to obtain a user’s location:

getCurrentPosition and watchPosition

Both of these methods return immediately, and then asynchronously attempt to obtain the current location. They take the same number of arguments, two of which are optional:

  1. successCallback – called if the method returns successfully
  2. [errorCallback] – called if the method returns with an error
  3. [options] – a number of options are available:
    • enableHighAccuracy – provides a hint that the application would like the best possible results. This may cause a slower response time and in the case of a mobile device, greater power consumption as it may use GPS. Boolean with a default setting of false.
    • timeout – indicates the maximum length of time to wait for a response. In milliseconds with a default of 0 – infinite.
    • maximumAge – denotes the maximum age of a cached position that the application will be willing to accept. In milliseconds, with a default value of 0, which means that an attempt must be made to obtain a new position object immediately.

Before mentioning the differences between the two, another method needs to be introduced:

clearWatch

This method takes one argument, the watchID of the watch process to clear (which is returned by watchPosition)

Now, the main difference between getCurrentPosition and watchPosition is that watchPosition keeps informing your code should the position change, so basically it keeps updating the user’s position. This is very useful if they’re on the move and you want to keep track of their position, whereas getCurrentPosition is a once off. This method also returns a watchID which is required when you want to stop the position constantly being updated by calling clearWatch method is called.

When the user’s position is returned, it is contained within a Position object which contains a number of properties:

Property Details
coords.latitude Decimal degrees of the latitude
coords.longitude Decimal degress of the longitude
coords.altitude Height in metres of the position above the reference ellipsoid
coords.accuracy The accuracy in metres of the returned result. The value of this setting informs the application how useful the returned latitude/longitude value actually is. This can help in determining if the returned result is accurate enough for the purpose it is intended for, e.g. values for streetview locations will need to be more accurate than those for a country based location
coords.altitudeAccuracy The accuracy in metres of the returned altitude
coords.heading Direction of travel of the hosting device, clockwise from true north
coords.speed The current ground speed of the hosting device in metres per second
timestamp Timestamp of when the position was acquired

Amongst these only which is coords.latitude, coords.longitude and coords.accuracy are guaranteed to be returned (all others may be null), and the first two are by and large the most relevant, as it is from these that a position can be plotted on a Google Map, for example.

You can read more about the Position object and the coordinates interface on the W3 specification itself.

Putting it all together

Putting this altogether, the following code will attempt to obtain a user’s location, calling the method displayPosition on success which simply pops up an alert box with the captured latitude and longitude:

if (navigator.geolocation) {
  var timeoutVal = 10 * 1000 * 1000;
  navigator.geolocation.getCurrentPosition(
    displayPosition, 
    displayError,
    { enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
  );
}
else {
  alert("Geolocation is not supported by this browser");
}

function displayPosition(position) {
  alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
}

The code above also calls the displayError method when attempt to fetch the user’s location data. This function simple converts the returned error code to an appropriate message:

function displayError(error) {
  var errors = { 
    1: 'Permission denied',
    2: 'Position unavailable',
    3: 'Request timeout'
  };
  alert("Error: " + errors[error.code]);
}

A final word

This is just a simple introduction to using the Geolocation API and one of it’s uses.

Of course the API can be used for more than simply plotting a position on a map (although that in itself is quite useful). The specification itself offers a list of potential use cases for the API such as:

  • Finding and plotting points of interest in the user’s area
  • Annotating content with location informationShowing a user’s position on a map (helping with directions of course!)
  • Turn-by-turn route navigation – using watchPosition
  • Up-to-date local information – updates as you move

Examples

To see geolocation in action, I’ve put together a couple of quick examples in which I encourage you to view source and then go and try it out for yourself.

Finding your position with Geolocation originally appeared on HTML5 Doctor on June 14, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/finding-your-position-with-geolocation/feed/ 43