×
Namespaces

Variants
Actions
(Difference between revisions)

Real-time rotation of the Windows Phone 8 Map Control

From Nokia Developer Wiki
Jump to: navigation, search
ltuska (Talk | contribs)
m (Ltuska - - References)
ltuska (Talk | contribs)
m (Ltuska - - New features in Windows Phone 8 Maps API)
Line 16: Line 16:
 
* Background task support for location tracking applications
 
* Background task support for location tracking applications
  
{{Tip|For a comprehensive introduction to the new capabilities of the Location API, watch [http://channel9.msdn.com/posts/Building-Apps-for-Windows-Phone-8-Jump-Start-14-Maps-and-Location-in-Windows-Phone-8 this excellent video from channel 9].}}
+
{{Tip|For a comprehensive introduction to the new capabilities of the Location API, watch [http://channel9.msdn.com/posts/Building-Apps-for-Windows-Phone-8-Jump-Start-14-Maps-and-Location-in-Windows-Phone-8 this excellent video from channel 9] presented by Microsoft Technical Evangelist Andy Wigley.}}
  
 
Since these features are covered quite well in various tutorials in the internet, in this article I will concentrate only on the map view setting feature.
 
Since these features are covered quite well in various tutorials in the internet, in this article I will concentrate only on the map view setting feature.

Revision as of 21:20, 9 December 2012


This article explains how to rotate the Windows Phone 8 Map Control object real-time. The provided solution uses the Touch class to react on FrameReported events. It also shows a relatively simple way to test multi touch behavior using the Windows Phone 8 emulator.

Note.pngNote: This is an "internal" entry in the Windows Phone 8 Wiki Competition 2012Q4. The author is a Nokia / Microsoft employee.

Contents

Motivation

Windows Phone 8 comes with a new Maps framework, and provides extended functionality compared to the Windows Phone 7.1 Maps components. One of these new features is that the developer can set the "Heading" property of the Map control. This property is described on the Maps and navigation for Windows Phone 8 page as: This parameter specifies the directional heading that is pointing “up” on the map. It is represented in geometric degrees by a value that is between 0 and 360, indicating the number of degrees to rotate the map.

Preparation

New features in Windows Phone 8 Maps API

Here are just a few new features for the Location framework I found interesting:

  • Improved ability for one-shot location acquisition
  • Map control, Map tasks can make use of the downloaded offline maps (no data connection required)
  • Background task support for location tracking applications

Tip.pngTip: For a comprehensive introduction to the new capabilities of the Location API, watch this excellent video from channel 9 presented by Microsoft Technical Evangelist Andy Wigley.

Since these features are covered quite well in various tutorials in the internet, in this article I will concentrate only on the map view setting feature.

How to test multi touch in the emulator

But before we could start to work on our problem, we have to come over an obstacle: what if you (like me) doesn't have the hardware to test multi touch events on a real device. Luckily there is help on the internet. The Multi-Touch Vista project on codeplex provides a Windows service which emulates a touch screen, with multiple touch points (at least if you happen to have at least 2 pointing devices).

To install this service, follow the steps from the download page.

Note The driver worked for me correctly only when I installed it as a Windows service. Make sure to block the native Windows mouse input in the configuration utility (Multitouch.Configuration.WPF.exe)

The multi touch service installed as Windows service.


The configuration tool with the blocking native mouse option. The red dots represent my two usb mice connected to the computer.

How the easy way should look like...

At this point we are ready to implement our Windows Phone app with multi-touch. For this, I have created a basic sample app, following the instructions from the How to handle manipulation events for Windows Phone msdn page.

The idea was simple, I assign a RotateTransform object to my rectangle, and catch the PinchManipulation event's contact points' location. When the event starts (i.e. two fingers touch the display), I save the initial points as the base line, then on every manipulation delta, I compute the angle between the original line and the current line.

Initialization:

        public MainPage()
{
InitializeComponent();
 
this.ManipulationDelta += this.PhoneApplicationPage_ManipulationDelta;
this.ManipulationCompleted += this.PhoneApplicationPage_ManipulationCompleted;
 
TransformGroup transformGroup = new TransformGroup();
this.rotate = new RotateTransform();
 
transformGroup.Children.Add(this.rotate);
rectangle.RenderTransform = transformGroup;
}

The manipulation handler methods:

        private void PhoneApplicationPage_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
{
lastAngle = this.rotate.Angle;
}
 
void PhoneApplicationPage_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
if (e.PinchManipulation != null)
{
double angle = angleBetween2Lines(e.PinchManipulation.Original, e.PinchManipulation.Current);
this.rotate.Angle = lastAngle-angle;
}
}

I store the last angle in a separate field, in order to know where to start from when the user decides to rotate the object once again. Otherwise it would always "jump" back to its original position, because initially the difference between the base and current lines is 0.

Finally, the method to calculate the angle between the point sets (the formula can be found on the internet):

        public static double angleBetween2Lines(PinchContactPoints line1, PinchContactPoints line2)
{
if (line1 != null && line2 != null)
{
double angle1 = Math.Atan2(line1.PrimaryContact.Y - line1.SecondaryContact.Y,
line1.PrimaryContact.X - line1.SecondaryContact.X);
double angle2 = Math.Atan2(line2.PrimaryContact.Y - line2.SecondaryContact.Y,
line2.PrimaryContact.X - line2.SecondaryContact.X);
return (angle1 - angle2) * 180 / Math.PI;
}
else { return Double.NaN; }
}

With these changes, I am able to rotate my rectangle by "pinching" the emulator display:

Multitouch demo.png

Tip.pngTip: This simple method can be applied to any type of UIElement objects supporting Manipulation events. Try out to move the name tag to the "page name" text's object in the xaml code. The rotation will be applied on this text without any modification in the C# code.

Unfortunately, this method can't be applied to the Map Control object. I guess the manipulation is marked as completed as soon as the zoom value is calculated and set. So to achieve my goal, I needed to dig a bit deeper...

The solution

To calculate the "delta angle", I need two set of base coordinates. A base line and the updated one. The .Net API for Windows Phone provides an application-level service that processes touch input from the operating system and raises the Windows Phone-specific FrameReported event. The class is called Touch.

I will catch the FrameReported events and store the first two "touch devices" (fingers) in a map (Dictionary). As soon as I register the second finger (TouchAction.Down event), I calculate the base line, and keep it until both fingers are moving (TouchAction.Move). My custom manipulation is ending when one of the fingers report a TouchAction.Up event. To make my life easier I save the start line and the current one as System.Windows.Shapes.Line objects.

In the "move" phase, I simply use the slightly-modified version of the angleBetween2Lines function to calculate the angle and apply the calculated value to the map object. The rotate center is the center of the map at the point of the start of the event.

For the demonstration I used the Simple Map Control Sample from msdn. I extended the sample code as follows:

Step 1 Registering the event handler: I put the logic in a separate class to ease reusability.

        public MainPage()
{
InitializeComponent();
// This is the only line I need to add, the rest is from the sample app from the SDK
rotationHelper = new RotationHelper(ContentPanel, sampleMap);
 
// Create the localized ApplicationBar.
BuildLocalizedApplicationBar();
 
// Get current location.
sampleMap.ZoomLevel = 10;
GetLocation();
}

The constructor of the helper class:

        public RotationHelper(UIElement touchArea, Map rotatedMap)
{
this.touchTarget = touchArea;
this.rotatedMap = rotatedMap;
 
Touch.FrameReported += this.Touch_FrameReported;
}

Step 2 Handling the FrameReported event:

        public void Touch_FrameReported(object sender, TouchFrameEventArgs e)
{
bool moveOccurred = false;
// this array contains all available touch devices, i.e. finger coordinates
var pts = e.GetTouchPoints(touchTarget);
 
foreach (TouchPoint p in pts)
{
if (p.Action == TouchAction.Down)
{
// I save the touch points into the startTouchPoints and deltaTouchPoints dictionaries
if (!startTouchPoints.ContainsKey(p.TouchDevice.Id))
{
startTouchPoints.Add(p.TouchDevice.Id, p);
deltaTouchPoints.Add(p.TouchDevice.Id, p);
}
// if I happen to have the second touch point, I save the base line and rotation center
if (startTouchPoints.Count > 1)
{
startLine = calculateLine(startTouchPoints);
Debug.WriteLine("Start line set to: {0:f}, {1:f}, {2:f}, {3:f}", startLine.X1, startLine.Y1, startLine.X2, startLine.Y2);
rotateCenter = this.rotatedMap.Center;
}
}
else if (p.Action == TouchAction.Move)
{
TouchPoint oldPositionTouchpoint;
// updating the touchpoints set
if (deltaTouchPoints.TryGetValue(p.TouchDevice.Id, out oldPositionTouchpoint))
{
deltaTouchPoints[p.TouchDevice.Id] = p;
}
// if we are already rotating, update the deltaLine
if (deltaTouchPoints.Count == 2)
{
deltaLine = calculateLine(deltaTouchPoints);
Debug.WriteLine("Delta line set to: {0:f}, {1:f}, {2:f}, {3:f}", deltaLine.X1, deltaLine.Y1, deltaLine.X2, deltaLine.Y2);
moveOccurred = true;
}
}
// if the user lifts up one finger, we abort the manipulation and reset the values
else if (p.Action == TouchAction.Up)
{
startTouchPoints.Remove(p.TouchDevice.Id);
deltaTouchPoints.Remove(p.TouchDevice.Id);
startLine = null;
deltaLine = null;
moveOccurred = false;
this.lastSavedAngle = this.rotatedMap.Heading;
}
}
// if we are in a move action, we should update the map
if (moveOccurred)
{
double angle = angleBetween2Lines(startLine, deltaLine);
Debug.WriteLine("Angle difference to startline: " + angle);
this.rotatedMap.SetView(rotateCenter, this.rotatedMap.ZoomLevel, lastSavedAngle + angle, MapAnimationKind.Parabolic);
}
}

Please note the SetView function, which is used to update the map behavior on the fly. For the different options, you should check the Map class documentation. 10 overloaded methods are defined.

The test in the emulator looks like this:

Multitouch map.png

Conclusion

Useful links

Although I was trying to link all external pages to my article, here are once again those which I found to be the most useful, extended by some "extra", which I can really recommend to check out.

Have fun!

Windows Phone Multi-Touch Manipulation

How to handle manipulation events for Windows Phone

Building Apps for Windows Phone 8 Jump Start

Building Apps for Windows Phone 8 Jump Start-Maps and Location in Windows Phone 8

App performance considerations for Windows Phone

Windows Phone 8 Maps Control API

Touch class

FrameReported event

SignpostIcon HereMaps 99.png
SignpostIcon XAML 40.png
WP Metro Icon WP8.png
Article Metadata
Compatibility
Platform(s): Windows Phone 8
Windows Phone 8
Article
Keywords: manipulation touch map control
Created: ltuska (09 Dec 2012)
Last edited: ltuska (09 Dec 2012)
474 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×