Windows Support Number

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Sunday, 16 October 2011

Drawing shapes on top of Bing Maps in a WP7 app

Posted on 11:54 by Unknown
Before I complete the 'How many pins can Bing Maps handle in a WP7 app...' set of posts. I wanted to show how I'm drawing shapes on top of the Bing Maps control in WP7. This is based around using the MapPolygon class in the Microsoft.Phone.Controls.Maps namespace, more info on MSDN. Basically this will drawn lines betweens the geo-locations defined in the collection exposed by the Locations property. You're also able to define other properties such as fill colour, stroke thinkness, opacity. With these you have the ability to really customize any polygon you render over the map control.

I'm going to show how I achieved the following screen shots and how this is all based around using the well known Haversine formula with only the centre location of the visible bounding rectangle of the Bing Maps control:


A couple of things to note, UI design is not my forte (as @RichGee will tell you) so the following is more about how to achieve it than what it finally looks like and secondly I'm using the Haversine formula to calculate geo-locations. This formula is not the most accurate available, but for my purposes the 0.3% error factor is acceptable. 'Movable Type' has a great page about lat & long formulas and calculations, more info here.

I've used MVVM pattern for this app so therefore I have a set of Model classes that are bounded to the View via the ViewModel. The app only has 1 View, 1 ViewModel and 1 Model class but the Model class uses both object orientated and functional techniques to achieve what I wanted.

The View has the map control and polygon defined  in XAML as follows:

As you can see the map Centre property is bound to the ViewModel and the Locations property of the MapPolygon is bound to the Polygon geo-locations collection on the ViewModel.

The Shape Model class defines a couple of properties, one for the shape name and the second a function for calculating the geo-locations used to describe the polygon (shape). This is a function delegate because the geo-locations are generated dynamically at runtime and this depends on the current centre location of the map control.

public sealed class Shape : BaseModel
{
private string name;
private Func<GeoCoordinate, LocationCollection> polygonFunc;

public string Name
{
get
{
return this.name;
}
set
{
this.SetPropertyAndNotify(ref this.name, value, () => this.Name);
}
}

public Func<GeoCoordinate, LocationCollection> PolygonFunc
{
get
{
return this.polygonFunc;
}

set
{
this.SetPropertyAndNotify(ref this.polygonFunc, value, () => this.PolygonFunc);
}
}
}

Instances of this Model are populated in the ViewModel constructor using a set of static methods on a helper class. This helper class is where the smarts for calculating polygons is contained. As you can see from the code below I've created several different shapes in different sizes.

public MapViewModel(ILog log)
{
this.log = log;

this.polygon = new LocationCollection();
this.Centre = new GeoCoordinate(51.561811605968394, -0.0883626937866211);
this.Zoom = 15;

this.shapes = new ObservableCollection<Shape>
{
new Shape { Name = "No Shape", PolygonFunc = centre => new LocationCollection()},
new Shape { Name = "Square (50 m)", PolygonFunc = MapFuncs.Square(0.050) },
new Shape { Name = "Square (250 m)", PolygonFunc = MapFuncs.Square(0.250) },
new Shape { Name = "Square (500 m)", PolygonFunc = MapFuncs.Square(0.500) },
new Shape { Name = "Circle (50 m)", PolygonFunc = MapFuncs.Circle(0.050) },
new Shape { Name = "Circle (250 m)", PolygonFunc = MapFuncs.Circle(0.250) },
new Shape { Name = "Circle (500 m)", PolygonFunc = MapFuncs.Circle(0.500) },
new Shape { Name = "Pentangle (500 m)", PolygonFunc = MapFuncs.Pentangle(0.500) },
new Shape { Name = "Star (5 points)", PolygonFunc = MapFuncs.Star(5, 0.500) },
new Shape { Name = "Star (6 points)", PolygonFunc = MapFuncs.Star(6, 0.500) },
new Shape { Name = "Star (7 points)", PolygonFunc = MapFuncs.Star(7, 0.500) },
new Shape { Name = "Star (8 points)", PolygonFunc = MapFuncs.Star(8, 0.500) },
new Shape { Name = "Star (9 points)", PolygonFunc = MapFuncs.Star(9, 0.500) },
new Shape { Name = "Star (10 points)", PolygonFunc = MapFuncs.Star(10, 0.500) },
new Shape { Name = "Polygon (4 sides)", PolygonFunc = MapFuncs.Polygon(4, 0.500) },
new Shape { Name = "Polygon (5 sides)", PolygonFunc = MapFuncs.Polygon(5, 0.500) },
new Shape { Name = "Polygon (5 sides, offset)", PolygonFunc = MapFuncs.Polygon(5, 0.500, 36) },
new Shape { Name = "Polygon (6 sides)", PolygonFunc = MapFuncs.Polygon(6, 0.500) },
new Shape { Name = "Polygon (7 sides)", PolygonFunc = MapFuncs.Polygon(7, 0.500) },
new Shape { Name = "Polygon (8 sides)", PolygonFunc = MapFuncs.Polygon(8, 0.500) },
new Shape { Name = "Polygon (9 sides)", PolygonFunc = MapFuncs.Polygon(9, 0.500) },
new Shape { Name = "Polygon (10 sides)", PolygonFunc = MapFuncs.Polygon(10, 0.500) }
};

this.SelectedShape = this.shapes.First();
}

This collection of Shapes is then bound to the View via the Shapes property on the ViewModel. The View uses this as part of ListPicker to allow the user to select the current Shape. When a Shape is selected the ViewModel raises a property notify changed event to indicate the currently selected Shape should be re-drawn. The important part is the static class MapFuncs, this is where the smarts are. It uses the Haversine formula to calculate the polygons. The Haversine method is shown below along with a couple of hepler methods for converting degrees to and from radians. The Haversine formula calculates the geo-location given a start geo-location, distance and bearing on a sphere, the sphere in case is the Earth:

private static GeoCoordinate CalculateUsingHaversine(GeoCoordinate startLocation, double distance, double bearing)
{
var lat1 = DegreeToRadian(startLocation.Latitude);
var long1 = DegreeToRadian(startLocation.Longitude);

var bar1 = DegreeToRadian(bearing);
var angularDistance = distance / EarthRadius;

var lat2 = Math.Asin(Math.Sin(lat1) * Math.Cos(angularDistance) + Math.Cos(lat1) * Math.Sin(angularDistance) * Math.Cos(bar1));

var lon2 = long1 + Math.Atan2(Math.Sin(bar1) * Math.Sin(angularDistance) * Math.Cos(lat1),
Math.Cos(angularDistance) - Math.Sin(lat1) * Math.Sin(lat2));


var destinationLocation = new GeoCoordinate(RadianToDegree(lat2), RadianToDegree(lon2));

return destinationLocation;
}

private static double DegreeToRadian(double angle)
{
return Math.PI * angle / 180.0;
}

private static double RadianToDegree(double angle)
{
return angle * (180.0 / Math.PI);
}

As I said earlier, the formula is then used to calculate the geo-locations which describe the required polygon (shape).

Method for creating polygon describing a Circle:

public static Func<GeoCoordinate, LocationCollection> Circle(double diameter)
{
var radius = diameter / 2;
Func<GeoCoordinate, LocationCollection> func = location =>
{
var locations = new LocationCollection();

// Calculate the the location for each degree of a circle...
for (var i = 0; i < 360; i++)
{
locations.Add(MapFuncs.CalculateUsingHaversine(location, radius, i));
}

return locations;
};

return func;
}


Method for creating polygon describing a Square:

public static Func<GeoCoordinate, LocationCollection> Square(double length)
{
Func<GeoCoordinate, LocationCollection> func = location =>
{
var locations = new LocationCollection();

// Calculate the mid points of the square...
var halfLength = length / 2;
var north = CalculateUsingHaversine(location, halfLength, 0);
var south = CalculateUsingHaversine(location, halfLength, 180);
var east = CalculateUsingHaversine(location, halfLength, 90);
var west = CalculateUsingHaversine(location, halfLength, 270);

// Use the mid points to calculate the corners of the square...
locations.Add(new GeoCoordinate(north.Latitude, west.Longitude));
locations.Add(new GeoCoordinate(north.Latitude, east.Longitude));
locations.Add(new GeoCoordinate(south.Latitude, east.Longitude));
locations.Add(new GeoCoordinate(south.Latitude, west.Longitude));

return locations;
};

return func;
}


Method for creating any polygon, e.g. hexagon, heptagon, octagon etc:

public static Func<GeoCoordinate, LocationCollection> Polygon(int sides, double diameter, double startAngle)
{
Func<GeoCoordinate, LocationCollection> func = location =>
{
var locations = new LocationCollection();

var radius = diameter / 2;
var angle = 360.00 / sides;

for (var i = 0; i < sides; i++)
{
var aggregatedAngle = (i*angle) + startAngle;
locations.Add(CalculateUsingHaversine(location, radius, aggregatedAngle));
}

return locations;
};

return func;
}



The following 2 are the most interesting, they are also the most complicated - Star & Pentangle (pentagram). The method for creating a Star polygon allows the number of points to be defined as well as the diameter (size). The Pentangle is a special case of a Star, it gives you a more natural looking star image. Wikipedia describes a pentagram as 'the shape of a five-pointed star drawn with five straight strokes.'

The difference between two is essential the ratio between the inner and outer points of the star - I'm sure there is a technical term for this but I'm not aware of the name. For the following Star polygons I've a ratio of 2/3 and for the Pentangle I've used 8/17 - this give the distinctive Pentangle shape:



Method for creating a Star polygon:

public static Func<GeoCoordinate, LocationCollection> Star(int sides, double diameter)
{
return Star(sides, diameter, 0);
}

public static Func<GeoCoordinate, LocationCollection> Star(int sides, double diameter, double startAngle)
{
return Star(sides, diameter, startAngle, ((double)2)/3);
}

private static Func<GeoCoordinate, LocationCollection> Star(int sides, double diameter, double startAngle, double ratio)
{
Func<GeoCoordinate, LocationCollection> func = location =>
{
var locations = new LocationCollection();

var outerPoints = new LocationCollection();

// Calculate the outer points, these lie on the circumference of the circle
// described by the diameter...
var radius = diameter / 2;
var angle = 360.00 / sides;
for (var i = 0; i < sides; i++)
{
var aggregatedAngle = (i * angle) + startAngle;
outerPoints.Add(CalculateUsingHaversine(location, radius, aggregatedAngle));
}

// Distance between 2 outer points...
var distance = (outerPoints[0].GetDistanceTo(outerPoints[1])) / 1000;
var side = Math.Sqrt((radius * radius) - ((distance / 2) * (distance / 2)));

// Calculate the inner points and combine with outer points...
var halfAngle = angle / 2;
for (var i = 0; i < sides; i++)
{
var aggregatedAngle = (i * angle) + (startAngle + halfAngle);
var point = CalculateUsingHaversine(location, (side * ratio), aggregatedAngle);

locations.Add(outerPoints[i]);
locations.Add(point);
}

return locations;
};

return func;
}



Method for creating a Pentangle polygon:

public static Func<GeoCoordinate, LocationCollection> Pentangle(double diameter)
{
return Star(5, diameter, 0, ((double)8)/17);
}



I included a couple of memory counters at the bottom of the demo app to observe the memory consumption when rendering polygons onto the map control. After showing 10 polygons on the map and then removing  the polygon the following memory usage was observed. I was a little surprised by the increase of over 14 Mb in peak memory usage. I could see there being issues when rendering multiple polygons on the map control.


Removing the polygon from the map control was also not as straight forward as expected.  I had to use the same pattern as described in this post. Clearing the contents of the geo-locations collection did not work, I had to clear it then add a single value back into the collection. I ended up with the following functionality:

public LocationCollection Polygon
{
get
{
this.polygon.Clear();
this.BuildPolygon().ForEach(this.polygon.Add);

// If the 'no shape' is selected we need to force the polygon to be removed
// this is done by adding a point, in this case the centre location.
if (this.polygon.Count() == 0)
{
this.polygon.Add(this.centre);
}

return this.polygon;
}
}

The code makes use of the WP7Contrib for the base class for the ViewModel & Model classes and is referenced as an NuGet packages. The code for this demo app is available on SkyDrive.



Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Posted in WP7 WP7Contrib Bing Maps Polygon Development | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Unit testing Rx methods Timeout & Retry with moq
    Earlier this week I was trying to unit test an asynchronous service (Foo) which used another asynchronous service (Bar) internally and ran i...
  • Understanding RefCount in Reactive Extensions
    A couple of weeks ago  @LordHanson  & I ran into an issue converting a stateless async service exposed as an Rx cold observable to a  co...
  • StructureMap: ILifecycle
    The other day I wanted to control the scope of a service inside a web based app with semantics which didn't fit either 'HttpContextS...
  • MVVM anti-pattern: Injecting the IoC container into a View Model
    This is another anti-pattern I've seen a lot recently, the dynamic use of the IoC container inside a view model to resolve child view mo...
  • How many pins can Bing Maps handle in a WP7 app - part 1
    part2 -  http://awkwardcoder.blogspot.com/2011/10/how-many-pins-can-bing-maps-handle-in.html part3 -  http://awkwardcoder.blogspot.com/2011/...
  • Bad developers love 'The Daily WTF'
    When 'The Daily WTF' started up back in 2003/2004 it was a great laugh looking at shocking code other developers wrote, but after a ...
  • Using CompositeDisposable in base classes
    To help make an object eligible for collection by the GC (garbage collector) one would implement the IDisposable interface. Executing the di...
  • Implementing a busy indicator using a visual overlay in MVVM
    This is a technique we use at work to lock the UI whilst some long running process is happening - preventing the user clicking on stuff whil...
  • Daily Dilbert Service - the most important service I've ever written...
    NuGet package available here ... First off a big shout to  @hamish  &  @leeoades  on this one - I'm just blogging about it. At work ...
  • Comparing performance of .Net 4.5 to .Net 4.0 for WPF
    Currently I'm working on a .Net 4.0 WPF app and we've had some discussion about moving to .Net 4.5, we don't get to make the dec...

Categories

  • .Net
  • .Net 4.5
  • Abstractions
  • Advertising
  • Agile
  • Agile Courage
  • AOP
  • Async
  • automated testing
  • Azure
  • Azure IIS RESTful development
  • BDD
  • Bing Maps
  • Bounded Context
  • C#
  • C# 5.0
  • Caching
  • Chocolatey
  • CLoud
  • CodePlex
  • Coding
  • Coding Building CI Testing
  • Coding C#
  • coding C# IoC StructureMap
  • Coding Functional-Programming
  • Coding REST Knowledge
  • Coding Services
  • Coding TDD Refactoring Agile
  • Command
  • continuous testing
  • coupling
  • CultureInfo
  • DAL
  • databases
  • DDD
  • DDD Coaching
  • DDD Domain Events Auditing nHibernate
  • DDD Entities Value Objects
  • Debugging
  • Design Patterns
  • Design Patterns Databases Auditing
  • Developement
  • Development
  • Development Coding
  • Development Process
  • Development unit testing
  • Development VS 2011
  • Diagnostics
  • Disposable
  • Exceptions
  • FINDaPAD
  • FindaPad Property Rental Windows Phone 7 Mobile Devices
  • Fun Coding Duct-Tape
  • Hotfixes
  • integration testing
  • IoC
  • jasmine
  • javascript
  • Jobs Development
  • LINQ
  • marketplace
  • Mobile Devices
  • Mocking
  • MSDN Coding
  • MSpec
  • Multilingual
  • MVC
  • MVVM
  • nCrunch
  • nHbiernate Repository Pattern Criteria
  • nHibernate Auditing Design Fluent
  • nHibnerate Entities Events Listeners
  • node.js
  • nodes.js
  • Nokia
  • NoSQL RavenDB Azure Development
  • Observations
  • OO
  • ORM
  • Performance
  • Portable Class Library
  • Portable Library
  • PostSharp
  • Process
  • Rants
  • RavenDB IIS 7.5 Development
  • Reactive
  • Reactive Extension
  • Reactive Extensions
  • ReadOnlyCollections
  • Resharper
  • REST Distributed-Systems
  • REST HTTP
  • rest web
  • RESTful
  • Rx
  • Serialization
  • Silverlight
  • Silverlight Installation
  • Task
  • TDD
  • TDD IoC DI
  • TDD Mocking
  • TDD Team Observation
  • Telerik
  • testing
  • threading
  • TPL
  • UI
  • Undo-Redo
  • unit testing
  • ViewModels
  • VS 2012
  • wcf
  • web api
  • Web Services
  • web services mobile devices data
  • WebAPI
  • Windows
  • Windows 8
  • windows phone
  • Windows Phone 7
  • WP7
  • WP7 Bing Maps Development Network HTTP
  • WP7 Bing Maps Development UK Crime
  • WP7 Bing Maps Development UK Crime Clustering
  • WP7 Bing Maps Development UK Polygons Clustering Performance
  • WP7 cryptography bouncy castle
  • WP7 Cultures C#
  • WP7 feedback development app store
  • WP7 Javascript web browser
  • WP7 MSBuild
  • WP7 ORM Databases performance
  • WP7 Serialisation
  • WP7 SilverlightSerializer C#
  • WP7 sqlite performance development
  • WP7 WP7Contrib Bing Maps Development
  • WP7 WP7Contrib Bing Maps Polygon Development
  • WP7 WP7Contrib CodePlex
  • WP7 WP7Contrib CodePlex Bing Maps Development
  • WP7 WP7Contrib CodePlex ObservableCollection
  • WP7 WP7Contrib ILMerge .Net
  • WP7 WP7Contrib Phone Maps
  • WP7 WP7Contrib SilverlightSerializer C#
  • WP7Contrib
  • WP7Contrib Bing Maps WP7
  • WP7Contrib WP7 Geo-Location development C#
  • WP7Contrib WP7 HTTP Compression
  • WP7Contrib WP7 Url Development Rx
  • WP7Dev
  • WPF
  • WPF Cultures
  • WuApi
  • XAML

Blog Archive

  • ►  2013 (16)
    • ►  November (5)
    • ►  September (3)
    • ►  August (1)
    • ►  July (1)
    • ►  June (3)
    • ►  May (2)
    • ►  January (1)
  • ►  2012 (44)
    • ►  November (2)
    • ►  October (8)
    • ►  September (5)
    • ►  August (2)
    • ►  July (4)
    • ►  June (3)
    • ►  May (1)
    • ►  April (2)
    • ►  March (13)
    • ►  February (4)
  • ▼  2011 (52)
    • ►  December (3)
    • ►  November (5)
    • ▼  October (7)
      • Tessellating shapes on top of Bing Maps in a WP7 app
      • WP7Contrib: Added support for GZip compression to ...
      • WP7Contrib: URL shortening in a WP7 app
      • Drawing shapes on top of Bing Maps in a WP7 app
      • How many pins can Bing Maps handle in a WP7 app - ...
      • Observing network traffic for Bing Maps control in...
      • Removing poly line from Bing Maps on WP7
    • ►  September (7)
    • ►  August (11)
    • ►  July (4)
    • ►  May (2)
    • ►  April (1)
    • ►  March (5)
    • ►  February (3)
    • ►  January (4)
  • ►  2010 (1)
    • ►  August (1)
  • ►  2009 (32)
    • ►  December (3)
    • ►  November (7)
    • ►  October (6)
    • ►  September (11)
    • ►  April (1)
    • ►  March (4)
Powered by Blogger.

About Me

Unknown
View my complete profile