×
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)
(Ltuska -)
ltuska (Talk | contribs)
(Ltuska -)
Line 6: Line 6:
 
== Motivation ==
 
== 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 [http://msdn.microsoft.com/en-US/library/windowsphone/develop/jj207045(v=vs.105).aspx 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.''
 
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 [http://msdn.microsoft.com/en-US/library/windowsphone/develop/jj207045(v=vs.105).aspx 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.''
 +
 
I found this new feature very interesting and expected that soon the maps will be "rotatable". In the end it turned out that this feature is somehow not really popular, I've never seen any applications providing this feature.  
 
I found this new feature very interesting and expected that soon the maps will be "rotatable". In the end it turned out that this feature is somehow not really popular, I've never seen any applications providing this feature.  
 +
 
Another reason to pick this topic it that I think there should be a lot more applications out there using multiple touch points. I was curious how simple it is to develop an app which can handle the multiple touches simultaneously.  
 
Another reason to pick this topic it that I think there should be a lot more applications out there using multiple touch points. I was curious how simple it is to develop an app which can handle the multiple touches simultaneously.  
 +
 
The third one, which made me write this article, is the competition and the prices offered. :-)
 
The third one, which made me write this article, is the competition and the prices offered. :-)
  
 
== Preparation ==
 
== Preparation ==
 
In this section I list some of the new features of the new Maps API, then describe the steps to set up the development environment in order to be able to test multi touch in the emulator and finally show the "theoretical" method, which will work for most of the UIElement objects, but unfortunately doesn't work for the Map control.  
 
In this section I list some of the new features of the new Maps API, then describe the steps to set up the development environment in order to be able to test multi touch in the emulator and finally show the "theoretical" method, which will work for most of the UIElement objects, but unfortunately doesn't work for the Map control.  
 +
 
If you already own a Windows Phone 8 device and you are only curious about the map rotation, scroll to the "Solution" part.
 
If you already own a Windows Phone 8 device and you are only curious about the map rotation, scroll to the "Solution" part.
  
Line 83: Line 87:
 
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.
 
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):
+
Finally, the method to calculate the angle between the point sets (the formula can be found on the internet, it is basic trigonometry):
 
<code csharp>
 
<code csharp>
 
         public static double angleBetween2Lines(PinchContactPoints line1, PinchContactPoints line2)
 
         public static double angleBetween2Lines(PinchContactPoints line1, PinchContactPoints line2)
Line 99: Line 103:
 
</code>
 
</code>
  
With these changes, I am able to rotate my rectangle by "pinching" the emulator display:
+
With these changes, I am able to rotate my rectangle by "pinching" and rotating the emulator display:
  
 
[[File:multitouch_demo.png]]
 
[[File:multitouch_demo.png]]
Line 123: Line 127:
 
             InitializeComponent();
 
             InitializeComponent();
 
             // This is the only line I need to add, the rest is from the sample app from the SDK
 
             // This is the only line I need to add, the rest is from the sample app from the SDK
             rotationHelper = new RotationHelper(ContentPanel, sampleMap);
+
             rotationHelper = new RotationHelper(sampleMap);
  
 
             // Create the localized ApplicationBar.
 
             // Create the localized ApplicationBar.
Line 137: Line 141:
  
 
<code csharp>
 
<code csharp>
         public RotationHelper(UIElement touchArea, Map rotatedMap)
+
         public RotationHelper(Map rotatedMap)
 
         {
 
         {
            this.touchTarget = touchArea;
 
 
             this.rotatedMap = rotatedMap;
 
             this.rotatedMap = rotatedMap;
  
Line 153: Line 156:
 
             bool moveOccurred = false;
 
             bool moveOccurred = false;
 
             // this array contains all available touch devices, i.e. finger coordinates
 
             // this array contains all available touch devices, i.e. finger coordinates
             var pts = e.GetTouchPoints(touchTarget);
+
             var pts = e.GetTouchPoints(rotatedMap);
  
 
             foreach (TouchPoint p in pts)
 
             foreach (TouchPoint p in pts)
Line 210: Line 213:
 
</code>
 
</code>
  
Please note the SetView function, which is used to update the map behavior on the fly. For the different options, you should check [http://msdn.microsoft.com/en-us/library/windowsphone/develop/microsoft.phone.maps.controls.map(v=vs.105).aspx the Map class documentation]. 10 overloaded methods are defined.
+
Please note the SetView function, which is used to update the map behavior on the fly. For the different options, you should check [http://msdn.microsoft.com/en-us/library/windowsphone/develop/microsoft.phone.maps.controls.map(v=vs.105).aspx the Map class documentation] (10 overloaded methods!).  
  
In this example, I only define a new Heading for the map, with the map's current zoom level and the animation type "Parabolic".
+
In this example, I define only a new Heading for the map plus the animation type "Parabolic", leaving the map's current center and zoom level unchanged.
  
 
The test in the emulator looks like this:
 
The test in the emulator looks like this:
Line 222: Line 225:
  
 
Keep in mind that the FrameReported event is known-to-be a performance killer, so use it with care (just check the "App performance considerations" article listed below). Hopefully we don't need to wait too much and the element itself will provide this option for all location-based app developers.
 
Keep in mind that the FrameReported event is known-to-be a performance killer, so use it with care (just check the "App performance considerations" article listed below). Hopefully we don't need to wait too much and the element itself will provide this option for all location-based app developers.
 +
 
Thanks for reading!
 
Thanks for reading!
  

Revision as of 00:14, 10 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.

I found this new feature very interesting and expected that soon the maps will be "rotatable". In the end it turned out that this feature is somehow not really popular, I've never seen any applications providing this feature.

Another reason to pick this topic it that I think there should be a lot more applications out there using multiple touch points. I was curious how simple it is to develop an app which can handle the multiple touches simultaneously.

The third one, which made me write this article, is the competition and the prices offered. :-)

Preparation

In this section I list some of the new features of the new Maps API, then describe the steps to set up the development environment in order to be able to test multi touch in the emulator and finally show the "theoretical" method, which will work for most of the UIElement objects, but unfortunately doesn't work for the Map control.

If you already own a Windows Phone 8 device and you are only curious about the map rotation, scroll to the "Solution" part.

New features in Windows Phone 8 Maps API

Here are just a few new features of 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
  • "forcing" custom-style pushpins

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.

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.

How to test multi touch in the emulator

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 on Windows 8 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)

After successful installation, services.msc should report the Multitouch driver under services:

The multi touch service installed as Windows service.

Start the service and set the configuration.

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

It will take some time to get used to it. ;-)

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();
// I removed scale and move transform, as they were out-of-scope for me
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, it is basic trigonometry):

        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 0.0; }
}

With these changes, I am able to rotate my rectangle by "pinching" and rotating 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 coordinates: one defining the base line and one for 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 points" (finger coordinates) in a map (Dictionary). As soon as I register the second finger's position (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 coordinates and the current ones as System.Windows.Shapes.Line objects (the touch points of the two fingers define a line).

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 code as follows:

Step 1 Registering the event handler:

        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(sampleMap);
 
// Create the localized ApplicationBar.
BuildLocalizedApplicationBar();
 
// Get current location.
sampleMap.ZoomLevel = 10;
GetLocation();
}

The event handler logic is implemented in a helper class:

        public RotationHelper(Map rotatedMap)
{
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(rotatedMap);
 
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!).

In this example, I define only a new Heading for the map plus the animation type "Parabolic", leaving the map's current center and zoom level unchanged.

The test in the emulator looks like this:

Multitouch map1.pngMultitouch map2.png

Conclusion

In this short tutorial I presented you a method to rotate almost any type of UIElement object in your Silverlight application based on multi-touch user input, and also shown how to do the same with the Maps control element introduced in Windows Phone 8. I hope you can reuse some lines of my code in your application and create more and more use of it. If you find any place for further "optimization", or you find any problem with the code, or you should have any questions regarding it, please add a comment to the page.

Keep in mind that the FrameReported event is known-to-be a performance killer, so use it with care (just check the "App performance considerations" article listed below). Hopefully we don't need to wait too much and the element itself will provide this option for all location-based app developers.

Thanks for reading!

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!

First of all, the test projects: File:Basic UIElement rotation.zip, File:Map control rotation.zip Please note, that I'm "just" a java developer, so don't expect 100% clean C# code...

Tools, articles, documentation I used while working on this "project":

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 (10 Dec 2012)
416 page views in the last 30 days.
×