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.



Read More
Posted in WP7 WP7Contrib Bing Maps Polygon Development | No comments

Sunday, 9 October 2011

How many pins can Bing Maps handle in a WP7 app - part 2

Posted on 03:31 by Unknown
I wasn't planning this to span more than one post but it has and there's a good chance there'll be a third focusing back on the UI and how you can improve this further. This post is going to focus on what you can do with the service layer to improve the performance when loading a lot of pins into the Bing Maps control in a WP7 app.

To recap we reached a point where we are only showing the pins required for the bounding rectangle of the map control - even if the call to the service layer returned 500 hundred pins we were calculating which pins were actually visible and only adding them to the MapItemsControl class.

This was working well from a UI and general app perspective - we're no longer blocking the UI thread and we aren't chewing through to much memory. The main problem with this approach is the inefficiency in retrieving data from the UK crime web services. The data returned by these services is centred around the a geo-location for a radius of 1 mile, put simply they return all the reported crimes within a mile of a geo-location. The test location returns over 1000 crime geo-locations, we only want to show a subset of these, probably 150 or so. The screenshot from the last post shows this perfectly:


When I moved the map a request for more data is being made, even if I only move the map a couple of scrolls it is making a new request for data centred around the new geo-location. What became obvious was the actual data being displayed for this movement had already been requested previously. This forms the basis of the in-efficiency - requesting data that has already been requested by the app.

To recap we're getting the data when the ViewChangedEnd event is firing for the map control. We use the crime service in the service layer to request the data from the web services. It is then filtered before adding to the MapItemsControl class. I've shown a stripped down version of the call to the crime service in the service layer below:

private void HandleViewChangeEnd(object sender, MapEventArgs mapEventArgs)
{
var criterion = new StreetLevelCrimeCriterion { Latitude = this.map.Center.Latitude, Longitude = this.map.Center.Longitude };

this.crimeSubscriber = this.crimeService.SearchCrimeRelatedStreetLevelCrime(criterion)
.ObserveOnDispatcher()
.Subscribe(result =>
{
...
...
...
});
}

What's required to prevent requesting the same data again and again (when scrolling) is caching in the service layer. The service layer should be able to workout what data you're requesting and then if the data has already been requested then it should return this already requested data instead of making a request to the back-end web services - standard caching pattern.

Now the service layer did have a caching pattern at the end of the first post. The problem is the cache key was based on an exact geo-location (contained in the Criterion class). So it would cache the crimes for a mile around an exact geo-location for every request. As you can imagine the chances of 2 requests being made with the same geo-location are very small:

var cacheKeyTuple = new CacheKeyTuple&lt;NeighbourhoodCrimeCriterion>
{
Name = "SearchNeighbourhoodCrimes",
Value = criterion.DeepClone()
};

var cachedResult = this.cacheProvider.Get&lt;CacheKeyTuple&lt;NeighbourhoodCrimeCriterion>, NeighbourhoodCrimeResult>(cacheKeyTuple);
if (cachedResult != null)
{
this.log.Write("UkCrimeService: SearchNeighbourhoodCrimes results retrieved from cache, hash code - {0}", criterion.GetHashCode());
return Observable.Return(cachedResult).AsObservable();
}

The screen shot below shows how inefficient this is. When the app is started in location 1 all the crimes within a 1 mile are requested around the map centre point (shown by the pins inside the red circle). When the map is scrolled to locations 2 & 3 then it shouldn't have to request more data from the back-end web services it should be returned from the cache.


So the output in visual studio is shown below, you can see the inefficiency in the multiple requests to the web services, I've also highlighted the geo-location information sent to the web services.


To make this more efficient we have to apply some high school mathematics - Pythagorean Theorem. We're going to use this to calculate the largest square we can get inside the circle described by the crimes returned from the back-end web service. Once we know the length of the side of the square we can use trigonometry to calculate the geo-locations of the corners of the square. Finally when we know this we'll be able to calculate if the map control bounding rectangle is contained within the square, if it is then we don't need to make a request to the web services we can use the cached data, if not then a request will be made to the web services for more data.

First, applying Pythagorean Theorem, we are going to use metric units so instead of a radius of 1 mile it will be 1.60934 km.



By the symmetry of the diagram the center of the circle is on the diagonal AB of the square. The length of AB is 3.21868 km and the lengths of BC and CA are equal. The Pythagorean Theorem then says that

(BC * BC) + (AC * AC) = (AB * AB)

Hence

(BC * BC) + (CA * CA) = 10.35990

But since this is a square then BC is equal to AC, hence

2 * (BC * BC)  = 10.35990

and therefore

|(BC * BC)  = 5.17995

Taking the square root on my calculator I get

BC = 2.27595


The square has the sides of length 2.27595 Km.


Second, we use trigonometry to calculate the geo-locations of the 4 corners of the square. We use the following Haversine formula to calculate these, don't worry I've implemented this in code. It's shown here for completeness:

lat2 = asin(sin(lat1)*cos(d/R) + cos(lat1)*sin(d/R)*cos(θ))
lon2 = lon1 + atan2(sin(θ)*sin(d/R)*cos(lat1), cos(d/R)−sin(lat1)*sin(lat2))


θ is the bearing (in radians, clockwise from north);
d/R is the angular distance (in radians), where d is the distance travelled and R is the earth’s radius

Finally, these have been implemented in the CircularLocation class. It allows the setting of the radius and centre point and it will calculate the largest contained rectangle inside the described circle. The full implementation is shown below:

public sealed class CircularLocation
{
private const double EarthRadius = 6371;

private GeoCoordinate centerPoint;
private double radius;

private LocationRect containedRect;

public GeoCoordinate CenterPoint
{
get
{
return centerPoint;
}
set
{
this.centerPoint = value;
this.containedRect = null;
}
}

public double Radius
{
get
{
return this.radius;
}
set
{
this.radius = value;
this.containedRect = null;
}
}

public LocationRect ContainedRect
{
get
{
if (this.containedRect == null)
{
this.containedRect = this.CalculateContainedRect();
}

return this.containedRect;
}
}

public bool IsRectangleContained(LocationRect boundingRectangle)
{
var containedRect = this.ContainedRect;

if (boundingRectangle.North > containedRect.North)
{
return false;
}

if (boundingRectangle.East > containedRect.East)
{
return false;
}

if (boundingRectangle.South &lt; containedRect.South)
{
return false;
}

if (boundingRectangle.West &lt; containedRect.West)
{
return false;
}

return true;
}

private LocationRect CalculateContainedRect()
{
var hypotenuse = 2 * this.radius;

var side = Math.Sqrt(hypotenuse * hypotenuse / 2);
var halfSide = side / 2;

var directNorth = this.CalculateDestination(this.centerPoint, halfSide, 0);
var directSouth = this.CalculateDestination(this.centerPoint, halfSide, 180);
var directEast = this.CalculateDestination(this.centerPoint, halfSide, 90);
var directWest = this.CalculateDestination(this.centerPoint, halfSide, 270);

return new LocationRect(directNorth.Latitude, directWest.Longitude, directSouth.Latitude, directEast.Longitude);
}

private GeoCoordinate CalculateDestination(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 double DegreeToRadian(double angle)
{
return Math.PI * angle / 180.0;
}

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

This class is then used in the modified crime service as the key for an item added to the cache. When a request is made to the crime service it will recurse the keys added to the cache looking for an instance that
can contain the requested bounding rectangle of the map control - simple!

Obviously how the key is created and added to the cache has been modified, but this is nothing more than creating of an instance of the CircularLocation class and setting the required properties. Shown below is the crime service method.

public IObservable&lt;StreetLevelCrimeResult> SearchStreetLevelCrime(StreetLevelCrimeCriterion criterion)
{
try
{
var centrePoint = criterion.BoundingRectangle.Center;

var keys = this.cacheProvider.Keys&lt;CircularLocation>();
var key = keys.FirstOrDefault(k => k.IsRectangleContained(criterion.BoundingRectangle));

if (key != null)
{
var cachedResult = this.cacheProvider.Get&lt;CircularLocation, StreetLevelCrimeResult>(key);

this.log.Write("UkCrimeService: SearchStreetLevelCrime results retrieved from cache, hash code - {0}", criterion.GetHashCode());
return Observable.Return(cachedResult).AsObservable();
}

object[] @params = new[] { propertyEncoder.Encode(centrePoint.Latitude), propertyEncoder.Encode(centrePoint.Longitude) };

return resourceHandlerFactory.Create()
.ForType(ResourceType.Json)
.UseUrlForGet(this.settings.StreetCrimeUrl)
.WithBasicAuthentication(this.settings.Username, this.settings.Password)
.Get&lt;List&lt;CrimeRelated.StreetLevel.Resources.Result>>(@params)
.Select(response =>
{
var result = ProcessResponse(response);

var circularLocation = new CircularLocation { CenterPoint = centrePoint, Radius = SearchDistance };
var containedRect = circularLocation.ContainedRect;
this.log.Write("UkCrimeService: SearchStreetLevelCrime contained rectangle - {0}", containedRect);

this.cacheProvider.Add(circularLocation, result, this.cacheTimeout);

return result;
});
}
catch (Exception exn)
{
var message = string.Format(FailedPoliceStreetLevelCrime, exn.Message);
this.log.Write(message);
throw new Exception(message, exn);
}
}

Now when I run the app I get better performance when scrolling within the calculated contained rectangle. Only when you're no longer inside the contained rectangle is a request for more data made to the back-end web services. This can be observed in the output window of visual studio. The highlighted area shows the cached results being returned, eventually I scroll outside of the contained rectangle and another request to the back-end web services is made.



Back to the original question - How many pins can Bing Maps handle in a WP7 app?

This post hasn't really changed the answer to this question from the previous post, it has shown you how you can be more efficient with your requesting of data when you're only showing a subset of the returned data.

Part3 will focus back on the UI and how conflation of pins can will help the user experience.

I've put the code for this version up on SkyDrive, you'll need a username & password for the UK crime stats service to run the code.

Read More
Posted in WP7 Bing Maps Development UK Crime | No comments

Wednesday, 5 October 2011

Observing network traffic for Bing Maps control in WP7

Posted on 13:12 by Unknown
Using the Bing Maps control in a WP7 app can incur a rather large memory cost when compared to the rest of an app. Typically I see an initial cost of approximately 8 Mb to show a full screen map when the zoom level is set to 16. This is not a concern, and in my opinion this shouldn't be either. Whats interesting to see is whats happen under the covers from a network perspective and to see if I can see any correlation. None of the following has any scientific basis, more a set of observations.

This is very simple to do, all we need to do is configure the WIFI on the device and then reconfigure Fiddler for remote connections. You can find all the detailed required in this great post by Eric Law.

For the observations I used a modified version of the app from the 'How many pins...' post I did a couple of weeks ago. It only shows the map control it does not display any pins.

When the app is initially installed and run for the first time I'm observing the following network traffic in Fiddler:



You can see there are approximately 35 requests for tiles when the app initially starts, as expected the low resolution tiles are requested first followed by higher resolution. Interestingly the largest tile in png format is only 25 Kb in size.Even if we multiplied 35 by 25 we don't get anywhere near the 8 Mb figure. Infact it only totals about 875 Kb. What we have to remember is, PNG is a bitmapped image format employing a lossless compression format.

Lets see the cost of loading one of these single tiles into an Image control, shown below is the tile and the a test app which loads the tile into the Image control when button the is clicked. I've also stuck on a couple of memory counters.



You can see from loading the image explicitly there is a memory cost associated approximately 600 Kb for this tile. If this was multipled by 25 we'd get a total memory cost of 15 Mb. This is a theoretical total figure but even if it was approaching half this size for the tiles downloaded in the Fiddler screenshot you can see the Bing Maps control is already managing the memory allocated internal already without even approaching the 90 Mb limit.

The next observation was around restarting the application. I observed the tiles were being cached for the app. Whether these are cached by the control for all apps or on a per app basis is unclear. Each response for a tile has HTTP caching directives and these state the tile can be cached for a year - 365 days. The screenshot show 2 restarts of the application, once immediately after closing the app and the second after rebooting the device.


The final observation is the most obvious as I scroll & zoom in and out of the map, I see alot of requests for tiles as expected, the interesting part is it appears the control makes maximum of 5 simultaneous requests for tiles. This was pretty hard to capture but the following screenshot shows 3 outstsanding requests:








Read More
Posted in WP7 Bing Maps Development Network HTTP | No comments

Sunday, 2 October 2011

Removing poly line from Bing Maps on WP7

Posted on 08:19 by Unknown
Showing a route line for a journey on a Bing Maps control in a WP7 app is relatively easy, especially if you use the WP7Contrib Bing Maps Wrapper service to call out to the Bing Maps RESTful API. It's not quite so easy to remove a route line from the control once displayed.

The background to this is in our WP7 app FINDaPAD (you'll need Zune installed) we have a page which shows the route to a property. We offer a driving route and a walking route - if it's walking distance! We don't display these routes together, they are mutually exclusive. When either of the icons is clicked to calculate the route we remove the existing route and display the new route once it has been calculated. The couple of screen shots below show 2 different routes between the same start & end locations depending whether you are driving or walking.


Shown below is a quick demo I knocked up to show the problem in more detail. This app displays a driving or walking app between the 2 UK cities Oxford & Cambridge. It also has a couple of buttons for Clearing the route line and what I call Resetting the route line. This is very similar to what we have in FINDaPAD.


The MapPolyline class in the Microsoft.Phone.Controls.Maps namespace use the Location property for the line drawn on top of the map. This is not a generic collection like IList or ObservableCollection it is of type LocationCollection coming from the same namespace. 


So my definition of Clearing would be clearing contents of this collection. This is done in the 'Clear Route' button click event handler:

private void HandleClearRouteButtonClick(object sender, RoutedEventArgs e)
{
this.routeResult.Text = string.Empty;
this.routeMapRouteLine.Locations.Clear();
}

Unfortunately this doesn't do what I'd expected, it does not remove the overlaid map polyline. As you can see from the screenshot below the text showing the number of points and total distance has been removed but the line hasn't.


To get this to work I had to do what I define as Resetting the clearing of the collection but then adding back in a single value. It doesn't have to any particular value it could be anything that is a valid geo-location - not GeoCoordinate.Unknown.

private void HandleResetRouteButtonClick(object sender, RoutedEventArgs e)
{
this.routeResult.Text = string.Empty;
this.routeMapRouteLine.Locations = new LocationCollection {this.routeMap.Center};
}

I literally resetting the collection and adding the centre point of the map back in as the start of the poly line, this gives the expected UI response when 'Reset Route' button is clicked:


I've observed the same behaviour when using the MVVM pattern (FINDaPAD) or a code behind as in the above demo. I've included the code below for the demo, including the XAML.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

<Microsoft_Phone_Controls_Maps:Map x:Name="routeMap"
Height="400"
VerticalAlignment="Top"
ZoomBarVisibility="Collapsed"
CopyrightVisibility="Visible"
ZoomLevel="8"
AnimationLevel="UserInput"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch">

<Microsoft_Phone_Controls_Maps:MapPolyline x:Name="routeMapRouteLine"
Stroke="Green"
StrokeThickness="6"
Opacity="0.7" />

</Microsoft_Phone_Controls_Maps:Map>

<Button Content="Driving Route"
Height="72"
Margin="0,463,232,0"
Name="drivingButton"
VerticalAlignment="Top"
Click="HandleDrivingButtonClick" />

<Button Content="Walking Route"
Height="72"
Margin="209,463,6,0"
Name="walkingButton"
VerticalAlignment="Top"
Click="HandleWalkingButtonClick" />

<TextBlock Height="30"
Margin="12,427,6,0"
Name="routeResult"
VerticalAlignment="Top" />

<Button Content="Clear Route"
Height="72"
HorizontalAlignment="Left"
Margin="0,529,0,0"
Name="clearRouteButton"
VerticalAlignment="Top"
Width="224"
Click="HandleClearRouteButtonClick" />

<Button Content="Reset Route"
Height="72"
HorizontalAlignment="Left"
Margin="209,529,0,0"
Name="resetRouteButton"
VerticalAlignment="Top"
Width="241"
Click="HandleResetRouteButtonClick" />
</Grid>

As I said earlier I've used the Bing Maps Wrapper service from the WP7Contrib, you can find out more about calculating routes and all the other functionality by reading a couple of posts by RichGee and this by me.

public partial class MainPage : PhoneApplicationPage
{
private const string RouteResultFormat = "Route Points: {0}, Distance: {1} {2}";
private const string RouteFailedFormat = "Route Failed: {0}";

private readonly IBingMapsService bingMapsService;
private readonly IRouteSearchCriterion drivingCriterion;
private readonly IRouteSearchCriterion walkingCriterion;

public MainPage()
{
InitializeComponent();

this.bingMapsService = new BingMapsService("Your credentials", "Your app id");

var start = new GeoCoordinate(51.754240074033525, -1.25244140625);
var end = new GeoCoordinate(52.19413974159756, 0.1318359375);

var waypoints = new List<WayPoint> { new WayPoint { Point = start }, new WayPoint { Point = end } };

this.drivingCriterion = CriterionFactory.CreateRouteSearch(waypoints, ModeOfTravel.Driving);
this.walkingCriterion = CriterionFactory.CreateRouteSearch(waypoints, ModeOfTravel.Walking);

this.routeMap.Center = new GeoCoordinate(51.88369680508255, -0.4140472412109375);
this.routeMap.ZoomLevel = 8;
}

private void HandleDrivingButtonClick(object sender, RoutedEventArgs e)
{
this.routeProgressBar.IsIndeterminate = true;

this.bingMapsService.CalculateARoute(drivingCriterion)
.ObserveOnDispatcher()
.Subscribe(this.UpdateRouteResult, () => { this.routeProgressBar.IsIndeterminate = false; });
}

private void HandleWalkingButtonClick(object sender, RoutedEventArgs e)
{
this.routeProgressBar.IsIndeterminate = true;

this.bingMapsService.CalculateARoute(walkingCriterion)
.ObserveOnDispatcher()
.Subscribe(this.UpdateRouteResult, () => { this.routeProgressBar.IsIndeterminate = false; });
}

private void UpdateRouteResult(RouteSearchResult result)
{
if (result.HasError)
{
this.routeResult.Text = string.Format(RouteFailedFormat, result.ErrorDetails);
return;
}

if (result.HasPoints)
{
this.routeResult.Text = string.Format(RouteResultFormat, result.Points.Count, result.TravelDistance, result.DistanceUnit);
this.routeMapRouteLine.Locations = result.Points;
this.routeMap.ZoomLevel = 8;
}
}

private void HandleClearRouteButtonClick(object sender, RoutedEventArgs e)
{
this.routeResult.Text = string.Empty;
this.routeMapRouteLine.Locations.Clear();
}

private void HandleResetRouteButtonClick(object sender, RoutedEventArgs e)
{
this.routeResult.Text = string.Empty;
this.routeMapRouteLine.Locations = new LocationCollection {this.routeMap.Center};
}
}
Read More
Posted in WP7 WP7Contrib Bing Maps Development | No comments
Newer Posts Older Posts Home
Subscribe to: Posts (Atom)

Popular Posts

  • MVVM anti-pattern: View code behind with no implementation
    I've seen rather a lot of this anti-pattern recently, to be explicit about what I mean, lets define this in terms of a WPF user control....
  • WP7Contrib: Bing Maps REST Services Wrapper - Deep Dive
    Following on from Rich's post introducing the Bing Maps Service in the WP7Contrib I'm going to explain in more detail how we built ...
  • Using IoC nested lifetime scopes with View Models in MVVM
    A common pattern you see when developing web services is the use of the Unit of Work applied to the HTTP request - anything that happens dur...
  • Be careful of the culture when using Bing Maps REST API
    When developing the Bing Maps Wrapper service for the WP7Contrib we weren't aware of the importance of the instance of the CultureInfo ...
  • Implementing a message box using a visual overlay in MVVM
    I've blogged about implementing a busy indicator before, this post is an extension of this pattern to implement a message box - this is...
  • Azure - RoleEnvironmentException in OnStart
    My previous post was a bit of rant at the developer experience in Azure when trying to set-up diagnostics. I managed to work out what was c...
  • WP7Contrib: Transient caching with In Memory Cache Provider
    Rich  and I are currently working on a WP7 application based around local content stored on the device.   This content consists of a databas...
  • Manipulating web browser scroll position on Windows Phone 7
    Manipulating the browser control position on WP7 is relatively straight forward, all you need to is a couple of calls out to javascript usin...
  • 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...
  • Coupling and cohesion
    I was reading ploeh's blog  this morning and it made me think about coupling and cohesion in general. These are import concepts in softw...

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)
      • MVVM anti-pattern: Injecting the IoC container int...
      • MVVM anti-pattern: View code behind with no implem...
      • MVVM anti-pattern: explicitly using data context i...
      • Implementing a message box using a visual overlay ...
      • Using IoC nested lifetime scopes with View Models ...
    • ►  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)
    • ►  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