Map your Data – Part 5

In my last post, I showed how to process WKT emitted by SQL 2008 spatial types in WPF/SL.  The next step in turning our freshly parsed lat+long pairs into System.Windows.Shapes.

private static List<System.Windows.Shapes.Polygon> CreateMapPolygons(MyModel model, Style polygonStyle)
{
if (model == null) return null;
if (model.MapBricks == null) return null;
if (polygonStyle == null) return null;

    List<System.Windows.Shapes.Polygon> mapPolygons = new List<System.Windows.Shapes.Polygon>();

    try
{
foreach (MapBrick mapBrick in model.MapBricks)
{
foreach (GeoPolygon geoPolygon in mapBrick.GeoPolygons)
{
System.Windows.Shapes.Polygon polygon = new System.Windows.Shapes.Polygon { Tag = mapBrick.Id, ToolTip = mapBrick.Name, Style = polygonStyle };
PointCollection points = new PointCollection();

                if (geoPolygon.GeoPoints != null)
{
geoPolygon.Polygon = polygon;
foreach (LatLong geoPoint in geoPolygon.GeoPoints)
{
PixelCoord coord = MyXbap.MapEngine.PointConverter.LatLongToPoint(geoPoint, model.MapSize, model.MapViewscale, model.MapCenterpoint);
points.Add(new Point { X = coord.X, Y = coord.Y });
}
}

                polygon.Points = points;
mapPolygons.Add(polygon);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
mapPolygons = null;
}

    return mapPolygons;
}

The trick here is to call the PointConverter’s LatLongToPoint method to transform to pixel coordinates that can be plotted on a Canvas.  As I mentioned in my second post on this topic, you’ll need to know the following before you can call this method:

  • lat+long of point
  • size of map (width+height) in pixels
  • scale of map in kilometers (this is the diameter of the largest circle that can be inscribed within the map rectangle)
  • lat+long of center point of map

Given that, the PointConverter will do all the hard math necessary to give you back the right x+y coordinate to plot your point.

To plot a polygon or a line, just loop over all the points in the collection and convert them all.  Then, you’ll just need to add the shape to the Canvas’ Children collection.

Given that, you’ve been completely liberated from the map rendering engine.  In fact, you can plot geographic features without a map at all, but it’s much more fun to get a map into the mix, so I’ll show you how to do that in my next post.