Subscribe: Chris Pietschmann - Silverlight
http://pietschsoft.com/syndication.axd?category=ef953010-4cfa-49f2-baa2-ca51f3e8bb53
Added By: Feedage Forager Feedage Grade B rated
Language: English
Tags:
add  bing maps  bing  control  imagery  ldquo  map  maps silverlight  maps  microsoft  new  silverlight control  silverlight 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: Chris Pietschmann - Silverlight

Chris Pietschmann - Silverlight



husband, father, hacker, entrepreneur, futurist, innovator, autodidact



 



Step By Step: Bing Maps Silverlight and an Out Of Browser (OOB) Application

Wed, 26 Jan 2011 08:40:19 -0500

I’ve received a couple questions regarding the display of the Bing Maps Silverlight control within a Silverlight Out Of Browser (OOB) application, so I decided to write up a simple step by step example of creating a basic Silverlight OOB application that displays a map. Step By Step Example Follow the below steps to create a basic Silverlight OOB application that displays a map using the Bing Maps Silverlight control within Visual Studio 2010: Step 1: Create New Project In this case, I’m choosing to create a new “Silverlight Application” project, but you could also choose the Business or Navigation Application templates if you choose. Step 2: Select the desired Web Project Type on the New Silverlight Application dialog I’m leaving the default setting of an ASP.NET Web Application Project, but you could choose a Website or MVC Web Project. Step 3: Add a Reference to the Bing Maps Silverlight Control within the Silverlight project Step 4: Add a Map to the Application Here’s the source code for MainPage.xaml with a map added in the project that I’ve created: .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Step 5: Enable Out of Browser Mode Within the Silverlight Project Properties, check the “Enable running application out of browser” option to enable Out Of Browser (OOB) for this Silverlight application. Step 6: Run it! If you have the Silverlight project selected as the Startup Project (which is the default when creating the project) then Visual Studio will run it in Out Of Browser mode. If you have the Web project selected as the Startup Project, then you will need to Right Click the Silverlight Application (when running) and select “Install […] onto this computer…” Generally when debugging an OOB application, you’ll want to have the Silverlight project set as Startup Project, unless you have web services, images or other data hosted within the Web Project that the Silverlight Project consumes. In this case you’ll want to debug while running the Web Project as Startup. Additional Note Regarding Silverlight OOB (Out of Browser) Applications The Bing Maps Silverlight control requires itself you be hosted within a web site or application. If you are using the Bing Maps Silverlight control within a Silverlight Application, then you’ll need to host it on a website (over http). If you do not host it on a web site or application, then the Bing Maps Silverlight control will display a “Map loaded in unsupported Uri Scheme. Please reload page in “http” scheme.” error message. Happy Mapping![...]



Silverlight: Modify MEF to load plugins from DLL and XAP files

Fri, 22 Oct 2010 12:44:42 -0500

I’m using MEF in a new project, and the limitation that I’ve found in using MEF with Silverlight is that it only supports downloading and loading plugins/assemblies from XAP files. What I would really like to do is support plugins that are compiled into either individual DLL’s or more complex plugins within a XAP. Update: I have also posted this to the Issue Tracker on the MEF CodePlex site. Why individual DLL’s? The really answer to this is flexibility. I don’t think they creators of MEF made a mistake supporting XAP file, but I think they made a mistake by not supporting DLL’s in addition. XAP files are great. They allow you to package your entire plugin, along with its dependencies, into a single file that gets loaded by the app at runtime. You never have to worry about the plugin breaking due to a missing assembly reference since they are all right there. However, where XAPs fail is when you have many XAPs that have dependencies on the same assemblies that are already referenced in the host application. These assemblies are added to the XAP (basically only the 3rd party assemblies, not core Silverlight assemblies) and downloaded with each XAP separately. Lets say you have an application where you are using a 3rd party library, say the Bing Maps Silverlight Control, and you have 10 plugins all compiled into their own XAP that have references to the 3rd party library. This mean that the file size of each XAP is increased with the 3rd party library. When each XAP is downloaded, so is the 3rd party library. In this case it’s needlessly downloaded 10 times! In this scenario, the XAP files are adding bloat by including the 3rd party library. You could remove the reference, to leave the library out, but then your XAP file wouldn’t compile. This is the very reason why supporting DLL’s, in addition to XAP’s, is important. If you know that multiple plugins to your application will be utilizing the same 3rd party library, then you could add its reference to the host application. Then with the host already having it loaded, you could load the plugins compiled as DLL’s, and only be downloading the 3rd party library once; when the application loads. This will reduce bandwidth costs, and speed up the time it takes to load the plugins. Modify the DeploymentCatalog to also support DLL’s Luckily the way that MEF is designed, the change to support DLL’s in addition to XAP’s is only a matter of adding a few lines of code to the private HandleOpenReadCompleted method of the DeploymentCatalog. Here’s the DeploymentCatalog.HandleOpenReadCompleted method with its modifications: private void HandleOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { Exception error = e.Error; bool cancelled = e.Cancelled; if (Interlocked.CompareExchange(ref this._state, 0xbb8, 0x7d0) != 0x7d0) { cancelled = true; } if ((error == null) && !cancelled) { try { // Check if a XAP or DLL was downloaded, based on file extension if (this._uri.OriginalString.ToLower().EndsWith(".xap")) { // Load Assemblies from XAP IEnumerable assemblies = Package.LoadPackagedAssemblies(e.Result); this.DiscoverParts(assemblies); } else // if (this._uri.OriginalString.ToLower().EndsWith(".dll")) { // Load DLL Assembly var assemblies = new List(); assemblies.Add((new AssemblyPart()).Load(e.Result)); this.DiscoverParts(assemblies); } } catch (Exception exception2) { error = new InvalidOperationException(Strings.InvalidOperationException_ErrorReadingXap, exception2); } } this.OnDownloadCompleted(new AsyncCompletedEventArgs(error, cancelled, this)); } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New"[...]



Silverlight: Embed IronRuby within XAML Part 2

Sun, 17 Oct 2010 10:44:27 -0500

In the previous post I explored the possibility of embedding IronRuby / DLR Script within XAML using both an IValueConverter and Custom UserControl. I spent a little more time experimenting with the DLRScriptUserControl I posted, and came up with some small modifications to it that allow UI event handlers to be wired up using a DLR language (such as IronRuby. Loading Assemblies Into the ScriptEngine.Runtime Context Something nice with how the ScriptEngine class allows you to execute a script of IronRuby (or other DLR language) is that it requires the implementer of the ScriptEngine (not the DLR script writer) to call “ScriptEngine.Runtime.LoadAssembly” in order to make a certain CLR assembly accessible within the DLR script that gets executed. This allows the scripts to be run in a sort of sandboxed environment. There are two ways of doing this: // One: Load the assemblies of known types you want to // make available within the script. // Load System.Windows engine.Runtime.LoadAssembly(typeof(UserControl).Assembly); // Load System.Windows.Browser engine.Runtime.LoadAssembly(typeof(HtmlPage).Assembly); // Two: Load assemblies using thier Full Name engine.Runtime.LoadAssembly( Assembly.Load("System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e") ); engine.Runtime.LoadAssembly( Assembly.Load("System.Windows.Browser, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e") ); .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } The first method is easiest when the assembly you wish to load is already referenced by the host application. It also allows you to easily support being able to migrate your application to a newer version of the framework since it will load the version of the assembly that your application is compiled for, rather than the specific version stated in the full assembly name. Loading Assemblies within DLRScriptUserControl Here’s a modified version of DLRScriptUserControl from the previous post that includes the above snippets to load both “System.Windows” and “System.Windows.Browser” assemblies into the ScriptEngine.Runtime context. public class DLRScriptUserControl : UserControl { public object Script { get; set; } public DLRScriptUserControl() { this.Loaded += new RoutedEventHandler(DLRScriptUserControl_Loaded); } void DLRScriptUserControl_Loaded(object sender, RoutedEventArgs e) { // Create IronRuby Engine ScriptEngine engine = Ruby.CreateEngine(); // Load necessary assemblies for event handling, etc. // Load System.Windows engine.Runtime.LoadAssembly(typeof(UserControl).Assembly); // Load System.Windows.Browser engine.Runtime.LoadAssembly(typeof(HtmlPage).Assembly); // Give IronRuby access to this control via a variable named 'Ctrl' engine.Runtime.Globals.SetVariable("Ctrl", this); // Execute the code engine.Execute(this.Script as string, engine.CreateScope()); } } Handle UI Event within Embedded IronRuby using DLRScriptUserControl Now that the “System.Windows” and “System.Windows.Browser” assemblies are loaded and accessible to the DLR script that’s executed (in this case IronRuby) we can use their namespaces within code. The below example demonstrates how to: Get references to[...]



Silverlight: Embed IronRuby/DLR Scripting within XAML using IValueConverter and Custom UserControl

Sat, 02 Oct 2010 14:40:00 -0500

After I wrote the “Intro to IronRuby/DLR Scripting in C# Silverlight 4 Application” post, I came across an interesting series on embedding DLR scripts in XAML with WPF. This is an interesting series, although the code doesn’t run in Silverlight, due to the fact that Silverlight is only a subset of WPF and doesn’t support the System.Windows.Markup.MarkupExtension class. I test out a couple things in Silverlight, and I was able to get similar DLR scripting functionality working under Silverlight using a combination of a simple, custom IValueConverter and a custom UserControl class. If you are unfamiliar with value converters and the IValueConverter interface (same for both Silverlight and WPF), you may want to look it up and learn how to create your own. Value converters are tremendously helpful when performing data binding. Embedded IronRuby within XAML To start, here’s a few examples of IronRuby code embedded within a custom IValueConverter and custom UserControl. As you’ll see, this can be very effective to embed scripting to define how to display the values bound, or to manipulate the content of the custom user control. Although, you must keep in mind that this is not limited to simple tasks such as these. You have the full power of the DLR and .NET within the DLR scripts being executed, so there really is no limit to what could be coded within. class AddFive def add 5 + 5 end end a = AddFive.new a.add ConverterValue.FirstName + " " + ConverterValue.LastName Ctrl.FindNam[...]



Intro to IronRuby/DLR Scripting in C# Silverlight 4 Application

Wed, 29 Sep 2010 12:44:33 -0500

I’ve been working lately on figuring out how to add DLR scripting support to a Silverlight 4 application I’ve been working on. The idea is to give it a plugin style architecture, with the plugins being written in a DLR language; currently focusing on IronRuby. I originally searched how to do this, but couldn’t find any recent articles that discuss Silverlight 4. Also, most articles out don’t target Silverlight and more of them discuss IronPython and not IronRuby, even though the DLR stuff is the same regardless of DLR language used. So, I thought I’d share what I’m learning about adding IronRuby scripting to Silverlight 4 applications. I’m also focusing on C# as the host language, but the .NET object and methods used will be the same from VB.NET. Older Articles for Reference Adding scripting to a C# Silverlight app Scripting C# Silverlight apps with IronPython IronRuby script engine in C# Extending your C# application with IronPython Getting Started with IronRuby and SIlverlight What to download? Since I am talking about using Silverlight 4, you will need Visual Studio 2010 installed. You will need to have the following installed: Silverlight 4 Tools for Visual Studio 2010 Also, download the following and extract, as it will be used later: IronRuby 1.1 (.NET 4.0 ZIP & Silverlight 4) Add Assembly References to Silverlight Project Either create a new Silverlight 4 project or use an existing one, then add the references to the following assemblies located within the “silverlight/bin” folder of the IronRuby 1.1 archive previously downloaded. IronRuby.dll IronRuby.Libraries.dll IronRuby.Libraries.Yaml.dll Microsoft.Dynamic.dll Microsoft.Scripting.Debugging.dll Microsoft.Scripting.dll Microsoft.Scripting.Silverlight.dll System.Numerics.dll If your using a C# project, then you will also need to Add Reference to Microsoft.CSharp namespace. Execute IronRuby Code from C# It is actually very simple to use the ScriptEngine class to execute DLR code from within C# (or any other .NET language.) Here’s a small example that show how to use ScriptEngine to execute a small piece of IronRuby code: // Create instance of the IronRuby ScriptEngine ScriptEngine engine = Ruby.CreateEngine(); // some IronRuby code to execute // this just adds 2 plus 2 var code = "2 + 2"; // Execute the code and catch the result // in a variable var result = engine.Execute(code); // After execution "result" should contain // the value "4" .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } As you can see, it really is only 2 lines of code required to execute a piece of IronRuby (or other DLR language) code. Use Global Variables to Grant Access Within Your Application The ScirptEngine class allows you to set global variables from .NET code to allow the DLR language (in this case IronRuby) access to them. Here’s an example of creating a global variable “MainPage” that is a reference to the object that is executing the code. The MainPage object also implements a method named “SetTitleText” that the IronRuby code will call. public partial class MainPage : UserControl { public void SetTitleText(string t) { this.txtTitle.Text = t; } void MainPage_Loaded(object sender, RoutedEventArgs e) { Script[...]



Use New Bing Maps Road Imagery In Silverlight Map Control (Unofficially and Unsupported)

Thu, 19 Aug 2010 15:55:00 -0500

Recently the consumer facing Bing Maps site changed the map imagery that is displayed for the Road map mode. This map imagery has not been officially made available for Bing Maps for Enterprise developers to use within their applications. The imagery is only officially available to the Bing Maps consumer website. Unofficially, you can still access the imagery if you know the URL format to get it. Below is an example of using the URL format for the new imagery to display it within the Bing Maps Silverlight Control. I have not seen anything official from Microsoft on this, so I assume that doing this is against their terms of use. You assume any and all responsibility in violating their terms of use if you use the below code. Sorry for the disclaimer, but I don’t want you to tell Microsoft I told you it was ok. Basically, do not use this in a production application, unless you get consent from Microsoft. Now the code… Displaying the Map (XAML): NewBingMapTileSource (C#): public class NewBingMapsTileSource : Microsoft.Maps.MapControl.TileSource{ public NewBingMapsTileSource() : base("{UriScheme}://ecn.t{subdomain}.tiles.virtualearth.net/tiles/r{quadkey}?g=530&mkt=EN-US&lbl=l1&stl=h&shading=hill&n=z") { }} [...]



Loading Microsoft CDN Hosted OpenStreetMap Imagery in Silverlight Bing Maps Control

Thu, 19 Aug 2010 15:42:00 -0500

Recently a new Bing Maps App for OpenStreetMap (OSM) was released. This new feature of the Bing Maps consumer facing website is hosting the OpenStreetMap imagery using the Azure CDN, rather than relying on OpenStreetMap’s server. There has been some question as to whether developers can use the Microsoft hosted OpenStreetMap imagery within their own applications. I have not seen anything official from Microsoft on this, so I assume that doing this is against their terms of use. You assume any and all responsibility in violating their terms of use if you use the below code. Sorry for the disclaimer, but I don’t want you to tell Microsoft I told you it was ok. Basically, do not use this in a production application, unless you get consent from Microsoft. Now the code… Displaying the Map (XAML): OpenStreetMapTileSource (C#): public class OpenStreetMapTileSource : Microsoft.Maps.MapControl.TileSource { public OpenStreetMapTileSource() : base() { this.UriFormat = "{UriScheme}://{3}.osm.virtualearth.net/{2}/{0}/{1}.png" .Replace("{UriScheme}", OpenStreetMapTileSource.PageUriScheme); // <-- set "http" or "https" appropriately } public override System.Uri GetUri(int x, int y, int zoomLevel) { // Randomly decide which server to use string server; var rnd = new Random(); var i = rnd.Next(0, 2); switch (i) { case 1: server = "b"; break; case 2: server = "c"; break; default: server = "a"; break; } // Format Uri for the desired map tile image return new Uri(string.Format(this.UriFormat, x, y, zoomLevel, server)); } internal static string PageUriScheme { get { if ((HtmlPage.IsEnabled && (HtmlPage.Document != null)) && (HtmlPage.Document.DocumentUri != null)) { return HtmlPage.Document.DocumentUri.Scheme; } return "HTTP"; } } }[...]



Silverlight Bing Maps: Draw Circle Around a Latitude/Longitude Location

Mon, 28 Jun 2010 23:43:00 -0500

Over 2 years ago I posted an example of how to draw circles on the Bing Maps JavaScript control. I thought it was about time to update that post to demonstrate how to do this using the Bing Maps Silverlight control. This is basically a C# port of the original JavaScript code. Sometimes this can be really useful, but it isn’t built into the Sivleright Bing Maps Control. So you need to implement it yourself in order to do it. However, instead of writing from scratch, feel free to copy the code from this post. Download Full Source: SLBingMaps_DrawCircle.zip     Here’s example usage: // Draw circle at the location where the user clickedprivate void Map_MouseClick(object sender, Microsoft.Maps.MapControl.MapMouseEventArgs e){ // Get the location the mouse clicked var mousePoint = e.ViewportPoint; var clickedLocation = MainMap.ViewportPointToLocation(mousePoint); // Calculate the points to make up a circle with radius of 200 miles var locations = GeoCodeCalc.CreateCircle(clickedLocation, 200, DistanceMeasure.Miles); // Add Red Polyline to the Map var poly = new MapPolyline(); poly.Locations = locations; poly.Stroke = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0)); poly.StrokeThickness = 2; MainMap.Children.Add(poly); }   And, here’s the code that calculates the location points to make up the circle: /* * Written by Chris Pietschmann (http://pietschsoft.com) * This code is derived from the code posted in the following location: * http://pietschsoft.com/post/2010/03/02/Bing-Maps-JS-Calculate-Area-of-Circle-and-Draw-Circle-on-Map.aspx*/using System;using System.Collections.Generic;using Microsoft.Maps.MapControl;namespace SLBingMaps_DrawCircle{ public enum DistanceMeasure { Miles, Kilometers } public class GeoCodeCalc { public const double EarthRadiusInMiles = 3956.0; public const double EarthRadiusInKilometers = 6367.0; public static double ToRadian(double degrees) { return degrees * (Math.PI / 180); } public static double ToDegrees(double radians) { return radians * (180 / Math.PI); } public static LocationCollection CreateCircle(Location center, double radius, DistanceMeasure units) { var earthRadius = (units == DistanceMeasure.Miles ? GeoCodeCalc.EarthRadiusInMiles : GeoCodeCalc.EarthRadiusInKilometers); var lat = ToRadian(center.Latitude); //radians var lng = ToRadian(center.Longitude); //radians var d = radius / earthRadius; // d = angular distance covered on earth's surface var locations = new LocationCollection(); for (var x = 0; x <= 360; x++) { var brng = ToRadian(x); var latRadians = Math.Asin(Math.Sin(lat) * Math.Cos(d) + Math.Cos(lat) * Math.Sin(d) * Math.Cos(brng)); var lngRadians = lng + Math.Atan2(Math.Sin(brng) * Math.Sin(d) * Math.Cos(lat), Math.Cos(d) - Math.Sin(lat) * Math.Sin(latRadians)); locations.Add(new Location(ToDegrees(latRadians), ToDegrees(lngRadians))); } return locations; } }}[...]



Display Google Maps Imagery using Bing Maps Silverlight Control

Mon, 14 Jun 2010 23:15:00 -0500

I’ve gotten a couple emails asking how to show Google Maps imagery using the Bing Maps Silverlight Control. I previously post how to display OpenStreetMaps and Yahoo maps imagery using the control, but is it possible to show Google Maps imagery too?? Yes, absolutely; well technically, but the Google Maps Terms of Use does prohibit it. Actually, the Google Maps Terms of Use prohibits the direct access of the map tile images, and does not specifically prohibit using them with the Bing Maps Silverlight Control. You may only continue reading if you are willing to break the Google Maps Terms of Use, and see how similar the two mapping platforms really are. Remember the below code most likely violates the Google Maps Terms of Use, and probably shouldn’t be used in a production system; unless of course you really don’t mind breaking the terms of use. The below code follows suite after the code I posted a while back on displaying OpenStreetMap and Yahoo Maps imagery within the Bing Maps Silverlight Control. First, here’s some XAML usage samples using the Google Maps TIle Source classes listed further down. The first one is showing the Google Maps Road/Terrain imagery, the second shows the Google Maps Aerial/Satellite imagery:   If you notice, the second example showing the usage of the Google Maps Aerial/Satellite imagery is displaying 2 tile sources. This is because Google Maps has separate tile sources for both the Aerial/Satellite imagery and the Labels. This example shows the Labels tile source over the top of the Aerial/Satellite tile source to give the desired effect of “Aerial with Labels.” Now, here’s the main attraction of this article; the actual Google Maps TileSource objects referred to above: public class GoogleMapsRoadTileSource : GoogleMapsTileSourceBase{ public GoogleMapsRoadTileSource() : base("http://mt{0}.google.com/vt/lyrs=m@128&hl=en&x={1}&y={2}&z={3}&s=") { }}public class GoogleMapsAerialTileSource : GoogleMapsTileSourceBase{ public GoogleMapsAerialTileSource() : base("http://khm{0}.google.com/kh/v=62&x={1}&y={2}&z={3}&s=") { }}public class GoogleMapsLabelsTileSource : GoogleMapsTileSourceBase{ public GoogleMapsLabelsTileSource() : base("http://mt{0}.google.com/vt/lyrs=h@128&hl=en&x={1}&y={2}&z={3}&s=") { }}public abstract class GoogleMapsTileSourceBase : Microsoft.Maps.MapControl.TileSource{ public GoogleMapsTileSourceBase(string uriFormat) : b[...]



Resizing and Auto-Scaling Pushpin in Bing Maps Silverlight

Fri, 04 Jun 2010 00:26:00 -0500

Plotting pushpins on the Bing Maps Silverlight control is really simple when using the Pushpin control that comes with the control. But, what if you want to change the size of the Pushpin? It doesn't work to just change the Pushpin.Height and Pushpin.Width properties. This is actually because those properties pertain to the controls Content property. So, how exactly do you go about changing the size of the Pushpin if the Height and Width properties don't work? Use ScaleTransform to Resize Pushpins The answer is simple. All you need to do is use a ScaleTransform. Below is a couple examples, one making the pushpin smaller and the other bigger.                                 You may have noticed that not only does the above example set the ScaleX and ScaleY properties of the ScaleTransform, but the CenterX and CenterY are also set. This is because if we don't set the CenterX and CenterY appropriately the Pushpin will get "moved" from its correct location when the Transform is performed. How did I decide to set CenterX to 17 and CenterY to 35? Well, the Pushpins "default" size sets the Width equal to 34 and Height to 35, and the PositionOrigin to BottomCenter. Since the PositionOrigin is set to BottomCenter, in order to get the pushpin to stay in its correct position on the map we need to set the CenterX to half the Width or 17, and CenterY to the Height or 35. The image to the right shows an example of this in action. Auto Scale Pushpin with Map Zoom Level A neat feature that becomes available with the Bing Maps Silverlight control once you start using ScaleTransforms to modify the size of Pushpins is the ability to change the size of the Pushpins when the Map Zoom Level is changed. All it takes is a little help from a custom IValueConverter and a little Data Binding. The image to the right shows this in action. Both sides of the image were not resized at all, the difference in size of the Pushpins is due to the usage of the following code. First, we'll add some Pushpins to a Map and set the Pushpins RenderTransform property binding to bind it to the Map's ZoomLevel property and set it to use a custom converter.                         Next, make sure you declare the PushpinScaleTransform static resource in the UserControl, Page or App. Also, don't forget to include the namespace, in the below example I named it "local".     Finally, add the PushpinScaleTransform custom IValueConverter object to the project. This custom IVa[...]



Draggable Pushpins using Bing Maps Silverlight Control

Sun, 30 May 2010 08:39:00 -0500

Using a map to visualize data within an application is great, but you must first get the location of the data to be displayed. If you have the address you can geocode it using the Bing Maps Web Services, but "What if you can't geocode it?" Or, "What if the geocoding can't find the address?" Well, if your user knows where the location is, then you can have them point it out by clicking on the map. Creating Pushpins in response to a users click is nice, but wouldn't it be even nicer if they could "Click and Drag" the Pushpin around to define/edit/change the location of the data entity? I have even seen this discussed a bit in regards to the Bing Maps Silverlight Control, and it isn't something that is built into the map control directly. However it isn't too difficult to implement, if you know what to do. So I decided to create and post a simple "DraggablePushpin" object deriving from the "Microsoft.Maps.MapControl.Pushpin" object that implements Dragging in a nice, self contained fashion. There's no need to wire up any events, you simple add a "DraggablePushpin" to you Map, and the user can drag it around. Here's the code for the "DraggablePushpin": public class DraggablePushpin : Microsoft.Maps.MapControl.Pushpin { private bool isDragging = false; EventHandler ParentMapMousePanHandler; MouseButtonEventHandler ParentMapMouseLeftButtonUpHandler; MouseEventHandler ParentMapMouseMoveHandler; protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { // Check if the Map Event Handlers have been created/attached to the Map // If not, then attach them. This is done in the "Pushpin.OnMouseLeftButtonDown" // event because we don't know when the Pushpin is added to a Map or MapLayer, but // we do konw that when this event is fired the Pushpin will already have been added. var parentLayer = this.Parent as MapLayer; if (parentLayer != null) { var parentMap = parentLayer.ParentMap; if (parentMap != null) { if (this.ParentMapMousePanHandler == null) { this.ParentMapMousePanHandler = new EventHandler(ParentMap_MousePan); parentMap.MousePan += this.ParentMapMousePanHandler; } if (this.ParentMapMouseLeftButtonUpHandler == null) { this.ParentMapMouseLeftButtonUpHandler = new MouseButtonEventHandler(ParentMap_MouseLeftButtonUp); parentMap.MouseLeftButtonUp += this.ParentMapMouseLeftButtonUpHandler; } if (this.ParentMapMouseMoveHandler == null) { this.ParentMapMouseMoveHandler = new MouseEventHandler(ParentMap_MouseMove); parentMap.MouseMove += this.ParentMapMouseMoveHandler; } } } // Enable Dragging this.isDragging = true; base.OnMouseLeftButtonDown(e); } #region "Mouse Event Handler Methods" void ParentMap_MousePan(object sender, MapMouseDragEventArgs e) { // If the Pushpin is being dragged, specify that the Map's MousePan // event is handled. This is to suppress the Panning of the Map that // is done when the mouse drags the map. if (this.isDragging) { e.Handled = true; } } void ParentMap_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { // Left Mouse Button released, stop dragging the Pushpin this.isDragging = false; } void ParentMap_MouseMove(object sender, MouseEv[...]



Silverlight with WCF RIA Services Throws "Project File ... Not Found" Error When Compiling in Visual Studio 2010 RC

Wed, 24 Mar 2010 15:24:00 -0500

While working with the Silverlight Business Application template in Visual Studio 2010 RC I discovered a peculiar issue that if the project specified as the "WCF RIA Services Link" for the Silverlight Project can not be found a compile time error of "Project File ... Not Found" will be generated. This is a very cryptic error message since it's the same message that gets thrown if you delete a Project File (.csproj or .vbproj) from the hard drive but it's still references within the Solution File. This took me a little while to figure out, and I only discovered it when I looked through the Project File of my Silverlight Application. This particular issue may also apply to the VS'10 RTM once it's release, only time will tell if they fix it before then.

The project file "..\App.Website\App.Website.csproj" was not found.

 

What Causes The Error

What I did to cause this issue to come up was I created a New Project using the Silverlight 4 Business Application Template. Then I moved the each Projects folder to a different sub-folder to better organize the code since I needed to add multiple more projects/assemblies to each application (ASP.NET and Silverlight) to build out the application I'm working in a more module fashion. The reason I usually tend to do this is to keep the "Standard .NET" and "Silverlight-only" assemblies separate since you can not include a non-Silverlight Assembly within a Silverlight Project. (If only .NET and Silverlight made it easier to share whole assemblies...)

After moving the projects to different sub-folders, and fixing the linked file references that I broke in the process, I tried building the project to make sure everything was "ok" and the compiler threw a "The project file ... was not found." error.

To fix this is really simple, but then again only if you know what to look for.

How To Fix It

To fix this all you need to do is go to the Project Properties for the Silverlight Project, and change the "WCF RIA Services link" dropdown to select the correct ASP.NET Project; then you'll be all ready to compile and keep developing.

Below is a screenshot of VS'10RC showing the Error Message and the Properties UI for changing the WCF RIA Services link.

(image)

Is This A Bug?

I certainly consider this to be a bug, since the error message that is shown if you have the "WCF RIA Services link" set to a non-existent project doesn't really point you in the direction of fixing the issue; at least directly. Yes, if you look at the "Project" specified for the Error it does specify the Silverlight Project, but doesn't exactly spell out where to look to fix the issue.

Instead of the cryptic message, I propose that it state something like "WCF RIA Services link Error; the "App.Website" project was not found."

I hope this article helps others solve this potentially very perplexing issue.




Prototype of OpenStreetMap Silverlight Control using DeepEarth and Bing Maps SDK

Fri, 13 Nov 2009 07:40:00 -0500

I’ve decided to expand a little on using OpenStreetMap imagery with the new Bing Maps Silverlight Control in response to the following comment posted by John O’Brien on my previous “Display OpenStreetMap Imagery using Bing Maps Silverlight Control v1” post: “Very close Chris but you will still need to enter a Bing Maps AppID. If however you create your own map from MapCore and don't use the Bing Maps services then you don't need creditials” Yes, it is true that by just displaying the OpenStreetMap imagery on the Bing Maps Silverlight Control using a custom TileSource you still need to provide the control a Bing Maps Key (App ID). However, what if you inherited from the “MapCore” base class (the same one that the Bing Maps “Map” object inherits) and built out a full OpenStreetMap Map control? Custom “OpenStreetMap” Control I built out a test “OpenStreetMap” object that inherits from “MapCore” that automatically sets the Map Mode to a “OpenStreetMapMode” object that loads up the OpenStreetMap imagery automatically. This was some simple code to write, basically just extending only a little bit on top of what I posted in the previous post. Here’s the code for the “OpenStreetMap”, “OpenStreetMapMode” and “OpenStreetMapTileSource” objects: using System; using Microsoft.Maps.MapControl; using Microsoft.Maps.MapControl.Core; namespace SilverlightApplication1 { public class OpenStreetMap : MapCore { public OpenStreetMap() : base() { this.Mode.SetView(new Location(), 2.0, 0.0, 0.0, false); this.Mode = new OpenStreetMapMode(); } } public class OpenStreetMapMode : RoadMode { public OpenStreetMapMode() : base() { var tileLayer = (MapTileLayer)this.Content; tileLayer.TileSources.Clear(); tileLayer.TileSources.Add(new OpenStreetMapTileSource()); } } public class OpenStreetMapTileSource : TileSource { public OpenStreetMapTileSource() : base("http://tile.openstreetmap.org/{2}/{0}/{1}.png") { } public override System.Uri GetUri(int x, int y, int zoomLevel) { return new Uri(string.Format(this.UriFormat, x, y, zoomLevel)); } } }   And, here’s an example of using this new “OpenStreetMap” control:   What About Navigation Controls? One side effect of creating this completely custom Map Control based off MapCore is that the other controls that the “Map” control includes automatically do not get displayed[...]



Display OpenStreetMap Imagery using Bing Maps Silverlight Control v1

Thu, 12 Nov 2009 09:02:00 -0500

The Bing Maps Silverlight SDK documentation on MSDN contains an article on Adding Tile Overlays to the Map, that demonstrates how to overlay your own map imagery over top of the Bing Maps Imagery. However, what if you want to completely replace the Bing Maps Imagery with some other Imagery like the OpenStreeMap Imagery? In the “Adding Tile Overlays to the Map” article it shows using a “LocationRectTileSource” to add the custom map imagery overlay. To implement the OpenStreetMap imagery you will need to create a simple class that inherits from “TileSource” since you wont be restricting the imagery to only a small portion of the map, but instead will be showing all the OpenStreetMap Imagery in place of the Bing Maps Imagery. First, Hide the Bing Maps Imagery Since we will be displaying the OpenStreetMap imagery instead of the Bing Maps Imagery, we want to prevent the Map control from loading/displaying the Bing Maps Imagery completely. To do this, all you need to do is set the Maps Mode to an instance of the “MercatorMode” object:   Display OpenStreetMap Imagery Next, we will create a simple “OpenStreetMapTileSource” class that inherits from “TileSource” that will be used to specify the location (URI) of the OpenStreetMap Imagery so the Map control can load and display it. Here’s the simple OpenStreetMapTileSource class: public class OpenStreetMapTileSource : Microsoft.Maps.MapControl.TileSource { public OpenStreetMapTileSource() : base("http://tile.openstreetmap.org/{2}/{0}/{1}.png") { } public override System.Uri GetUri(int x, int y, int zoomLevel) { return new Uri(string.Format(this.UriFormat, x, y, zoomLevel)); } }   Now to put the OpenStreetMapTIleSource in place and actually display the OpenStreetMap Imagery. To do this, we will add a new MapTileLayer to the Maps Children collection, and add an instance of our OpenStreetMapTileSource object to the MapTileLayer objects TileSources collection. Here’s the code to do this:



Getting Started with Bing Maps Silverlight Control v1.0

Thu, 12 Nov 2009 05:45:00 -0500

It’s been 8 months since the CTP release of the Bing Maps Silverlight Control at MIX’08, and finally this week Microsoft released the Final v1.0 release of the control to the web.  Now, we can all finally start using the Bing Maps Silverlight Control in Production! If you’ve worked with the CTP, then you’ll want to take a look at Ricky’s “Migrating from Bing Maps Silverlight CTP to Production Version” article. It explains all the stuff you’ll need to modify within your project in order to gracefully switch from the CTP to the v1 Map Control. Now for those of you who haven’t worked with the CTP… Where to Start? First you’ll need to make sure you have the following Tools installed: Visual Studio 2008 SP1 –or- Visual Web Developer 2008 Express with SP1 Silverlight 3 Tools for Visual Studio 2008 SP1 Of course you’ll also need to at least be familiar with the basics of Silverlight development. I’m mostly referring to XAML, so if your familiar with WPF that should be enough to get you started. For those Bing Maps (formerly Virtual Earth) developers new to Silverlight; If you need a little help getting started learning the basics, here are some resources that will help you get started: Getting Started Building Silverlight Applications at Silverlight.net Silverlight Learning Resources at Silverlight.net Now that you have all the necessary tools installed, you can go ahead and download and install the Bing Maps Silverlight v1 Control. Download: Bing Maps Silverlight Control SDK Version 1.0 The installer will install the Bing Maps Silverlight Control within the “Program Files” on your computer, along with an SDK Documentation Help (.chm) file. If you would like to see the Bing Maps Silverligth Control “In Action” and see the source code that powers each example, then you’ll want to check out the Bing Maps Silverlight Control Interactive SDK. Display a Basic Map Create a New Silverlight Application Project Run VIsual Studio 2008 and Create a New Project using the Silverlight Application template. In the “Add Silverlight Application” dialog box, select “Host the Silverlight application in a new Web site” option and click “OK”. You must select this option to create an ASP.NET Web Application Project, ASP.NET Website, or ASP.NET MVC Website because the URL Access Restrictions in Silverlight require the page that hosts the Map control be hosted using HTTP in order to load/access the Map TIle Imagery.   Add a Reference to Microsoft.Maps.MapControl.dll Go to the “Solution Explorer” and RIght-Click “ References” in the Silverlight Project (not the ASP.NET Web Application Project), and Select “Add Reference…”   Within the “Add Reference“ Dialog, Select the “Browse“ tab and navigate to the folder where the SDK is installed, then select the “Microsoft.Maps.MapControl.dll” and “Microsoft.Maps.MapControl.Common.dll” files. Note: Be Default the SDK is installed in this folder on x64 version of Windows: “C:\Program Files (x86)\Bing Maps Silverlight Control\V1\Libraries”. On x86 (or 32-bit) versions of Windows it’s installed within the “Program Files” folder instead of “Program Files (x86)”.   Display a Bing Maps Map! Add a Namespace declaration to Page.xaml for the Microsoft Maps.MapControl namespace. To do this add the following to the tag: xmlns:m=”clr-namespace:Microsoft.Maps.MapControl;ass[...]



Bing Maps Silverlight CTP: Plot/Edit Pushpin data via a ChildWindow

Tue, 04 Aug 2009 16:57:00 -0500

Recently I posted an example of using the Web.Maps.VE Bing Maps ASP.NET AJAX Server Control with the AjaxControlToolkit ModalPopup Extender over at the Simplovation Blog. Writing that example was rather simple since those two components/libraries are both written on top of ASP.NET AJAX and work extremely well together. This did however get me thinking about how to implement this same type of functionality using the Bing Maps Silveright Control CTP, and now that Silverlight 3 is out and it has a ChildWIndow control, this is actually really simple to implement using Silverlight as well. This was written for the Bing Maps Silverlight CTP Release. Download Example Code: Silverlight_BingMaps_CTP_EditPushpinsWithChildWindow.zip (235.44 kb) To the right you can see a screenshot of this code sample in action. The screenshot in the back is just displaying the plotted “pushpins” as red squares, with tooltip being displayed over the pushpin located in Seattle, WA. The front screenshot is displaying the “Edit” dialog using the ChildWindow control. Before you hit Run (F5) on this Example Code, you will need to have the Bing Maps Silverlight Map Control SDK CTP Installed. If you want to see how to use the Silverlight 3 ChildWindow control, I recommend you take a look at Jeff Prosise’s “Silverlight 3’s New Child Windows” post. Also, if you want to see how to work with the Bing Maps Silverlight Control CTP, then you may want to take a look at the following links: Getting Started with Bing Maps Silverlight Map Control SDK CTP Bing Maps Silverlight: Using MouseClick Event to Add “Pushpins” Bing Maps Silverlight: Basics of Adding Polygons and Polylines using XAML and Code Bing Maps Silverlight: Adding Media (Images, Video, etc.) to the Map Bing Maps Silverlight: Using Tile Layers to Overlay Custom Map Imagery Bing Maps Silverlight: Overlay OpentStreetMap, OpenAerialMap and Yahoo Map Imagery using Custom Tile Layers [...]



OpenStreetMap: Get FREE Web Mapping with Road Maps for your Applications

Mon, 03 Aug 2009 21:29:00 -0500

(image) OpenStreetMap has been around for awhile and provides free geographic data that can be used by anyone. The data is all community created/contributed and that’s why it’s free to use. Other mapping services such as Bing Maps for Enterprise and Google Maps license their geographic data from some other third party and that’s why they cost thousands of dollars per year to use within commercial applications.

Using OpenStreetMap with JavaScript

The screenshot on the left is showing an example of embedding OpenStreetMap imagery within a web page using OpenLayers. OpenLayers is an open-source, JavaScript-based Map control similar to the Bing Maps for Enterprise JavaScript Control and the Google Maps API; except it’s free to use and offers some decent mapping when combined with OpenStreetMap.

You can find examples of using OpenStreetMap with OpenLayers here: http://wiki.openstreetmap.org/wiki/OpenLayers

Using OpenStreetMap with Silverlight

Unfortunately, there aren’t any open-source Silverlight controls like OpenLayers, but you can easily use OpenStreetMap imagery with the Bing Maps for Enterprise Silverlight Control. Here’s an example of how to do this using the current Bing Maps for Enterprise Silverlight Control Beta release:

Virtual Earth Silverlight: Overlay OpenStreetMap, OpenAerialMap and Yahoo Map Imagery using Custom Tile Layers!




Bing Maps Silverlight CTP: Using MouseClick Event To Add "Pushpins"

Wed, 25 Mar 2009 22:38:00 -0500

In previous tutorials I covered the “Basics of Adding Polygons and Polylines” and “Adding Media (Images, Video, etc.)”, but what about handling user input via Map Events? Well, in this tutorial I’ll cover the basics of working with the Map.MouseClick Event (equivalent of the old “onclick” event in the Virtual Earth JavaScript Control). This was written for the Bing Maps Silverlight CTP Release. Adding a MouseClick Event Handler In order to wire things up to manipulate the Map using the MouseClick event, we must first attach an Event Handler to it. The Event Handler for the MouseClick event needs to be just like any other event handler in .NET; it must accept two parameters: 1) a “sender” object, and 2) an “EventArgs” object. Before we create our event handler, it’s worth noting that to be more specific, the value that gets passed to the “EventArgs” parameter of the Map.MouseClick event is actually of Type MapMouseEventArgs. The MapMouseEventArgs object has the following two properties: Handled – Gets or Sets a value indicating whether the Map event was handled. If you want to prevent the “default” event handling behavior from executing, then all you need to do is set this to True. ViewportPoint – Gets the viewport point where the mouse event occurred. This is a System.Windows.Point object that represents the X and Y coordinates where the mouse was clicked. To declare the MouseClick event handler a method that matched the following signature: void(object sender, MapMouseEventArgs e) Here’s an example Map.MouseClick event handler method: private void myMap_MouseClick(object sender, MapMouseEventArgs e) { } You can attach the above event handler from within code: myMap.MouseClick += new EventHandler(myMap_MouseClick); Or, from within XAML:   Get the Location (Lat/Long Coordinate) the Mouse was Clicked One thing that you may have noticed is the MapMouseEventArgs object that is passed to the MouseClick event handler doesn’t contain a “Location” or “LatLong” property of any kind. It’s seems odd at first that there’s no direct way of obtaining the Map Location (Lat/Long) of where the mouse was clicked, but with the help of a little helper method on the Map object itself we can pass in the ViewportPoint (X and Y Coordinates) value contained within the MapMouseEventArgs.ViewportPoint property and get back a Location object with Latitude/Longitude. To obtain the Location (Lat/Long) where the mouse was clicked, simply invoke the Map.ViewportPointToLocation method by passing in the MapMouseEventArgs.ViewportPoint value. The following line of code demonstrates how this can be done within the MouseClick Event Handler we defined above: var location = clickedMap.ViewportPointToLocation(e.ViewportPoint); Now that we have the  Location of where the mouse was clicked, we can directly access the Latitude and Longitude values. var lat = location.Latitude; var lng = location.Longitude;   Add a “Pushpin” at the Clicked Location Now that we have a MouseClick Event Handler in place, and we have access to the Location (Latitude/Longitude) where the mouse was clicked; we can go ahead and add a “Pushpin” to the Map at that Location. If you have any questions on how to add a Shape or “Pushpin” to the Map, I recommend reading the following two tutorials: Basics of Adding Polygons and Polylines using XAML and Code Adding Media (Images, Video, etc.) to the Map [...]



MIX'09: Virtual Earth Silverlight CTP Session Online for Viewing

Sat, 21 Mar 2009 16:46:00 -0500

The "Introducing the Microsoft Virtual Earth Silverlight Map Control CTP" session from MIX'09 by Chris Pendlton is now available for your viewing pleasure online.

http://sessions.visitmix.com/MIX09/T34F

Also, here it is below:

(object) (image)




Bing Maps Silverlight CTP: Overlay OpenStreetMap, OpenAerialMap and Yahoo Map Imagery using Custom Tile Layers!

Fri, 20 Mar 2009 18:51:00 -0500

UPDATE: I have written a newer version of this article to specifically target the latest Bing Maps Silverlight Control Version 1.0 Release. You can find the new article here: Display OpenStreetMap Imagery using Bing Maps Silverlight Control v1 In the “Using Tile Layers to Overlay Custom Map Imagery” article I showed you how to overlay your own Custom Map Imagery that you generated using the MapCruncher tool on top of the Map. Now, in this article I’ll show you what you need to know in order to overlay map imagery from other competing mapping services (OpenStreetMap, OpenAerialMap and Yahoo Maps). This allows you to easily build in functionality that allows your users to easily switch (with the click of a button or selection of a dropdown) which mapping service imagery is used to visualize the data in your application. This was written for the Bing Maps Silverlight CTP Release. Beware: This article is just a demo of how this is possible. If you do implement this, you need to keep in mind that you’ll need to then adhere to both the Virtual Earth Silverlight Control CTP Terms of Use and the Terms of Use for which ever mapping services data you are displaying. Before I begin, I’d like to thank the awesome guys that are working on the DeepEarth Project. Now to the exciting stuff! Overview of What’s Needed The steps to create a Tile Layer that displays Map Imagery from the mentions services is very similar to the method mentioned in the “Using Tile Layers to Overlay Custom Map Imagery” arcticle, with the exception that you need to create your own Custom Tile Source object that inherits from TileSource. Here’s the steps needed to do this: Create a Custom Tile Source (inheriting from TileSource) object  Define the “uriFormat” to be used to generate the Uri of the Map Images. Override the”GetUri” method. This method uses the “uriFormat” to generate the Uri of the Map Images. Add the Tile Source to the Map Create a MapTileLayer object instance Create an instance of you Custom Tile Source object Add the Custom Tile Source object to the MapTileLayer Set the MapTileLayer’s Opacity to the desired value Add the MapTileLayer to the Children collection of the Map The TileSource objects “GetUri” method takes the following 3 arguments: x – The horizontal position of the tile. y – The vertical position of the tile. zoomLevel – The zoom level of the tile. You then need to convert (within this method) the x, y, and zoomLevel values into the correct values to be passed using the uriFormat to load the map imagery tiles. This can take a little work in some cases (as with Yahoo Maps) and it an be straight forward in others (as with OpenStreetMap and OpenAerialMap). Also, when you’re showing Map Imagery that will completely overlay over the top of the Virtual Earth Imagery, it’s a good practice to set the Map’s Mode to an “Empty” mode that will prevent the Virtual Earth imagery from even being downloaded for display. This will increase performance a little (whether you notice it or not), and it will prevent you from using up unnecessary transactions using the Virtual Earth Web Service (this is how the control loads the Virtual Earth imagery behind the scenes.) Create a TileSource for OpenStreetMap First we need to create custom TileSource object, set the UriFormat to be used to generate the Imagery Uri, and then override the “GetUri” method wi[...]



Bing Maps Silverlight CTP: Using Tile Layers to Overlay Custom Map Imagery

Fri, 20 Mar 2009 18:47:00 -0500

One of the features that the Virtual Earth JavaScript Control has is the ability to add custom Tile Layers to overlay your own custom imagery over the map. The Virtual Earth Silverlight control also supports this feature. This was written for the Bing Maps Silverlight CTP Release. Before I begin to explain how to add custom Tile Layers to the Map it’s important to note that you can still use the MapCruncher tool to generate Map Imagery Tiles to be used with the custom Tile Layers. The specifics of using the MapCruncher tool to generate Map Imagery Tiles isn’t within the scope of this article. You can find a tutorial on how to use MapCruncher here: http://research.microsoft.com/en-us/um/redmond/projects/mapcruncher/tutorial/version3.0docs/index.htm Add Custom Tile Layer using Code Once you have some custom Map Imagery Tiles generated from using MapCruncher, you can then add them using an instance of the LocationRectTileSource object and adding it to a MapTileLayer on the Map. To do this we will following the below steps: Create a MapTileLayer object Create a LocationRect object that defines the bounding rectangle for our map tile overlay Create a LocationRectTileSource Point it to the Uri of our custom Map Imagery Tiles Set the Minimum and Maximum Zoom Levels (ZoomRange) that the imagery is to be visible within Set the Bouding Rectangle to the LocationRect object we previously created Add the LocationRectTileSource to the MapTileLayer’s TileSources collection property Set the MapTileLayer’s Opacity to the desired value Add the MapTileLayer to the Children collection of the Map Here’s some sample code that will add a custom Tile Layer using the imagery that the JavaScript Map Controls SDK uses as an example for this same thing: // Create a Tile Layer that will display our custom Map Imagery Tiles var customTileLayer = new MapTileLayer(); // Define the Bounding Rectangle LocationRect boundingRect = new LocationRect(     new Location(49, -123),      new Location(47, -121) ); // Create a LocationRectTileSource LocationRectTileSource customTileSource = new LocationRectTileSource(); // Set the Uri for the custom Map Imagery Tiles customTileSource.UriFormat = "http://dev.live.com/virtualearth/sdk/layers/lidar/{0}.png"; // Set the Min and Max Zoom Levels that the imagery is to be visible within customTileSource.ZoomRange = new Range(10, 18); // The bounding rectangle area that the tile overaly is valid in. customTileSource.BoundingRectangle = boundingRect; // Add the Tile Source to the Tile Layer customTileLayer.TileSources.Add(customTileSource); // Set the Tile Layer Opacity to a desired value customTileLayer.Opacity = 0.7; Map1.Children.Add(customTileLayer);   Hide Virtual Earth Imagery From Being Displayed Sometimes you may want to hide the Virtual Earth Imagery from being displayed altogether. To do this all you need to do is set the Map’s Mode property to a new instance of the MercatorMode object. Doing this allows you to show only your custom map imagery. Using XAML: Bing Maps Silverlight CTP: Adding Media (Images, Video, etc.) to the Map

Fri, 20 Mar 2009 18:43:00 -0500

This was written for the Bing Maps Silverlight CTP Release. In the previous tutorial (“Basics of Adding Polygons and Polylines using XAML and Code”) I mentioned that there is no Pushpin Shape Type in the new Virtual Earth Silverlight Map Control SDK CTP. Instead, the Silverlight control has the flexibility of plotting/displaying anything (as long as it inherits from UIElement) you want at a specific Latitude/Longitude Coordinate. This opens up a ton of UI options that can be built to allow the user to interact with the data being displayed. One thing to keep in mind when adding Images, Video and any other UIElements to the Map is that you’ll need to add them to a MapLayer, then add the MapLayer to the Map. This is required so that you can specify the Location to Plot the UIElement at. This is something that you’ll probably want to do anyway so you can easily control the layering of the elements that are plotted, or even easily show/hide groups of elements (by having a seperate MapLayer contain the elements for each specific group.) Let’s start plotting some cool stuff on a Map. Adding Images to the Map (aka “Pushpins”) When adding Images to the Map, the process is very similar to adding Polygons or Polylines, except you need to add Images to a MapLayer first, then add the MapLayer to the Map. The closest thing with the Silverlight Map Control to the “Pushpins” of the old JavaScript control is the ability to directly plot Images on the Map. // Create MapLayer MapLayer myLayer = new MapLayer(); // Create Image Image image = new Image(); // Set the Image Source image.Source = new BitmapImage(new Uri("pushpinImage.png", UriKind.Relative)); // Set Image Display Properties image.Opacity = 0.8; image.Stretch = Stretch.None; // Create a Location object that defines where the "Shape" will be plotted Location location = new Location() { Latitude = -10, Longitude = 10 }; // Center the image around the location specified PositionMethod position = PositionMethod.Center; // Add Image to the Layer myLayer.AddChild(image, location, position); // Add Layer to the Map Map1.AddChild(myLayer); Adding Video to the Map Plotting Video content on the Map is a good example of what some of the possibilities are opening up with this new Virtual Earth Silverlight Map Control. To do this all you need to do is create a MediaElement with its Source set to the Uri of a Video and add it to the Map in the same way as shown above with adding Images to the Map. // Create MapLayer MapLayer myLayer = new MapLayer(); // Create MediaElement MediaElement video = new MediaElement(); // Set the MediaElement Source to the Video video.Source = new Uri("http://mschnlnine.vo.llnwd.net/d1/ch9/8/9/1/1/6/4/ScottGuthrieSL3_ch9.wmv",         UriKind.RelativeOrAbsolute); // Set MediaElement Display Properties video.Opacity = 0.8; video.Width = 200; video.Height = 150; // Create a Location object that defines where the "Shape" will be plotted Location location = new Location() { Latitude = -10, Longitude = 10 }; // Center the image around the location specified PositionMethod position = PositionMethod.Center; // Add Image to the Layer myLayer.AddChild(video, location, position); // Add Layer to the Map Map1.AddChild(myLayer); Conclusion You can add any visual control/object that derives from UIElement to the Map using the same [...]



CTP: Bing Maps Silverlight CTP: Basics of Adding Polygons and Polylines using XAML and Code

Fri, 20 Mar 2009 18:40:00 -0500

This was written for the Bing Maps Silverlight CTP Release. Now that we’re familiar with the basics of the Virtual Earth Silverlight Map Control SDK CTP (from my Getting Started with Virtual Earth Silverlight CTP tutorial), we’re ready to move on to adding Shapes (Polygons and Polylines). After all what use is a Virtual Earth Map Control without plotting some data on it. If you’re not familiar with how to get a Map displayed within a Silverlight Application, I really encourage you to go take a look at my “Getting Started with Virtual Earth Silverlight Map Control SDK CTP” tutorial. Did you notice that I left out Pushpins? Well, this is actually because the Map control doesn’t have a Pushpin Shape Type; the only Shapes Types are Polygon and Polyline. The reason for this is because instead of limiting you to just Pushpins (a small icon of some sort) like the JavaScript Map Control; the Silverlight Control allows you to plot/display anything (as long as it inherits from UIElement) you want at a specific Latitude/Longitude Coordinate. Since, “Pushpins” are a newly changed concept with the Silverlight Map Control; I’ll be covering that is a separate tutorial that covers “Adding Media (Images, Video, etc.) to the Map”. Now let’s get to plotting some Polygons and Polylines! Adding Polygons to the Map To add a Polygon to the Map, you will need to create an instance of the MapPolygon object and add a collection of Location objects to its “Locations” property. You will also need to define the look of your Polygon by setting its “Fill”, “Stroke”, “StrokeThickness” and “Opacity” properties. The MapPolygon properties and what they do: Fill – A Brush object that defines how the inside of the Polygon is filled in. Stroke – A Brush object that defines how the border that outlines the Polygon will be drawn. StrokeThickness – A Double value that defines the thickness of the border that outlines the Polygon. Opacity – A Double value that defines the Opacity (or Transparency) of the Polygon. When adding Polygons to the Map you add your MapPolygon object instance to the Map.Children collection. Add a Polygon Programmatically using Code Here’s an example of adding a Polygon to a Map programmatically: MapPolygon polygon = new MapPolygon(); polygon.Fill = new SolidColorBrush(Colors.Red); polygon.Stroke = new SolidColorBrush(Colors.Yellow); polygon.StrokeThickness = 5; polygon.Opacity = 0.7; polygon.Locations = new LocationCollection() {     new Location(20, -20),     new Location(20, 20),     new Location(-20, 20),     new Location(-20, -20) }; Map1.AddChild(polygon); // Map1.Children.Add(polygon); // <—This also works just the same   Add a Polygon Declaratively using XAML One other neat thing that you can do is add Polygons to a Map declaratively using XAML. Here’s an example:



CTP: Getting Started with Bing Maps Silverlight CTP Map Control SDK

Fri, 20 Mar 2009 18:27:00 -0500

UPDATE: I have written a newer version of this article to specifically target the latest Bing Maps Silverlight Control Version 1.0 Release. You can find the new article here: Getting Started with Bing Maps Silverlight Control v1.0 It seems like forever since MIX’08 when a demo was shown of a new Silverlight-based Virtual Earth Map Control. Well, now FINALLY we actually have a version of the control to “play” around with. The reason I say “play” is because it’s still a CTP (Community Technology Preview). If you read the license file you’ll see that basically the most important points of Microsoft’s position on CTP’s are: 1) You can NOT use it in a production environment, and 2) It’s a Preview, so anything can change from now until the next release (CTP, Beta, whatever). Well, anyway… I introduce you to the Virtual Earth Silverlight Map Control SDK CTP! Before I dig into what’s needed to begin development, and show you how simple it is to use; here’s a few highlights of what’s so Awesome about the control. Why is the Virtual Earth Silverlight Map Control so Awesome?!? Here’s a few reason: Silverlight! – Silverlight itself is truly a high point with this new control. You can now Plot/Overlay Rich Media Content (Images, Video, and any Silverlight/XAML content you can think of!) over the Map! Performance! – If you’ve used the Virtual Earth JavaScript Map Control, then you must be familiar with the fact that the Map really starts to slow down when you try to plot something around 300+ Pushpins or a hand full of Polygons with 1000+ points each. With the new Silverlight control you can literally plot THOUSANDS of Pushpins on the Map and you wont render it useless like you would with the previous JavaScript control. Your limit is really only based on the Client Computer that is running the application, and I expect that it’ll probably improve a bit with Silverlight 3’s ability to utilize the local GPU. No More JavaScript or Browser Inconsistencies! – You no longer need to worry or hassle yourself with JavaScript and making sure it runs/works as expected in all the different web browsers (Internet Explorer, Firefox, Safari, etc.) No you can manipulate the map using pure .NET code. Don’t fret if you need to integrate with existing JavaScript code; you can always use Silverlight’s HTML Bridge to interact back and forth as needed. Virtual Earth! – And, last but not least, we can not forget that part of the Vast Awesomeness of this control is just due to the fact that it’s Virtual Earth Mapping!! What’s Needed to Get Started? Firstly, Download the Virtual Earth Silverlight Map Control SDK CTP from Microsoft Connect: http://connect.microsoft.com/silverlightmapcontrolctp Note: At the time of posting this (3/20/2009 6:26PM CST) the CTP Download is currently down. You can still go to the Microsoft Connect website and Register, then you’ll be able to download the bits when they’re back up. The download issue has been fixed. There is also a Virtual Earth Silverlight Map Control CTP Interactive SDK (in the same style of the Virtual Earth JavaScript control) here: https://sharepoint.connect.microsoft.com/silverlightmapcontrolctp/iSDK/default.htm Secondly, you’ll need a couple Tools installed first: Visual Studio 2008 SP1 –or- Visual We[...]



Virtual Earth Silverlight Control CTP Teaser and Some Initial Thoughts

Thu, 19 Mar 2009 18:12:21 -0500

Yesterday, the Virtual Earth Silverlight Control CTP (Community Technology Preview) was announced at MIX’09. I was also fortunate to get early access to the CTP, so I’ve been playing with it for a few days. I can’t show you any code yet (until it’s released publicly), but I can tell you a little about it for now. Once it’s released I’ll be posting some articles that range from Basic How-To to Implementing Some Cool Stuff; but you’ll have to wait a little bit for those. For now, here’s a little info… Combining the power of Silverlight and Virtual Earth Mapping makes for a pretty awesome combination. You can now build all the cool stuff you wanted to build with the JavaScript Map Control, Plus TONS More! Here’s a couple key feature points: Cross-Platform Support. No more hacky JavaScript to write; unless of course you want to use the Silverlight HTML Bridge to interface with existing JavaScript code (think about how you could upgrade existing mapping web applications with this). Ability to Plot ANY Rich Content on the Map. Including Videos or any other Custom Controls. Increased Performance! Since the control uses Silverlight it takes full advantage of the performance benefits that Silverlight has to offer. Remember how slow the JavaScript Map Control can become? Map wraps across the International Date Line. This is an issue with the JavaScript Map Control, since it doesn’t allow you to plot Polygons or Polylines that span across the International Date Line. This is no longer an issue with the Silverlight Map Control. Here’s a couple screenshots of the Map in action: The first one shows a Polygon, Polyline and a Video plotted on the Map. The second one shows a Tooltip being displayed from the mouse hovering over a Polygon. Not a final release, and the JavaScript Map Control does offer some features that the Silverlight control does not: For example, the Silverlight control does not have Birdseye or 3D map modes. They haven’t mentioned when/if the Silverlight control may have these, but I’m hoping they do make it into the control before RTW to keep it on par with the existing JavaScript Control. Also keep in mind that this is just a CTP (Community Technology Preview); which means: 1) You can NOT use it in Production, and 2) The next release (CTP, Beta, Whatever) may contain (and probably will) breaking changes. So, if you’re looking for a Silverlight Map Control you can roll into Production Today, then you’ll want to check out the DeepEarth Project. Keep an eye out for my tutorials as I release them, starting tomorrow as soon as the CTP is Released To Web (RTW).[...]