Archiv:

Latest photoblog

photoblog

Blog » Webdev

Creating Mobile Websites

Why create a mobile website instead of an application? Using the web has a number of advantages, websites can be browsed on most devices, the technology is flexible, and it is easy to update sites so all users get the latest version. You only need to modify a single codebase if you want to add or change content or even features, rather than updating each application.

Context Is King

When you create a website for desktop browsers you typically design and develop for a context in which a user has a large display, enough time, power and also a fast persistent internet connection. None of these are guaranteed when using the internet on mobile devices.

Although most new devices have much larger screens than devices a few years before, they are mostly still small compared to desktop devices. Beyond that users often access a mobile website when they are on the go and they may be focusing on other things in addition to the web site they are using because they have to look at the traffic for example.

Other problems to consider are the effects of a weak signal and a slow mobile internet connection. Since the average internet user is impatient, you can easily lose a user who has to wait too long for pages to load – they may obtain the information elsewhere. Therefore you should try to keep content such as external scripts and images as small as practical.

You should consider these factors when you are about to design a website for mobile devices. Focus your mobile web strategy on what content a user is probably looking for when they visit your website. They are unlikely to be interested in your awesome company intro page animation made in Flash. Beyond you should also think about the contexts in which your mobile site will be used before you begin to design a mobile website.

It could be in a train with a weak signal, in a village with poor connection speed, outside in a sunny environment on a top-notch smartphone with touchscreen display as well as on an older feature phone with an even older browser and keypad operation. You cannot influence the context a user is in but you can design your site to be useable under all these circumstances.

Usability Aspects

After thinking about content and context it is equally important to consider usability. It is not only a matter of what content is interesting for a user and the contexts in it will be consumed but also a matter of how your target audience will use your site. Navigating your site is less fun when doing it using the device’s keyboard instead of just using your finger on a large screen but it can be easier if the links within your page are so damn small that it is almost impossible to hit them without causing unwanted behavior (like tapping other links as you actually wanted to). There are some basic hints to make sure your content is adapted in the best possible and usable way for mobile users:

  1. Make it “mobile” not only “small”: Create a concept that utilizes the possibilities of the technology. You won’t satisfy many people by simply offering a smaller version of your classic website. Mobilize, don’t miniaturize!
  2. Keep all paths open: Leave it up to the user to access either the mobile or desktop version of your website.
  3. Keep it simple: Avoid complex navigation structures, users will not dig that deep anyway while they are on the go.
  4. Avoid text input wherever possible: Text input on mobiles sucks. If you really need the users to enter text, use wide input boxes so that they see what they are typing. Buttons to clear an input field on click/touch are also helpful very often.
  5. Adapt the media: Adapt all pictures, videos and alike to be displayed properly on the handset (check the corresponding chapter in this guide: “Implementing Rich Media” for more information). Try to avoid formats such as .doc and pdf if possible.
  6. The user is a creature of habit: respect that: Adapt usage patterns from classic websites such as linking logos to the homepage or offering corrections to mistyped search requests.
  7. Think of stubby fingers: When optimizing your content for touch screen phones do not use clickable areas smaller than ~50x50px.
  8. Use sharp contrasts: Fonts and background colors that guarantee legibility in any surrounding, including bright sunlight.
  9. Reflect continuously: Ask yourself if you would use the implemented features yourself. Ask your friends and colleagues as well before realizing your ideas.
  10. Do not require the user to think. Try to implement intuitive navigation, do not force users to make decisions more often than necessary.

Technical Limits of Web Technologies

When it comes to the decision whether to create an app or a mobile website for a specific project many mobile developers tend to say “app” first because you seem to have more possibilities and better performance. This answer is seldom wrong but it is only half the truth. Let’s have a detailed view on the advantages and disadvantages of mobile websites or web apps compared with native mobile apps.

If you are coming from the “desktop world” and you have never created a website for mobile devices before (or if the last time you did is already a long time ago) you will be surprised about the capabilities of modern mobile phone’s web browsers. Assuming that you intend to optimize your mobile website mainly for modern platforms you would also create apps for (iOS, Android, BlackBerry OS, WebOS, bada, Windows Phone) we will primarily focus on modern browsers running on the mentioned platforms in this chapter.

The current generation browsers on major platforms support a variety of modern HTML5, CSS and JavaScript features like Geolocation, WebGL (interesting for mobile game development), hardware acceleration, offline storage and many more. You can easily find out if a user is online or offline, you can synchronize online data on a device for later offline use (e.g. if the signal is lost) and you can make whole web applications available even when a user has no active internet connection.

You can ask for permission to query the current position of a user just like you can do in a native app and you can also access the gyroscope of an iPhone using pure JavaScript directly in the browser. In addition mobile browser vendors are also working on making it possible to access the phone’s camera, network status or address book data.

Sounds pretty app like, doesn’t it? JavaScript is still often underestimated but if you know how you can rapidly create high class web apps which make extensive use of a device’s capabilities (almost) without the need to create proprietary versions for each platform.

And that’s not all: almost all recent mobile browsers support a lot of the current CSS3 standard and so you can create nice and shiny things like transitions, custom web fonts, drop shadows or rounded corners with only little effort which makes it very easy to let your web applications look and feel like native apps.

Pitfalls? Issues? Of course there are some. Although modern browsers already have a wide range of device API support there are still things you cannot yet do inside a browser. Accessing the camera as already mentioned is one thing. You cannot prevent the device from going to standby mode on a website which can sometimes be a problem. And sure: you will need to implement your own user interface in HTML, CSS and JavaScript instead of just using the native GUI functionality which is a bit faster in most cases. But if your code is clean and effects are used wisely the performance difference to native apps is so small that a user probably will not even realise he is just using a web app instead of a native app.

Feature Mobile Website Native App
Detect online status Yes Yes
Offline data storage Yes (very limited) Yes
Access GPS sensor/geolocation Yes Yes
Access gyroscope Yes Yes
Access camera Not yet (planned) Yes
Access address book Not yet (planned) Yes
Notifications (i.e. vibration, push, messages) Not yet (planned) Yes
Cross-platform compatible Yes No
Check battery status Not yet (planned) Yes
Different touch keyboard layouts on input fields Yes (incomplete) Yes
Appstore approval needed? No Yes

Fragmentation

“In mobile, fragmentation is forever”. Unfortunately it is not always as easy to create a cross-device cross-platform crossbrowser cross-markup “cross-blahblah” mobile website as you might think. Dealing with many different devices also results in an annoying fragmentation jungle. Some devices use their own implementation of device APIs (i.e. Geolocation on Blackberry OS 4.6) or even have absolutely no support for certain features (i.e. filesystem access on iOS).

This means you have to write workarounds of your code for different platforms and even for the same browser running on different platform versions. But the web wouldn’t be the web if there wasn’t already a solution for almost all of these problems. And so there are sites, libraries and services like caniuse.com, Modernizr or fitml.com where you can build quick and clean workarounds to handle fragmentation issues with only a minimum of effort. You still only need to write most parts of your web app once.

Server-Side vs. Client-Side Adaption

Basically there are two different approaches to professional mobile web development if you aim to deliver a great user experience. Either way you will have to determine which (type of) device is sending a request to your website and then you need to “guess” (server-side) or test (client-side) what features are supported by the according device.

Server-Side Detection and User Agent Sniffing

The first possible way is to do so using the so called “user agent sniffing” on the server-side and then let your server create and deliver an optimized version of your site to the client. Serverside detection is usually based on large databases containing the user agents of thousands of devices and their capabilities. The most common use of server side adaption is image scaling on the server to save some bytes when delivering a big image to a mobile device. In most cases it is not necessary to deliver a 800×600 JPG with a file size of 120K to a device whose display resolution is only 320×480. So you typically resize the image to the display size of the mobile device and then serve a much smaller version to the client.

Service-side detection can be a good choice for other reasons. You can also decide which markup to deliver based on the user agent of the accessing device. If you have a visitor with an iPhone or an Android phone you can serve a nice HTML5 document while users with old Nokia devices will receive an old fashioned XHTML 1.1 document.

The advantage of server-side adaption is that you optimize all the content to serve only what a client probably really needs. And “probably” is also the problem here. New devices are released so often it is hard to keep a device database entirely upto- date. There are some commercial providers for device databases (WURFL, DeviceAtlas, fitml.com for example) if you want to realize mobile web projects with server-side user agent detection I strongly recommend you consider one of these as they have full time employees actively maintaining their databases and do a lot of work that would be impractical for you to do yourself.

Pitfall here: user agents can be “wrong”, manipulated or unknown. You should therefore always provide a fallback in case your user agent detection fails. Such a fallback could be a document in a format (i.e. HTML4) that almost every mobile browser released in the past 5 years can understand.

Client-Side Adaption and Feature Detection

Client-side feature detection is the second approach to create a great user experience on mobile websites. Feature detection in general means that you use JavaScript to look if a certain capability is supported on the accessing device. To give you a first impression: you can use if(navigator.geolocation) to check if a device supports acquiring of the user’s current position.

Feature detection also means that you will have to deliver the complete document with all possible features of the website in it and then gracefully degrade it by removing features which are not supported on the device. That means you are sending a lot of content to all devices regardless of whether a certain feature is supported on a device or not.

One big advantage compared to server-side adaption: when a feature test passes you can (under normal conditions) be sure that your desired feature or behavior will work as expected even if a user agent was modified and therefore was not recognized properly by a device capability database.

The Modernizr JavaScript library is probably the first place to go when it comes to client-side feature detection. Modernizr covers a lot of possible browser capabilities and provides a simple API to check for support of a certain feature. If you need to know whether a browser supports Drag and Drop or not, just use the Modernizr library this way:

if(Modernizr.draganddrop) {
	// browser supports native drag and drop
} else {
	// fallback
}

Another part that belongs to the client-side is the adaption of layout. On modern mobile browsers you can use media queries which let you apply CSS rules only if a client or browser matches certain conditions. You can easily show a two column layout when a device exceeds a display width of 800px (on tablets for example) and fall back to a linear one column layout when a device’s display has a resolution of less than 800px.

Issues concerning client-side approach: first there are some things, especially browser bugs, which may be hard to detect on client side. Another big problem is that you always have to serve the whole document with large scaled images and a bunch of JavaScript to the client since you do not know if your visitor is using a bleeding-edge hipster browser from Cupertino or an oldschool “I don’t know what JavaScript is” browser from 2003.

Why not just use the best of both worlds?

Excellent idea! There is of course no rule that forbids to combine both server-side and client-side technology to create an even better user experience. So you can try to determine the basics (“which markup should be used?”, “what is the correct size for images?”, “JavaScript support, yes or no?”) on the server and let the client handle the rest. You can provide server-side fallbacks for JavaScript enhancement to make a site accessible and so you can create mobile websites which even work fine on old devices.

A commercial platform working according to this principle is fitml.com where you describe your content in an abstract XML markup called FITML, the platform then converts your markup to the best suitable output format and optimizes both on serverside and on client-side.

Hybrid Apps

If you necessarily want (or need) to publish your mobile app on Android Market, Apple Appstore, etc. you can also create a “hybrid app”. Create your app completely by using common web technologies (HTML, CSS, JavaScript) and then compile it as app. Sounds easy? It is. There are several hybrid app frameworks which let you create native apps with only a single HTML5 web app as shared base. There is PhoneGap2, Appcelerator3 or Apparat. io4 and probably many more you can use to achieve this.

How does it work exactly? Write your complete application in HTML5 just as you were about to publish it to the web. Then you use one of the frameworks to compile your web app as native app. The framework creates some sort of “wrapper app” which embeds your web app in a “web view” and it can then be installed as regular application on several different platforms. The big plus of doing it this way is that you only have one web app as the base and thus you can reduce your costs for development and maintaining but the result is still a “real” native app.

Small downer: although frameworks let you use features in your web app which you usually cannot use in a browser hybrid apps are not a complete substitute for native apps. They offer some nice advanced functions like vibration, access to camera or address book but in its core it still is a web app. That means you will have to create your own user interface which might be slower and you also cannot use really everything as you can when creating an app using the native SDK.

Lessons learned

The gap between native apps and web apps is rapidly decreasing. Browser vendors did a lot of good work in the past few years and implemented many features which were only available in native apps. There are different approaches to create great mobile websites which can look and even feel a lot like a native app and new devices will be released that have even better support for HTML5 and its device specific enhancements.

Creating mobile websites or mobile web apps makes your content accessible over the web on almost every platform with only little work compared to native development for several platforms. It can thus save you a lot of costs for development and maintenance. Due to the existence of hybrid app frameworks you can even publish your apps in app stores.

If you have never developed a mobile website or web app before or if you were not convinced because of the poor browsers in the early days of the mobile web you should give it another try. Consistent support of the many different features is still far from perfect but it has been improved by at least 1000% since the rise and success of Android and iOS.

When you became curious and want to create a mobile website always have one thing in mind: make your mobile website mobile, not just smaller!

This article was published in the Mobile Developer’s Guide To The Galaxy #9 in October 2011. You can download it for free.

Linkdump #5

5

A short test on performance when using IDs in CSS selectors:
http://oli.jp/2011/ids/

Nice trick: Fixing the JavaScript typeof operator
http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/

Understanding prototypes in JavaScript
http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/

How LinkedIn used Node.js and HTML5 to build a better, faster app
http://venturebeat.com/2011/08/16/linkedin-node/

Advantages of Most Perpetual Web Development Technologies – PHP, ASP.NET, Java, Ruby on Rails
http://phpwebdevelopmentservices.blogspot.com/2011/05/advantages-of-most-perpetual-web.html

10 Excellent HTML5 coding Tools Many Users Don’t Know About
http://smashinghub.com/excellent-html5-coding-tools.htm

Geolib.js

I created a small JavaScript library to provide some basic geo functions like distance calculation, conversion of decimal coordinates to sexagesimal and vice versa, etc.

Usage:

To calculate distance between two geo coordinates
geolib.getDistance({"latitude": 51.511928, "longitude": 7.463536}, {"latitude": 51.510318, "longitude": 7.524133}, 10); // -> 4200 (Accuracy 10m)

Takes 2 or 3. First 2 arguments must be an object with a latitude and a longitude property (e.g. {latitude: 52.518611, longitude: 13.408056}). Coordinates can be in sexagesimal or decimal format. 3rd argument is accuracy (in meters). So a calculated distance of 1248 meters with an accuracy of 100 is returned as 1200.

Return value is always an integer and represents the distance in meters.

To convert it into miles use:
geolib.convertUnit('mi', value)

Convert sexagesimal to decimal
geolib.sexagesimal2decimal("51° 29' 46\" N"); // -> 51.49611111

Convert decimal to sexagesimal
geolib.decimal2sexagesimal(51.49611111); // -> 51° 29' 46.00

Download:
https://github.com/manuelbieh/geolib

Demo:
http://www.manuel-bieh.de/publikationen/scripts/geolib/demo.html

Linkdump #4

4

18 mistakes that kill startups
http://www.paulgraham.com/startupmistakes.html

7 lovely things about HTML5
http://www.elated.com/articles/7-lovely-things-about-html5-markup/

Lists are cool. So here is another one: 15 HTML5 Canvas Applications Developers Should Know About
http://smashinghub.com/15-html5-canvas-applications-developers-should-know-about.htm

CSS3 @font-face design guide
http://webdesignerwall.com/tutorials/css3-font-face-design-guide

Published more than a year ago but still worth reading: Signs of a poorly written jQuery plugin:
http://remysharp.com/2010/06/03/signs-of-a-poorly-written-jquery-plugin/

Linkdump #2

2

An article about the new CSS calc() function. A feature we all have been waiting for a long time and yes: it already works in Firefox 4 and even in IE9(!):
http://webdesignernotebook.com/css/the-wonderful-calc-function/

Jeremy Keith has created a list of collected design principles, divided into five categories: people, organisations, formats, software, hardware. Definately worth reading:
http://principles.adactio.com/

30 Creative Examples of Responsive Web Design
http://webdesignledger.com/inspiration/30-creative-examples-of-responsive-web-design

A web-based DJ prototype plus a really comprehensive post about how it was created:
http://wheelsofsteel.net/
http://www.schillmania.com/content/entries/2011/wheels-of-steel/

If you want to develop websites or web apps for mobile using several different content sources like Twitter API, RSS feeds or your existing desktop website, you should consider to have a look at fitml.com which was released as public beta at the beginning of this week (disclosure: I work for Sevenval, the company behind fitml.com)
http://fitml.com

Linkdump #1

1

Nice demonstrations of what you can do with webfonts in combination with CSS3
http://webfontgallery.com/

An overview of new features coming in iOS 5
http://davidbcalhoun.com/2011/new-mobile-safari-stuff-in-ios5-position-fixed-overflow-scroll-new-input-type-support-web-workers-ecmascript-5

If you have to re-style large data tables for mobile and you have no idea how, this article on responsive data tables might help:
http://css-tricks.com/responsive-data-tables

You have recently made any award-worthy CSS3 animations and now you wanna win your deserved prize for it? Submit it to the Mozilla DevDerby:
https://developer.mozilla.org/en-US/demos/devderby

A browser tictactoe game including a computer opponent with only HTML and CSS – completely without JavaScript. You think that’s impossible? No it’s obviously not:
http://jsdo.it/usualoma/qzfr

fitml.com 1.0 beta is now online. The awesome mobile development platform I’ve been working on in the past 8 months is now online. Sign up and give it a try!
http://fitml.com

Another private showcase I’ve been working on went online yesterday. It was created during my daily trainride from Dortmund to Cologne and back. Check out my (yet little) HTML5 and CSS3 showcase
http://doctypehtml.net/

Geolocation jQuery-Plugin

I created a small jQuery plugin which acts as a simplification of the Geolocation API.

Instead of using navigator.geolocation.getCurrentPosition you can now just use the jQuery methods $.geolocation.get() or $.geolocation.watch().

Contrary to the standard API the only parameter the functions expect is a JSON object with three properties in no particular order: success, error, options. For success and error you can also use their alias properties „win“ and „fail“:
$.geolocation.get({win: function() {}, fail: function() {}, options);

You can also use $.geolocation.getCurrentPosition(success, error, options) to get native API feeling if this makes you happier. In conjunction with my Geolocation API polyfill script this also works with some non-standard Geolocation APIs like Google Gears or Blackberry Location.

Usage

$.geolocation.clearWatch(watchID)
Stops tracking of the user for the according watchID.
watchID (Integer)
$.geolocation.get(options)
Get the current position of the user
options (Object)

  • error
    Function to call if geolocation request failed
  • fail
    Alias for error
  • options
    Options for the geolocation request

    • enableHighAccuracy
    • maximumAge
    • timeout
  • success
    Function to call if geolocation request was successful
  • win
    Alias for success
$.geolocation.getCurrentPosition(success, error, options)
Get the current position of the user (API standard behavior)
success Function to call if geolocation request was successful
error Function to call if geolocation request failed
options Options for the geolocation request

  • enableHighAccuracy
  • maximumAge
  • timeout
$.geolocation.stop(watchID)
Stops tracking of the user for the according watchID.
watchID (Integer)
$.geolocation.stopAll()
Stops all watchPosition callbacks.
$.geolocation.watch(options)
Track the movement of the user
Returns: watchID (Integer)
options (Object)

  • error
    Function to call if geolocation request failed
  • fail
    Alias for error
  • options
    Options for the geolocation request

    • enableHighAccuracy
    • maximumAge
    • timeout
  • success
    Function to call if geolocation request was successful
  • win
    Alias for success
$.geolocation.watchPosition(success, error, options)
Track the movement of the user (API standard behavior)
Returns: watchID (Integer)
success Function to call if geolocation request was successful
error Function to call if geolocation request failed
options Options for the geolocation request

  • enableHighAccuracy
  • maximumAge
  • timeout

Examples

function alertMyPosition(position) {
	alert("Your position is " + position.coords.latitude + ", " + position.coords.longitude);
}
 
function noLocation(error) {
	alert("No location info available. Error code: " + error.code);
}
 
$('#getPositionButton').bind('click', function() {
	$.geolocation.get({win: alertMyPosition, fail: noLocation});
});
 
$('#watchPositionButton').bind('click', function() {
	// alertMyPosition is called each time the user's position changes
	myPosition = $.geolocation.watch({win: alertMyPosition}); 
});
 
$('#stopButton').bind('click', function() {
	$.geolocation.stop(myPosition);
});

Demo

http://manuel-bieh.de/publikationen/scripts/jquery/geolocation/

Download

https://github.com/manuelbieh/jQuery-Geolocation

Styleform jQuery-Plugin


[English version below!]

Mit diesem Plugin ist es möglich Checkboxen und Radiobuttons zu stylen.

Anwendung:

Einfach jedem Form-Element dessen Checkboxen und Radiobuttons gestyled werden sollen die Klasse „styleform“ anhängen. Alternativ kann das Styling auf alle oder nur ausgewählte Formulare angewandt werden:
$('form').styleForm();
$('#myForm').styleForm();

Styling:

Es kann entweder ein eigenes Stylesheet erstellt werden mit eigenen Eigenschaften für die klassen .styleRadio und .styleCheckbox was allerdings recht kompliziert ist, da es kein sauberes Standard-Stylesheet ist das angewandt werden kann. Daher empfiehlt es sich, einfach die mitgelieferten Bilder im images-Ordner so zu bearbeiten wie man es wünscht.

Bonus!

Ein iPhone Theme wird in drei größen mitgeliefert.

Bekannte Probleme:

  • Opera ignoriert die disabled Eigenschaft komplett

Wünsche:

  • Styling von select Elementen ermöglichen

Demo

http://www.manuel-bieh.de/publikationen/scripts/jquery/styleform
http://www.manuel-bieh.de/publikationen/scripts/jquery/styleform/iphone.html

Download

http://plugins.jquery.com/project/Styleform

English description

You can use this plugin if you want to change the default look of checkboxes and radiobuttons.

Usage:

Just add the class „styleform“ (all lowercase) to any form you want to be styled. Or you can alternatively use:
$('form').styleForm();
to apply the styling of checkboxes and radiobuttons in all forms inside a document.

Styling:

You can either create a new stylesheet with your own properties styling the .styleRadio and .styleCheckbox classes which is however quite complicated since there is no default stylesheet that can be applied yet. Or you can (the easy way) use the provided themes and edit the files inside the images folder the way you want it.

Bonus:

iPhone theme included in three different sizes (small, normal, big)!

Known issues:

  • Opera ignores the disabled state completely

Wishes:

  • Add styling of select elements

Demo

http://www.manuel-bieh.de/publikationen/scripts/jquery/styleform
http://www.manuel-bieh.de/publikationen/scripts/jquery/styleform/iphone.html

Download

http://plugins.jquery.com/project/Styleform

Xify jQuery-Plugin

[English version below!]
Da ich die Funktion aus der iPhone-Safari Adressleiste schon immer sehr praktisch fand, und mir diese schon oft für Eingabefelder auf Websites gewünscht habe, habe ich mich gestern kurz hingesetzt und ein kleines jQuery-Plugin gebaut, welches mir diese Funktionalität abbildet.

„Xify“ erzeugt einen X-Button zu einem Textfeld wie man ihn aus der Adressleiste des iPhone-Safari kennt. Ein Klick auf das Symbol löscht den kompletten Text des dazugehörigen Textfelds. Benötigt jQuery ab Version 1.2.3.

Die Anwendung

$('input:text').xify();
$('input:password').xify({color: "red"});

Parameter

color
Hintergrundfarbe des Buttons
Typ: CSS Farbangabe
Standardwert: #bbb
size
Größe des Buttons
Typ: integer
Standardwert: 12
left
Angabe um wieviel Pixel der Button im Eingabefeld nach links gerückt werden soll
Typ: integer
Standardwert: 4
callback
Callbackfunktion die aufgerufen wird, wenn das X geklickt wird. Muss true oder false zurückgeben.
Typ: function

Demo

http://www.manuel-bieh.de/publikationen/scripts/jquery/xify/

Download

http://plugins.jquery.com/project/xify

English description

You can use this plugin to automatically add a small „X“ to each input field to remove the current value by clicking or touching the X. You may know this function from the iPhone Safari URL bar. Requires jQuery 1.2.3+

Usage

$('input:text').xify();
$('input:password').xify({color: "red"});

Parameters

color
Backgroundcolor of the button.
Type: CSS color value
Default: #bbb
size
Size of the button.
Type: integer
Default: 12
left
Amount of pixels the button is moved to the left within the input field.
Type: integer
Default: 4
callback
Callback which is executed when the X is clicked. Must return true or false.
Type: function

Demo

http://www.manuel-bieh.de/publikationen/scripts/jquery/xify/

Download

http://plugins.jquery.com/project/xify

Geolocation: und dein Browser weiß, wo du bist

Viele Web-Entwickler haben lange darauf gewartet, mit aktuellen Smartphones und auch neueren Browsern am Desktop ist es nun endlich möglich: die zielgenaue Ortung des Besuchers einer Website. Die W3C Geolocation API hilft dabei.

Damit wird es einem Seitenbetreiber nun ermöglicht – vorheriges Einverständnis des Besuchers vorausgesetzt – dessen aktuelle Position (Längengrad, Breitengrad, Höhenlage), die Reisegeschwindigkeit, sowie die Himmelsrichtung zu ermitteln und daran angelehnt entsprechend geolokalisierte Inhalte auszuliefern. Für einen Tankstellenbetreiber wäre es damit z.B. möglich, einen Tankstellenfinder zu realisieren, der dem Besucher die umliegenden Tankstellen inklusive Entfernung oder sogar eine genaue Wegbeschreibung auf dem Handy präsentiert. Auch eine Tracking-Anwendung, die bspw. die zurückgelegte Wegstrecke beim Joggen für die spätere Analyse am PC aufzeichnet, könnte so – ohne eine App zu installieren – mit dem Browser realisiert werden.

Anders als bei bisherigen Methoden wird dabei nicht ausschließlich auf die IP des anfragenden Clients geachtet, sondern es werden darüber hinaus Parameter wie umliegende öffentliche W-LAN SSIDs (inkl. Stärke des Empfangs) oder ein möglicherweise vorhandenes GPS-Modul abgefragt. Um datenschutzrechtliche Bedenken aus der Welt zu schaffen, wird der Benutzer beim Versuch einer Ortung jedoch vorab um Erlaubnis gefragt. Sollte dieser die Anfrage verneinen, ist der Zugriff auf den Standort über die API nicht möglich.

Wie bei den meisten Technologien, die sich gerade in den Kinderschuhen befinden, gibt es aber auch bei der Implementierung der Geolocation API leider noch einige Tücken. So unterstützen nicht alle Browser mit grundsätzlicher Unterstützung der Geolocation API auch alle Funktionen, die in der Spezifikation vorgesehen sind, und auch die Methoden, mit der die Daten abgefragt werden können, unterscheiden sich teilweise erheblich. Darüber hinaus nagt häufiges Orten bei mobilen Geräten, also Geräten ohne permanenten Strom-Anschluss, stark am jeweiligen Akku. Die Lokalisierung sollte also nicht unnötig oft oder mit einem übertrieben kurzen Intervall durchgeführt werden.

Zumindest um das Problem mit dem nicht einheitlichen Interface zu umgehen, gibt es einige frei nutzbare Open Source JavaScript Libraries, die ein vereinheitlichtes Interface zur Verfügung stellen, wie beispielsweise Geo-location-javascript oder Better Geolocation API.

Eine generelle Unterstützung des Standards, ob vollständig oder nicht, gibt es im Wesentlichen bisher in den folgenden Browsern bzw. Geräten:

  • Android Webkit und Dolphin HD
  • Apple iPhone/iPod Safari iOS 3.0+
  • Blackberry OS 4.1+
  • Firefox 3.5+ (< 3.5 mit installiertem Geode Addon)
  • Google Chrome
  • Opera 10.6+
  • Alle Browser mit installiertem Google Gears

Um eine Ortung in einem Browser durchzuführen, der den Standard korrekt implementiert, kann der folgende exemplarische Code verwendet werden:

var successCallback = function(position) {
    alert('Ihre Position: ' + position.coords.latitude + ', ' + position.coords.longitude);
}
 
var errorCallback = function(error) {
alert('Es konnte keine Ortung durchgeführt werden. Fehlercode: ' + error.code);
}
 
if(typeof (navigator.geolocation) != 'undefined') {
    navigator.geolocation.getCurrentPosition(
        successCallback,
        errorCallback,
        {
            enableHighAccuracy: true,
            maximumAge: 10000
        }
    );
}


Zur Erklärung: Mittels typeof(navigator.geolocation) != 'undefined' wird abgefragt, ob der Browser des Benutzers die Geolokalisierung unterstützt. Daraufhin wird die Methode getCurrentPosition() aufgerufen, welche versucht, die aktuelle Position des Benutzers zu ermitteln. Gelingt dies, wird die als successCallback angegebene Funktion aufgerufen und ein Objekt position übergeben. Dieses erhält dann in position.coords.longitude bspw. den ermittelten Längengrad in Dezimalform (z.B. 7.45333164).

Schlägt eine Ortung hingegen fehl, wird die als errorCallback angegebene Callback-Funktion aufgerufen. Als Übergabe gibt es hier das PositionError-Objekt, das gemäß Spezifikation die Zahlenwerte 0 (Unbekannter Fehler), 1 (Ortung nicht erlaubt), 2 (Position konnte nicht ermittelt werden) oder 3 (Timeout) enthalten kann.

Als dritter, zusätzlicher und zugleich optionaler Parameter kann noch ein Objekt in JSON-Notation angegeben werden, um die Eigenschaften der Abfrage genauer zu spezifizieren. Gültige Eigenschaften des Objekts sind:

  • enableHighAccuracy
  • maximumAge
  • timeout

Die Eigenschaft enableHighAccuracy soll sicherstellen, dass ein besonders genaues Ortungsergebnis erzielt wird. Dies geht allerdings, wie eingangs angesprochen, einerseits auf Kosten des Akkus, andererseits verzögert es die Ortung unter Umständen massiv. Im Gegenzug wird dafür die Fehleranfälligkeit sowie die Möglichkeit der Fehlortun verringert.

Über die Eigenschaft maximumAge kann festgelegt werden, wie alt das Ergebnis der letzten Ortung maximal sein darf (in Millisekunden), bevor eine erneute Ortung durchgeführt wird. Setzt man den Wert sehr hoch, ist das Ergebnis, sollte man sich in der Zeit seit der letzten Ortung bereits weit vom Ursprungsort weg bewegt haben, sehr ungenau. Setzt man es hingegen sehr niedrig an, geht das auch hier zu Lasten des Akkus. Einen empfehlenswerten Erfahrungswert gibt es hier nicht, da kommt es sehr auf den jeweiligen Anwendungsfall und etwas Fingerspitzengefühl an.
Mittels der dritten Eigenschaft, timeout, kann angegeben werden wie lange das Gerät bzw. der Browser probiert, die Position herauszufinden, bevor die errorCallback-Funktion mit dem Vermerk Timeout aufgerufen wird.

Neben der getCurrentPosition()-Methode, gibt es auch noch eine zweite Methode watchPosition(). Mit dieser Methode, die die gleichen Parameter erwartet wie auch getCurrentPosition(), ist es möglich, die Bewegung eines Benutzers zu verfolgen und die als successCallback definierte Funktion bei jeder Positionsänderung erneut aufzurufen. Um dieses Verhalten zu stoppen, muss die dritte und letzte Methode der API, clearWatch(), mit der Rückgabe-ID des watchPosition() Aufrufs aufgerufen werden.

Am konkreten Beispiel:

if(typeof (navigator.geolocation) != 'undefined') {
    var watchExample = navigator.geolocation.watchPosition(
        successCallback,
        errorCallback,
        {
            enableHighAccuracy: true, maximumAge: 10000
        }
    );
 
    // watchPosition wieder anhalten:
    navigator.geolocation.clearWatch(watchExample);
 
}

Die Geolocation API bietet eine sehr interessante Möglichkeit für Seitenbetreiber, die ihre Seite mit standortspezifischen Daten anreichern möchten. Man kann davon ausgehen, dass in Zukunft mehr mobile Geräte und mehr Browser den Standard korrekt unterstützen werden. Wenn die Hürden der Vereinheitlichung des Interfaces erst einmal genommen sind oder man sich mit den genannten Möglichkeiten weiterhilft, entstehen so viele neue Möglichkeiten, um das Web mit sinnvollen zusätzlichen Funktionen anreichern zu können. Der Kreativität des Web-Entwicklers sind dabei (fast) keine Grenzen gesetzt.

Dieser Artikel entstand im Rahmen des Webkrauts Adventskalenders und wurde dort am 3. Dezember 2010 erstveröffentlicht.