.NET Rocks!
Road Trip Tracking

Fig 0 - Tracking a RoadTrip


Overview

Microsoft is on the move this fall. Win8 is the big news, but Visual Studio 2012, .Net 4.5, a revamped Azure, WP8, Office 2013, and even a first foray into consumer hardware, Surface Tablets (not tables), all see daylight this fall.

The Net Rocks duo, Carl Franklin and Richard Campbell, are also on the move. Carl and Richard head out this week for a whirl wind tour through 36 states in 72 days or roughly 1728 hours. The DNR Road Trip Tracking application, http://www.web-maps.com/RoadTrip2012/, keeps tabs on the .Net Rocks RV with Tweet encouragement for the road weary travelers. All are welcome to follow the DNR RV online and add Tweet comments at #dnrRoadTrip. The app gives event information and up to the minute updates of time to next show with tweets along the route. It even gives turn by turn directions for those inclined to catch the .Net Rocks RV and follow along in the real world – .NET Rocks stalking.

Technical Overview

Project Outline

Fig 1 – .Net Rocks Road Trip Tracking app project outline

Backend:

SQL Server Azure is the key resource for the DNR tracking app. GPS feeds are pushed at 1 minute intervals from a commercial Airlink GPS unit to a Windows service listening for UDP packets. This Feed Service turns incoming UDP packets into Feed records stored in SQL Azure with a geography point location and datetime stamp.

On the same system, a Twitter Query service is checking for Tweets on a 30 second interval using the Twitter REST API. Tweets are also turned into Feed records in SQL Azure. However, the geography point locations for Tweets are pulled from the latest GPS record so they are associated in time with the location of the GPS unit in the DNR RV.

Frontend:

Fig2 – Windows 8 IE10 browser showing stop and routes

On the front end, an Azure WebRole provides the UI and WCF service for communicating with the SQL Azure Feed data. In order to handle the widest spectrum of devices, this UI leverages jQuery Mobile sitting on top of HTML5. jQuery Mobile Supported Platforms

Inside the app divs (jQuery Mobile <div data-role=”page”..> ) are maps leveraging Bing Maps Ajax v7 API. The UI client also accesses Bing Geocode and Bing Route services through a proxy.

Fig 3 – IE9 on a laptop with GPS dots and Tweet icons along the way

Some more details:

Routes

Since there are several thousand points for each ‘event to event’ route, these are stored in SQL Azure as geography LineStrings. Using SQL Server spatial functions, the routes can be simplified on query for improved performance in both network latency and map rendering. SQL Azure’s geography Reduce(factor) function is a thinning algorithm that reduces the number of vertices of geography features while maintaining shape integrity. In this app the reduce factor is tied to zoomlevels of the map, thinning the number of points returned to the UI.

The map viewport is used as a bounding box STIntersect so only the visible routes are returned. Obviously Carl and Richard may find reasons to take a different route so the GPS breadcrumbs may wander from the Bing generated routes.

Tweets

Fig 4 – WebMatrix iPad simulator

The Twitter REST API queries are simple search by hashtag queries:
http://search.twitter.com/search.json?q=%23dnrroadtrip

To avoid returning lots of duplicate Tweets the search is limited by the last since_id in the Feed table. There are some caveats to REST Twitter searches:
“Search is focused on relevance and not completeness. This means that some
Tweets and users may be missing from search results

Fig 5 - webmatrix WP7 emulator

Fig 6 - iPhone simulator

GPS points

GPS points are generated every 60 seconds while the RV GPS unit is powered on. When the vehicle is off, and power is scarce, the unit still sends a packet once every 4 hours. Carl and Richard will be driving a lot of hours and there will be lots of points generated over the next 72 days and roughly 1728 hours. Assuming a 25% driving time over the duration, there could be as many as 1728/4 *60 = 25,920 GPS locations. Even Bing Maps Ajax v7 will choke trying to render this many locations.

In order to keep things more reasonable, there is another thinning algorithm used in the GPS query service. This is again tied to zoomlevel . At lower zoom levels points are thinned using a type of decimation – every 20th, 10th, 5th point, etc is kept depending on the zoomlevel. In addition only points required by the viewport bounding box are returned. Once the map is zoomed to higher resolution (zoom > 11) all of the points will be returned.

GPS map locations include a rollover infobox with time and detected speed at the location. We can all check up on Carl’s driving (moving: 86.99mph) and keep track of coffee stops (moving: 0.0 mph).

Bing Routes

Routing services are provided for user position to the latest GPS location and Stop venues selected on the map or from the Stop list. In addition to the route map a turn by turn directions list is provided as a page option. The GeoLocation API is used for identifying a user’s location for these routing requests. Geolocation API is an opt in API, so users need to allow location sharing to have their location automatically available. If allowed, getCurrentPosition returns a latitude, longitude which is run through the Bing reverse geocoding service to get an address used as the ‘from’ field for routing requests.

Fig 7 - Stop Detail with Maps.Themes.BingTheme()

Fig 8 - Bing Route Denver to Seattle Stop

Fig 9 - Bing Turn by Turn directions

jQuery Mobile

jQuery Mobile is a javascript library for abstracting away some of the complexity of supporting a large number of devices. WP7, Win8 tablets, iPads, iPhones, and Android devices are multiplying while traditional laptop and desktop systems have a number of browser choices and versions. jQuery Mobile is not perfect but it is a great help in a project that had to be ready in about ten days from start to finish.

One interesting feature of jQuery Mobile is the page transition effect. These are based on CSS3 and are not supported by all browsers. It adds a little pizazz to see slide, flip, and pop effects for page transitions.

JQuery Mobile apps do not have access to device native sensors such as accelerometer, compass, gyrometer, etc , so jQuery Mobile webapps will not have the full range of capabilities found in custom apps for Win8, WP7, iOS, and Android. However, just one web UI for all is an enticing benefit, while deployment is ordinary webapp rather than a series of more complex app store submissions. This approach allows easy updates over the course of the tour.

Fig 10 – Microsoft Way on an Android AVD emulator

Heatmaps
Collecting some locations always leads to the possibility of heatmaps. These are value gradients which are helpful for analyzing geospatial data.

Fig 11 – Tweet heatmap along tour route from Seattle to Wyoming

Maybe it’s pretty obvious where Tweets are concentrated, but how about locations of app users who share their location. Australia is hot, India is not. Guess who listens to .NetRocks! Or, at least who’s less cautious about sharing location with GeoLocation API. User heatmaps bring to mind some intriguing possibilities for monitoring use, markets, and promotion effectiveness.

Fig 12 - GeoLocation users world wide

Summary

On the Road Again

Windows 8 RTM and Bing Maps

Fig 1 Windows 8 Grid App template

Windows 8 RTM was released to developers last week. Win8 with its “Metro” style UI promises to be a major reset to both the Windows OS and the Microsoft developer community. No longer called “Metro” due to some potential trademark issues, the new Win8 style is very much aimed at touch devices. It targets the full spectrum of platforms: smart phones, tablets, laptops, desktops, and servers, but touch is obviously the preferred interface.

The goal appears to be an OS that easily transitions between desktop and mobile. A worthy goal for multi device consumers who in a Microsoft world would no longer need to shift gears dramatically from one device to the next. OSs are like musical instruments, the fingerings differ from one to the next requiring an annoying shift of gestalt gears. Now that smartphones are firmly entrenched, consumers are forced to master alternative OSs and leakage out of the Microsoft OS corral is growing. Microsoft is concerned enough to take the risk of a Windows reset with Win8 Metro.

In the conventional desktop world we have Windows, Apple OS X, and Linux focused on screen, mouse, and keyboard interfaces. In the mobile world we have iOS, Android, BlackBerry OS, and WP7 focused on screen, touch, voice, and a plethora of sensors pertinent to motion. Win8 puts both into one OS, desktop and mobile, but mobile is the front man. WP8 and Win8 appear to be on a merging trajectory.

Win8 and Maps
From a mapping perspective there are again two paths, desktop and mobile (Metro)
… oh and plain old internet.

Internet
IE10 forks browser web apps as well:
(with some nice html5, css additions, … and websockets)
1) Win8 desktop IE10 – compatible desktop experience including plugins like Silverlight
2) Win8 mobile IE10 – plugin free and touch complete. Silverlight is out for mobile IE10, as is any sanctioned 3D.

There are also cosmetic differences that make desktop a compatibility version and mobile optimized for smaller form factors and touchy gestures. Bing Maps ajax v7 is slightly upgraded with a new Bing Theme module. As far as IE10 browsers, Bing Maps webapps using generic html5, css, jQuery Mobile with Bing Maps Ajax v7 will work with both IE10 branches and most any device, as well as avoiding Windows Store distribution.

Win8 Desktop – old stuff
Not much to say here. Everything I tried worked the same as usual. Bing Maps ajax v7, Bing Maps Silverlight, and Bing Maps WPF controls are all supported. Normal ClickOnce install works as before. VS2012 continues to evolve to accommodate Azure and mobile target platforms – ARM joins x86 and x64. Everything is familiar once you get to the desktop, but there can be some discovery process getting there.

Win8 Mobile – new stuff
A lot to explore here. – some media info on user experience for mobile Win8 Bing.

From a Bing Maps developer perspective there are again two paths. (Lots of dualism in the picture) ref Windows API for Metro apps
Both paths support distribution through the new Windows Store.

1) Bing Maps SDK for JavaScript – Windows 8 JavaScript API is the same as the existing Bing Maps ajax v7 API and makes transitions easy for existing ajax v7 map applications. Starting a project in VS2012 allows selection of a template with all the appropriate boilerplate. The map action is exactly the same as Bing Maps ajax v7 API.

Sample html for Bing Maps JavaScript SDK:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=1024, height=768" />
    <title>BingMaps-JavaScript-SDK</title>

    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0/js/base.js"></script>
    <script src="//Microsoft.WinJS.1.0/js/ui.js"></script>

    <!-- BingMaps-JavaScript-SDK references -->
    <script type="text/javascript" src="ms-appx:///Bing.Maps.JavaScript//js/veapicore.js"></script>
    <script type="text/javascript" src="ms-appx:///Bing.Maps.JavaScript//js/veapiModules.js"></script>

    <!-- application specific -->
    <link href="/css/default.css" rel="stylesheet">
    <script type="text/javascript"  src="/js/default.js"></script>

</head>
<body>
<div id="content">
    <div id="header"> </div>
    <div id="mapdiv"> </div>
 </div>
</body>
</html>

Fig 2 – Windows 8 JavaScript API sample

Javascript SDK event types are just the same as the existing ajax v7 API and do not include all the new sensor capabilities. However, the more interesting parts of Win8 are the multiple sensor support that requires Win8 Bing Maps SDK for Metro.

2) XAML Bing Maps control – This is the most comprehensive SDK with access to all core platform features. Bing Maps SDK for Metro style apps is still RTM Beta with final build due at the end of September. For the present Maps will be decorated with a large BETA band.

First there are some special Bing Map Keys available:

  1. Basic Windows Metro style app – Application is a Windows Metro style app that is publicly available without restriction and does not exceed 500,000 transactions of any type within a 12 month period.
  2. Enterprise Windows Metro style app – Application is a Windows Metro style app that is a public or a private application

The distinguishing capability in Bing Maps SDK for Metro style is access to sensors when available on a target platform:

Sensor classes:

  •  Accelerometer – This sensor returns G-force values with respect to the x, y, and z axes.
  • Compass – This sensor returns a heading with respect to True North and, possibly, Magnetic North.
  • Gyrometer – This sensor returns angular velocity values with respect to the x, y, and z axes
  • Inclinometer -This sensor returns pitch, roll, and yaw values that correspond to rotation angles around the x, y, and z axes, respectively.
  • LightSensor – This sensor returns the ambient-light reading as a LUX value.
  • OrientationSensor – This sensor returns a rotation matrix and a Quaternion that can be used to adjust the user’s perspective in a game application.
  • SimpleOrientationSensor – This sensor detects the current quadrant orientation of the specified device as well as its face-up or face-down status.

GeoLocation:
GPS is a subset of GeoLocation which can use fall back locations such as ip or WiFi triangulation as well as gps.

Fig 3 - Example GeoLocation lookup in Bing Maps SDK for C# .

Fig 4 Win8

Fig 4 – Win8 Bing Maps SDK Beta

Example XAML Page

<Page
    x:Class="BingMap1.MainPage"
    IsTabStop="false"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:BingMap1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:bm="using:Bing.Maps">

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="350" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <StackPanel Orientation="Vertical" VerticalAlignment="Top" HorizontalAlignment="Center">
            <Button x:Name="btn" Click="btnClicked" Content="Get Location" FontSize="26"/>
            <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                    </Grid.RowDefinitions>
                    <TextBlock TextWrapping="Wrap" Grid.Row="0" Grid.Column="0" Style="{StaticResource BasicTextStyle}" FontSize="24" HorizontalAlignment="Left" Text="Latitude: " />
                    <TextBlock TextWrapping="Wrap" Grid.Row="1" Grid.Column="0" Style="{StaticResource BasicTextStyle}" FontSize="24" HorizontalAlignment="Left" Text="Longitude: " />
                    <TextBlock TextWrapping="Wrap" Grid.Row="2" Grid.Column="0" Style="{StaticResource BasicTextStyle}" FontSize="24" HorizontalAlignment="Left" Text="Accuracy: " />
                    <TextBlock x:Name="ScenarioOutput_Latitude" TextWrapping="Wrap" Grid.Row="0" Grid.Column="1" Style="{StaticResource BasicTextStyle}" FontSize="24" HorizontalAlignment="Right" Text="No data" />
                    <TextBlock x:Name="ScenarioOutput_Longitude" TextWrapping="Wrap" Grid.Row="1" Grid.Column="1" Style="{StaticResource BasicTextStyle}" FontSize="24" HorizontalAlignment="Right" Text="No data" />
                    <TextBlock x:Name="ScenarioOutput_Accuracy" TextWrapping="Wrap" Grid.Row="2" Grid.Column="1" Style="{StaticResource BasicTextStyle}"  FontSize="24" HorizontalAlignment="Right" Text="No data" />
                </Grid>
            </Grid>
        </StackPanel>

        <bm:Map Grid.Column="1" x:Name="map" Width="Auto" Height="Auto" MapType="Road" ZoomLevel="12" Credentials="<Bing Key Here>" >
            <bm:Map.Center>
                <bm:Location Latitude="47.62" Longitude="-122.19" />
            </bm:Map.Center>
        </bm:Map>
    </Grid>
</Page>

C# code behind

using Bing.Maps;
using System;
using System.Threading;
using System.Threading.Tasks;
using Windows.Devices.Geolocation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace BingMap1
{

    public sealed partial class MainPage : Page
    {
        private Geolocator _geolocator = null;
        private CancellationTokenSource _cts = null;

        public MainPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            _geolocator = new Geolocator();
        }

        private void btnClicked(object sender, RoutedEventArgs e)
        {
            GetGeolocation(sender, e);
        }

        async private void GetGeolocation(object sender, RoutedEventArgs e)
        {
            try
            {
                _cts = new CancellationTokenSource();
                CancellationToken token = _cts.Token;

                Geoposition pos = await _geolocator.GetGeopositionAsync().AsTask(token);
		  // update text
                ScenarioOutput_Latitude.Text = pos.Coordinate.Latitude.ToString();
                ScenarioOutput_Longitude.Text = pos.Coordinate.Longitude.ToString();
                ScenarioOutput_Accuracy.Text = pos.Coordinate.Accuracy.ToString();
		   // update map location
                map.SetView(new Location(pos.Coordinate.Latitude, pos.Coordinate.Longitude), 12);
            }
            catch (System.UnauthorizedAccessException ue)
            {
                ScenarioOutput_Latitude.Text = "No data";
                ScenarioOutput_Longitude.Text = "No data";
                ScenarioOutput_Accuracy.Text = "No data";
            }
            catch (TaskCanceledException te)
            {
            }
            finally
            {
                _cts = null;
            }
        }
    }
}

Fig 5 – Metro style tiles including the above BingMaps1 project

Fig 6 – Win8 Bing Maps SDK with GeoLocation and BirdsEye view

Distribution
The Windows Store is a prominent tile in the Start page. Win8 applications are vetted through a Microsoft analysis and certification process before distribution through the public Windows Store. Of course any app created in VS2012 is available as a tile in the Start Page of the development system, but getting an app to clients happens through the Windows Store. Enterprise LOB applications do have a SideLoading process to bypass the public Windows Store.

Fig 7 – Windows Store for Win8 app delivery (Sideloading is possible for Enterprise licensees)

Summary
At present Win8 is still a future affair. Developers can play, while consumers wait. Microsoft dominance of desktops will guarantee a desktop market going forward. Since neither phone nor tablet will be available to consumers with Win8 until later 4th quarter, Win8 is an OS focused on devices that may or may not generate a market. The risk is alienating a relatively loyal base of desktop users in the hope of gaining traction in the fast growing mobile market. Without a market, developers will not devote much effort to all the new stuff.

Win8 is a “do or die” gambit for Balmer, Sinofsky, and friends. Mobile is moving fast and Microsoft’s future in mobile remains in serious question. If the mobile market is entirely lost, Microsoft is headed toward a long slow Gibbonesqe decline. However, Win8 is potentially the lever required to pry Microsoft into at least a place at the mobile table. We won’t know much for a few more quarters. In the meantime steep learning curves ahead for Bing Maps devs.

Fig 8 - NASA Avg Day Temperatures over past month