Bing Maps JS: Calculate Area of Circle and Draw Circle on Map

2. March 2010

Something that can be usefull at times in being able to calculate the total Area of a circle, especially when plotting it on a map. So, I decided to slightly modify my "Draw a Circle Radius Around Lat/Lng Point" to make it also calculate the Area of the circles and display that value within the TItle of the Circle Shapes Pushpin.

Remember, back in Trig class, it's fairly simple to calculate the area of a circle. You just Multiply Pi by the Radius Squared.

Area = Pi * (radius * radius)

Anyway, I know this isn't a very advanced math problem. If fact it's much simpler than calculating out the point that make up the circle in the first place. However, I thought I'd post it since it may be usefull to someone that maybe doesn't quite remember this little trick from Trig class.

Here's the full, modified source code that contains this:

DrawRadiusCalcArea_JS_BingMaps.zip (3.28 kb)

Bing Maps, JavaScript , ,

Community Coding Contest 2010 - Looking for Input and Prizes

4. January 2010

Now that it's 2010, and over a year since the first Community Coding Contest came to an end, I'm thinking about running the contest again in 2010.

Last time it ran for 3 months and we had 6 really great entries. This time around I'm thinking that it may be better to accept entries for 6 months, and have the voting run for a full month. This will give much more time for entries to be submitted, and for people to work on their entries before submitting and/or voting begins.

These are just some initial thoughts, and I'm going to need input on everything from YOU (the community) before I can make a final decision as to when and how to run the contest again. I'd really appreciate if you could fill out the following survey and tell us what you think.

Community Coding Contest 2010 Pre-Contest Survey

Also, we will need some prizes donated before the contest will be able to go on. If you or your company are interested in donating prizes or monetary support (web hosting fees, mailing expenses, etc.) for the contest, please contact the contest directly here: http://communitycodingcontest.org/contact.aspx

You can view the official contest website here: http://communitycodingcontest.org

Thanks, and I look forward to hearing more about what everyone thinks!

asp.net, ASP.NET MVC, Bing Maps, C#, General, Silverlight, vb.net , , , ,

Prototype of OpenStreetMap Silverlight Control using DeepEarth and Bing Maps SDK

13. November 2009

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:

<UserControl x:Class="SilverlightApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:map="clr-namespace:Microsoft.Maps.MapControl;assembly=Microsoft.Maps.MapControl"
    xmlns:local="clr-namespace:SilverlightApplication1"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
    <Grid x:Name="LayoutRoot">
        <local:OpenStreetMap Name="map">
            <local:OpenStreetMap.Children>
                <map:MapLayer>
                    <Image Source="BluePin.png" Opacity="0.8" Stretch="None" map:MapLayer.Position="42.16, -95"></Image>
                </map:MapLayer>
            </local:OpenStreetMap.Children>
        </local:OpenStreetMap>
    </Grid>
</UserControl>

 

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.

The “Map” control displays the “MapControlNavigationBar” control via the “MapForeground” object, however due to the MapForeground constructor that lets you tell it what MapBase object to attach to being marked “internal” is seems that it can’t be easily reused.

However, with a little help from the newest controls in developments within the DeepEarth project, you can fairly simply modify the Bing Maps Navigation control within the DeepEarth project to be used with the new “OpenStreetMap” control.

Here’s the code I worked up for a DeepEarth NavigationPanel for the “OpenStreetMap” control created earlier:

using System;
using System.Windows;
using DeepEarth.Client.BingMaps.Convertors;
using DeepEarth.Client.Common;
using GeoAPI.Geometries;
using GisSharpBlog.NetTopologySuite.Geometries;
using Microsoft.Maps.MapControl;
using Point = System.Windows.Point;
using Microsoft.Maps.MapControl.Core;

namespace NewDeepEarth.NavigationPanel
{
    public class NavigationPanel : DeepEarth.Client.Controls.NavigationPanel.NavigationPanel, IMapControl<MapCore>
    {
        private string mapName;

        public NavigationPanel()
        {
            Loaded += CoordinatePanel_Loaded;
        }

        public override double ZoomLevel
        {
            get
            {
                if (MapInstance != null)
                {
                    return MapInstance.ZoomLevel;
                }
                return 0;
            }
            set
            {
                if (MapInstance != null)
                {
                    MapInstance.ZoomLevel = value;
                }
            }
        }

        public override ICoordinate Center
        {
            get
            {
                if (MapInstance != null)
                {
                    return CoordinateConvertor.Convert(MapInstance.Center);
                }
                return new Coordinate(0, 0);
            }
            set
            {
                if (MapInstance != null)
                {
                    MapInstance.Center = CoordinateConvertor.ConvertBack(value);
                }
            }
        }

        #region IMapControl<MapCore> Members

        public string MapName
        {
            get { return mapName; }
            set
            {
                mapName = value;
                setMapInstance(MapName);
            }
        }

        public MapCore MapInstance { get; set; }

        public new void Dispose()
        {
            MapInstance = null;
            base.Dispose();
        }

        public override void PanMap(int deltaX, int deltaY)
        {
            if (MapInstance != null)
            {
                NewDeepEarth.Client.BingMaps.Utilities.Pan(deltaX, deltaY, MapInstance);
            }
        }

        #endregion

        private void CoordinatePanel_Loaded(object sender, RoutedEventArgs e)
        {
            setMapInstance(MapName);
        }

        private void setMapInstance(string mapname)
        {
            MapInstance = Utilities.FindVisualChildByName<MapCore>(Application.Current.RootVisual, mapname);
        }

    }
}

Also, hers a small utility method that I needed to modify slightly within the DeepEarth project to get the above NavigationPanel to work:

using Microsoft.Maps.MapControl.Core;
using Point = System.Windows.Point;

namespace NewDeepEarth.Client.BingMaps
{
    public static class Utilities
    {
        // Convert to accept Bing Maps "MapCore" instead of "Map" object
        public static void Pan(double deltaX, double deltaY, MapCore map) //Map map)
        {
            Point center = map.LocationToViewportPoint(map.Center);
            center.X = center.X + deltaX;
            center.Y = center.Y + deltaY;
            map.Center = map.ViewportPointToLocation(center);
        }
    }
}

 

Suggestion for the DeepEarth Preview Controls

One big suggestion I have for the DeepEarth projects new Preview Controls is to make the Bing Maps objects/libraries within the project use/accept “MapCore” or “MapBase” where ever it can instead of “Map”. This way as much of the DeepEarth code can be reused, without modification, when building a completely custom Map Control using the Bing Maps Silverlight SDK.

A perfect example of this are the modifications I needed to make to the NavigationPanel object and Utilities.Pan method posted above. By simply changing them from referencing/using “Map” to “MapCore” instead, they can not be used with any Map Control built using the Bing Maps Silverlight SDK.

Conclusion

Even though the above code works, it’s really just a prototype of what can be done using the current Preview controls within the DeepEarth project along with the new Bing Maps Silverlight Control. There is definitely some cool stuff to be done with both the Bing Maps Silverlight SDK and the DeepEarth project!

Anyway, here’s a download link to the full code of the project for the above code:

C#, Bing Maps, Silverlight , , , ,

Display OpenStreetMap Imagery using Bing Maps Silverlight Control v1

12. November 2009

BingMapsSilverlight_OpenStreetMap 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:

<UserControl x:Class="BingMapsSilverlightApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:m="clr-namespace:Microsoft.Maps.MapControl;assembly=Microsoft.Maps.MapControl"
    xmlns:mCore="clr-namespace:Microsoft.Maps.MapControl.Core;assembly=Microsoft.Maps.MapControl">
    <Grid x:Name="LayoutRoot">
        <m:Map>
            <m:Map.Mode>
                <!-- Do Not Display Bing Maps Imagery -->
                <mCore:MercatorMode></mCore:MercatorMode>
            </m:Map.Mode>
        </m:Map>
    </Grid>
</UserControl>

 

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:

<UserControl x:Class="BingMapsSilverlightApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:m="clr-namespace:Microsoft.Maps.MapControl;assembly=Microsoft.Maps.MapControl"
    xmlns:mCore="clr-namespace:Microsoft.Maps.MapControl.Core;assembly=Microsoft.Maps.MapControl"
    xmlns:local="clr-namespace:BingMapsSilverlightApplication1">
    <Grid x:Name="LayoutRoot">
        <m:Map>
            <m:Map.Mode>
                <!-- Do Not Display Bing Maps Imagery -->
                <mCore:MercatorMode></mCore:MercatorMode>
            </m:Map.Mode>
            <m:Map.Children>
                <m:MapTileLayer>
                    <m:MapTileLayer.TileSources>
                        <!-- Display OpenStreetMap Imagery -->
                        <local:OpenStreetMapTileSource></local:OpenStreetMapTileSource>
                    </m:MapTileLayer.TileSources>
                </m:MapTileLayer>
            </m:Map.Children>
        </m:Map>
    </Grid>
</UserControl>

 

Conclusion

It’s really pretty simple to display your own custom map tile image sets and even completely replace the Bing Maps Imagery with the new control. If your interested in seeing how to display Yahoo Maps imagery within the control, then you’ll want to refer to my previous article on doing this with the CTP version of the Bing Maps Silverlight Control.

C#, Bing Maps, Silverlight , , ,

Getting Started with Bing Maps Silverlight Control v1.0

12. November 2009

BingMapsRTW_BasicMapIt’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:

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:

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.
    BingMapsRTW_CreateSilverlightProject
  • 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.
    BingMapsRTW_CreateHostWebsite 
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…
    BingMapsRTW_AddReference 
  • 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)”.

    BingMapsRTW_AddReferenceBrowse 
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 <UserControl> tag:
    xmlns:m=”clr-namespace:Microsoft.Maps.MapControl;assembly=Microsoft.Maps.MapControl”
  • Add the Map Control to the Page by adding the following tag within the Grid in the Page:
    <m:Map></m:Map> The resulting Page.xaml will look like this:
    <UserControl x:Class="BingMapsSilverlightApplication1.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
        xmlns:m="clr-namespace:Microsoft.Maps.MapControl;assembly=Microsoft.Maps.MapControl"
        mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
        <Grid x:Name="LayoutRoot">
            <m:Map></m:Map>
        </Grid>
    </UserControl>
    Now, when you run the application (press F5 within Visual Studio) you will see a fully interactive Bing Maps map displayed.
    BingMapsRTW_BasicMap

BingMapsRTW_BasicMapWithDevAccountSignUpWarningSetting Up a Bing Maps Developer Account

When running the above example you may have noticed the “Invalid Credentials. Sign up for a developer account at: http://www.microsoft.com/maps/developers” message being displayed over top of the Map. This is because in order for you to use the Silverlight Map control within an application, Microsoft is requiring you to setup a Developer Account for the domain you will be hosting your application in.

Setup a Bing Maps Developer Account
  • Go to the Bing Maps Account Center at https://www.bingmapsportal.com
  • Click the “Create an Account” link on the left side of the site.
  • Sign in with your Windows Live ID
  • Enter it the required Account Details
Get a Bing Maps Key
BingMapsRTW_CreateBingMapsKey
  • Once you have created a Bing Maps Developer Account, just click the “Create or view keys” link on the left side of the Bing Maps Account Center website.
  • Type in some Application Name. This is your name for the application.
  • Type if the Application URL. This is the domain name that you will be hosting the application at.
  • Click the “Create key” button. Now you have a Bing Maps Key that you can use within your application to get rid of that pesky little warning message displayed over the top of the Map and everything on it.
    Note: For testing purposes I entered in an Application Name of “Test” and Application URL of “http://localhost”. This way I have a Bing Maps Key to use for testing/playing with the Silverlight Map Control that wont track any usage to the application I’ll eventually build.
Use the Bing Maps Key within Your Application

Now that you have a Bing Maps Key for your application, you can set your Map within that application to use this key.

To do so, just set the Map controls “CredentialsProvider” property value within XAML to the Bing Maps Key. Just copy and paste the key from the Bing Maps Account Center into your XAML code.

<UserControl x:Class="BingMapsSilverlightApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:m="clr-namespace:Microsoft.Maps.MapControl;assembly=Microsoft.Maps.MapControl"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
    <Grid x:Name="LayoutRoot">
        <m:Map CredentialsProvider="[Bing Maps Key Here]"></m:Map>
    </Grid>
</UserControl>

 

Set Map Properties Declaratively Using XAML and Programmatically Using Code

You can change/set the Bing Maps Controls properties Declaratively using XAML, and Programmatically using Code.

Below is an example of setting the Map Mode to Aerial using XAML:

<UserControl x:Class="BingMapsSilverlightApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:m="clr-namespace:Microsoft.Maps.MapControl;assembly=Microsoft.Maps.MapControl"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
    <Grid x:Name="LayoutRoot">
        <m:Map Mode="Aerial"></m:Map>
    </Grid>
</UserControl>

 

Below is an example of setting the Map Mode to Aerial using C# code:

using System.Windows.Controls;
using Microsoft.Maps.MapControl;

namespace BingMapsSilverlightApplication1
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            Map1.Mode = new AerialMode();
        }
    }
}

 

First, in order to access the Map Control programmatically you’ll need to assign its “Name”  property within XAML so you have a name to reference it by; like the following:

<UserControl x:Class="BingMapsSilverlightApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:m="clr-namespace:Microsoft.Maps.MapControl;assembly=Microsoft.Maps.MapControl"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
    <Grid x:Name="LayoutRoot">
        <m:Map Name="Map1"></m:Map>
    </Grid>
</UserControl>

 

Additional Articles

Here are some links to additional articles on using the Bing Maps Silverlight Version 1.0 Control:

Conclusion

It’s pretty exciting that we now have a Bing Maps Silverlight control to use within our applications, and finally there is an option other than the JavaScript Control that has far superior performance when plotting over just a couple hundred Pushpins. Plus the Silverlight controls bring the full power of Silverlight to Bing Maps development; which allows for much richer mapping applications to be built.

Keep an eye out, I’ll be posting more articles/tutorials to help you out in exploring this shiny, new Bing Maps Silverlight Control.

Bing Maps, C#, Silverlight , , ,

MvcMaps Preview 1 – A Unified Bing/Google Maps API for ASP.NET MVC

2. November 2009

I spent some time lately working on bringing some of the concepts of Web.Maps.VE to ASP.NET MVC. The concepts I’m referring to are Simplicity and Ease of Development in making the implementation of mapping within ASP.NET MVC applications as simple as possible along with the Flexibility and Customizability of the Base Mapping API itself. Then I thought, Since I’m building an abstraction layer to simplify Bing Maps development, why not implement it in a flexible manor as to be able to support other Mapping API’s as well?

The result of such an effort in a nice Unified API that allows virtually the same code to be written when implementing either Bing Maps or Google Maps. In fact, all you need to do to change your application over to using one mapping provider instead of the other is to just change a single line of code.

Sound too good to be true?

I introduce you to the all new “MvcMaps” project, and I’m releasing it as Open Source under the Microsoft Public License.

Source Code: MvcMaps Preview 1 (698Kb)

Preview Release?

This initial release is just a “Preview” release and isn’t really meant for production use, although there’s absolutely nothing stopping you from using it in such an environment.

Introduction

The above source code download link contains the full source code for the component, plus a very basic “Interactive SDK” style website demonstrating some basic examples of using it.

The following snippet is the most basic example of how to add both a Bing Map and a Google Map within a View:

<%@ Import Namespace="MvcMaps" %>

<style type="text/javascript">
.BingMap
{
    width: 600px;
    height: 400px;
    border: solid 1px black;
}
.GoogleMap
{
    width: 600px;
    height: 400px;
    border: solid 1px black;
}
</style>

<h3>Bing Map</h3>
<% Ajax.BingMap()     // Create a Bing Map
    .CssClass("BingMap") // Define the CSS Style to use. These specify the Maps Size
    .Render();           // Render all the HTML / JavaScript necessary to create the Map to Server.Response
    %>

<h3>Google Map</h3>
<% Ajax.GoogleMap()      // Create a Google Map
    .CssClass("GoogleMap")  // Define the CSS Style to use. These specify the Maps Size
    .Render();              // Render all the HTML / JavaScript necessary to create the Map to Server.Response
    %>

 

Notice that the code is idential, except for the “BingMap” and “GoogleMap” parts. That is how you define the specific mapping provider to use, but the rest of the code is the same.

Plotting Pushpins, Polylines and Polygons

Adding some Pushpins, Polylines and Polygons is extremely simple, and its the same code for both Bing Maps and Google Maps!

Here’s a basic example of adding one of each:

<% Ajax.BingMap().CssClass("BingMap")
    // Add Pushpin Shape
    .AddPushpin(
        new Pushpin(39.9097362345372, -97.470703125,
             "Some Pushpin Title", "Some Pushpin Description")
        )
    
    // Add Polyline Shape
    .AddPolyline(
        new Polyline(new List<LatLng>() {
            new LatLng(48.166085, -121.11328),
            new LatLng(34.270835, -118.34472),
            new LatLng(43.041543, -87.901954),
            new LatLng(38.889546, -77.035338)
        }) {
            LineColor = "#0000FF",
            LineWeight = 6
        }
    )
    
    // Add Polygon Shape
    .AddPolygon(
        new Polygon(new List<LatLng>() {
            new LatLng(34.270835, -118.34472),
            new LatLng(43.041543, -87.901954),
            new LatLng(38.889546, -77.035338)
        }) {
            FillColor = "#00ff00",
            FillOpacity = 0.5,
            LineWeight = 2,
            LineColor = "#FF0000"
        }
    )
    
    // Render Map (HTML and JavaScript) to the Page
    .Render()
%>

 

Dynamic / Interactive Style Map

One of the coolest features I’ve built into the component so far is the ability to extremely easily add Dynamic / Interactive Style Map.

You probably wouldn’t believe me if I explained in words how simple it is to add a dynamic style map, so instead I’ll just show you the most basic code to get it working.

Here’s the code to add the Map to the Page. In this example you just tell the Map what Controller and Action to call to get the Map data to be displayed.

<% Ajax.BingMap()
    .CssClass("BingMap")
    .DynamicMap( new { controller = "DynamicMap", action = "SchoolDistricts" })
    .Render();
%>

 

Then you define your Controller Action, make it accept the Map View (or Map Bounds) which are essentially the Min and Max Lat/Lng values of the visible area on the client, and then you just return a “MapDataResult” object that contains the Pushpins, Polylines and Polygons to be plotted.

The following example demonstrates searching an XML file for School Districts within the Maps Viewable Area, and then plots them on the Map using Pushpins. As of MvcMaps Preview 1, only Pushpins are supported with the MapDataResult object.

public class DynamicMapController : Controller
{
    public ActionResult SchoolDistricts(double minLat, double maxLat, double minLng, double maxLng)
    {
        // Query and Get all School Districts within the passed in "Map View".
        var doc = XDocument.Load(Server.MapPath("~/App_Data/WISchoolDistricts.xml"));
        var schooldistricts = (from d in doc.Element("schooldistricts").Elements("schooldistrict")
                        where double.Parse(d.Attribute("latitude").Value) >= minLat
                        && double.Parse(d.Attribute("latitude").Value) <= maxLat
                        && double.Parse(d.Attribute("longitude").Value) >= minLng
                        && double.Parse(d.Attribute("longitude").Value) <= maxLng
                        select d
                    );

        // Generate "Pushpin" objects for each School District to be Plotted on the Map.
        var pushpins = (from d in schooldistricts
                        select(new Pushpin(
                            double.Parse(d.Attribute("latitude").Value),
                            double.Parse(d.Attribute("longitude").Value)
                        ){
                            Title = d.Attribute("name").Value,
                            Description = d.Attribute("address").Value
                        }));

        // Return a "MapDataResult" object that contains all the data that is to be Plotted on the Map.
        return new MapDataResult()
        {
            Pushpins = pushpins
        };
    }
}

 

Yes it really is that simple!!

How to Customize the Dynamic Map

The Dynamic Map example above is nice and simple, but if you need to customize the client-side map behavior somehow, don’t worry, there are “override” hooks built in to the component that allow you to override the complete behavior of the map in how it displays the data, or just execute some custom code on the returned data after it’s already been plotted.

You can use the DynamicMap  DataLoad option to specify a JavaScript function to get called every time map data is automatically loaded. The following example displayed the total number of Pushpins currently plotted in a SPAN tag above the Map. The “data” parameter on the function is the data object that is returned from the MapDataResult passed down from the controller action method.

Pushpin Count: <span id='lblPushpinCount'></span><br />
<% Ajax.BingMap()
    .CssClass("BingMap")
    .DynamicMap(
        new { controller = "DynamicMap", action = "SchoolDistricts" },
        new DynamicMapOptions() {
            DataLoaded = "function(data) { $('#lblPushpinCount').html(data.pushpins.length); }"
        })
    .Render();
%>

 

Also, you can use the DynamicMap DisplayData option to completely override the maps default behavior of plotting the data. Just in case you need to completely customize it, and the default behavior just doesn’t cut it. The following example plots the Pushpins returned and displays the total number of pushpins in a SPAN tag above the Map:

Pushpin Count: <span id='lblPushpinCount'></span>
<% Ajax.BingMap()
    .CssClass("BingMap")
    .DynamicMap(
        new { controller = "DynamicMap", action = "SchoolDistricts" },
        new DynamicMapOptions() {
            DisplayData = "DynamicMap_DisplayData_Handler"
        })
    .Render();
%>

<script type="text/javascritp">
function DynamicMap_DisplayData_Handler(data) {
    // Method gets called with "this" equaling the Mvc.Maps JavaScript Map Object
    
    // Clear All Currently Plotted Data
    this.clearDynamicMapData();
    
    // Plot New Pushpins that were Loaded
    this.plotPushpins(data.pushpins);

    // Display Pushpin Count
    $('#lblPushpinCount').html(data.pushpins.length);
}
</script>

 

Map Load Event

In case you need to execute some code on the Page as soon as the Map has finished loading, you can specify any JavaScript code you need to be executed.

<%-- Pass in JavaScript as String --%>
<% Ajax.GoogleMap()
        .Load("alert('Map Loaded!');")
        .Render();
        %>
        
<%-- Use Lambda Expression to define JavaScript code --%>
<% Ajax.GoogleMap()
        .Load( () => {%>
            alert('Map Loaded!');
            // var map = this.mapObject  //<-- get ref to underlying map providers object
        <%})
        .Render();
        %>

When specifying code to execute on the Load event, the context of the “this” keyword will be a reference to the client-side MvcMaps Map Object. To get a reference to the underlying Map Providers object (VEMap or GMap2), just access it’s “mapObject” property like so:

var map = this.mapObject;

 

Conclusion

The MvcMaps project really makes it dead simple to implement mapping in an ASP.NET MVC Web Application. There’s no need to worry about all the tedious work that you used to have to do on every page.

I plan on building out a few more features into the component, and getting it to the point of a “Stable” release soon. I just wanted to share what I’ve done so far, so others can provide feedback.

If you have any comments and/or suggestions on the Preview 1 release, please either leave a comment here or post to the projects Discussion Forums.

Also, don’t forget to download the code and the “Interactive SDK” from the link at the top of this post.

Bing Maps, ASP.NET MVC, JavaScript , , ,

Easily Convert Between HTML and RGB Colors using JavaScript

24. October 2009

To make things easier for converting between HTML Colors and RGB Colors using JavaScript I wrote the below “ColorConverter” object. This object has 2 methods that easily allow you to convert between HTML Colors (ex: #FF33C2) and RGB Colors (ex: 255, 0, 233). There isn’t anything built into JavaScript for doing this, and it can come in very handing when working with the Bing Maps VEColor object.

Usage Examples:

var rgb = ColorConverter.toRGB("#FF000A"); // returns {r:255, g:0, b:10}

var htmlColor = ColorConverter.toHTML(255,0,14); // returns "FF0021"

// Also supports 3 character HTML color values like the Web Browsers and CSS do
rgb = ColorConverter.toRGB("#DDD"); // returns {r:255, g:255, b:255}

Full Code for the “ColorConverter”:

(function(){
    window.ColorConverter = {
        toHTML: function(r, g, b){
            return $ensureHexLength(r.toString(16)) + $ensureHexLength(g.toString(16)) + $ensureHexLength(b.toString(16));
        },
        toRGB: function(color){
            var r, g, b;
            var html = color;
            
            // Parse out the RGB values from the HTML Code
            if (html.substring(0, 1) == "#")
            {
                html = html.substring(1);
            }
            
            if (html.length == 3)
            {
                r = html.substring(0, 1);
                r = r + r;
                
                g = html.substring(1, 2);
                g = g + g;
                
                b = html.substring(2, 3);
                b = b + b;
            }
            else if (html.length == 6)
            {
                r = html.substring(0, 2);
                g = html.substring(2, 4);
                b = html.substring(4, 6);
            }
        
            // Convert from Hex (Hexidecimal) to Decimal
            r = parseInt(r, 16);
            g = parseInt(g, 16);
            b = parseInt(b, 16);
        
            return {r: r, g: g, b: b};
        }
    };
    
    function $ensureHexLength(str){
        if (str.length == 1){
            str = "0" + str;
        }
        return str;
    }
})();

JavaScript, Bing Maps ,

Simplovation Web.Maps.VE v3.0 Now With FREE Edition!

26. August 2009

Simplovation Web.Maps.VE v3.0!Today, I just posted the latest Web.Maps.VE v3.0 release. The coolest thing about this new version is that is has a FREE Edition for non-commercial use!

Download Web.Maps.VE v3.0 FREE Edition!

There are a few new things in this latest release, but the most significant are the following performance updates:

  • Microsoft CDN (Content Delivery Network) Support Added. This helps improve the Bing Maps content delivery speed by up to 82%
  • JavaScript Performance Optimizations. All the JavaScript code internally within the control has been optimized to increase the overall speed of the Web.Maps.VE Map controls functionality.


Check out the following link to see what has all been included in this release:
https://simplovation.com/page/webmapsve30/roadmap.aspx

Also, this new version release is a completely FREE upgrade to all existing customers who have already purchased Web.Maps.VE v2.0. If you have previously purchased v2.0, then there is nothing required to obtain your v3.0 license other than going to the "My Licenses" page to download the DLL and License Activation File. If for some reason you have trouble obtaining your Free Upgrade to v3.0, please let us know and we'll get it activated as soon as possible.

asp.net, Bing Maps, JavaScript , , , , ,

Microsoft Killed the Virtual Earth ASP.NET Control

22. August 2009

Yesterday, Chris Pendleton officially announced that the Microsoft Virtual Earth ASP.NET Control is now Dead. Frankly, I’ve considered it “dead” for a long time now since it didn’t get updated much, didn’t have a completely full feature support, has a few bugs AND you couldn’t use it within your applications because it was just a Preview (CTP) anyway.

There are however a few good things to point out in the light of Microsoft killing its Virtual Earth ASP.NET Control:

If you were previously a fan of Microsoft’s control, then I recommend you check out the Simplovation Web.Maps.VE control. The licensing cost of the Simplovation control is fairly low and sold on a “per developer” basis. A single developer can purchase a single license and then use the Simplovation Web.Maps.VE control within as many (unlimited) applications as he wants/needs. Plus, the Simplovation Web.Maps.VE component can be redistributed along with any of those applications royalty free.

Go check it out: http://simplovation.com

Update 8/23/2009: John has created the CodePlex project to contain the source code for Microsoft’s control. http://bingmapsasp.codeplex.com/

asp.net, Bing Maps , ,

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

4. August 2009

Silverlight_BingMaps_CTP_EditPushpintsWithChildWindow 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:

Bing Maps, Silverlight ,