Making Web Apps Sizzle with Bing Maps and HTML5’s Geolocation API

2 Comments March 27, 2011


A few weeks ago, I wrote about Silverlight for Windows Phone’s location API, which allows applications to ascertain their location – latitude, longitude, altitude (if GPS is available), and so on. More recently, I’ve been writing samples around HTML5’s geolocation API. The two APIs are remarkably similar save for HTML5’s lack of support for setting movement thresholds. Both allow you to write location-aware apps with remarkably little code, and both can be combined with Bing Maps to produce stunning UIs pinpointing a user’s location, providing turn-by-turn directions, and more. In fact, once you learn one of the location APIs, you’ll feel right at home with the other. They’re that much alike.

To demonstrate how to combine HTML5 geolocation with Bing Maps, I wrote a sample that I call MapLocation.html. Here it is in IE9, with a pushpin directly over my house:

BingMaps

Here’s the source code for the page, minus the Bing Maps API key that you must register for before using Bing Maps controls and services:

 

<!DOCTYPE html>

<html>

<head>

<style type="text/css">

body {

    margin: 0;

    height: 100%;

    background-color: #404040;

}

#map {

     position: absolute;

    top: 50%;

    left: 50%;

    width: 800px;

    height: 600px;

    margin-left: -400px;

    margin-top: -300px;

}

</style>

 

<script charset="UTF-8" type="text/javascript"

  src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0">

</script>

 

<script type="text/javascript" src="jquery.js"></script>

 

<script type="text/javascript">

    var _map;

 

    $(document).ready(function () {

        // Create a Bing map

        _map = new Microsoft.Maps.Map(document.getElementById("map"),

            { credentials: "Insert Bing Maps API key here" });

 

        // Get the current position from the browser

        if (!navigator.geolocation)

            alert("This browser doesn't support geolocation");

        else

            navigator.geolocation.getCurrentPosition(onPositionReady, onError);

    });

 

    function onPositionReady(position) {

        // Apply the position to the map

        var location = new Microsoft.Maps.Location(position.coords.latitude,

            position.coords.longitude);

        _map.setView({ zoom: 18, center: location });

 

        // Add a pushpin to the map representing the current location

        var pin = new Microsoft.Maps.Pushpin(location);

        _map.entities.push(pin);

    }

 

    function onError(err) {

        switch (err.code) {

            case 0:

                alert("Unknown error");

                break;

            case 1:

                alert("The user said no!");

                break;

            case 2:

                alert("Location data unavailable");

                break;

            case 3:

                alert("Location request timed out");

                break;

        }

    }

</script>

</head>

<body>

 

<div id="map" />

 

</body>

</html>

 

So how does it work? First, I point a <script> element to http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0, which is home for the new Bing Maps AJAX control, version 7.0. Then I instantiate a Microsoft.Maps.Map object (the map) and insert it into the DIV named “map.” Next, I call HTML5’s navigator.geolocation.getCurrentPosition to get the latitude and longitude of my current location. When that call completes, I call setView on the map control, passing in the latitude and longitude provided by getCurrentPosition. For good measure, I create a pushpin at the same location so my current location is called out on the map. Not a lot of code, but a WHOLE lot of results!

Here’s what I found most surprising about this exercise. Testing it on my desktop PC, I wasn’t sure if the geolocation API would work. Even if it did work, I expected the accuracy to be low since the location data would have to come from Wi-fi positioning. In most browsers, the accuracy is good to within a few hundred feet. In IE9, it’s so accurate, it pinpointed the location of the router in my house! Most browsers, I believe, use a positioning service provided by Google to convert IP addresses into locations. (I know that’s true of Opera, because the first time an app running in Opera requests a location, Opera pops up a dialog and asks you to agree to Google terms and conditions.) IE9 evidently uses something different, which isn’t surprising given that Microsoft probably wouldn’t care to make their flagship browser dependent on anything Google provided. Whatever Microsoft is using, it’s amazingly accurate. Of course, your mileage may vary.

It’s pretty cool to know that with HTML5, you can write browser-based apps that, for example, use your current location to show nearby restaurants, movie theatres, and stores. But what’s even more alluring is the thought of building mobile apps that work across a range of devices. If I use Silverlight for Windows Phone to write a location-aware app, it only works on Windows phones. But if I use HTML5, it should work on iPhones, iPads, and even on Android devices. Once Windows Phone 7 acquires an HTML5 browser, it’ll work there, too.

Even HTML5 doesn’t insulate you from all the annoying differences between browsers; I still find myself spending way too much time trying to get something that works fine in Firefox working in IE9, too, or vice versa. But the geolocation API is so simple that there’s not a lot to break going from one browser to another. That’s good news for developers, and good news for consumers as well.


2 Comments

Have a Comment?

Archives

Tags

Blogs