Geoffrey Emery
Tech Goodness

Virtual Earth Web Service - Get Server Tile Information

January 21, 2009 23:35 by gemery

In this tutorial we are going to look at what you need to get Tile information from a lat Lat Long(GeoCode) 

First a picture of what the final project will look like.

image

Note:

You must!  change the username in the web.config

    <add key="VEUsername" value="YourKey"/>
    <add key="VEPassword" value="YourPassword"/>

with your own information

image

1) Learn about Tokens

Okay, so, first things first, you need to authenticate - see my post Authentication and Tokens with Virtual Earth for authentication.

 

2) Create  AJAX Website in VS

Now that you are dialed in with your virtual earth tokens we are going to dive right into the web services. Lets go ahead and create a web site in VS. I am going to spice this up a bit and make it Ajax enabled. So go ahead and install AJAX or if you are using VS2008 sp 1 you should be already cool. Through in a script manager down and a update panel, and a update progress manager down on the page. This is the web form should look like in between the body tags should look this now.

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1" DisplayAfter="5">
           <ProgressTemplate>
              
           </ProgressTemplate>
       </asp:UpdateProgress>
       <asp:UpdatePanel ID="UpdatePanel1" runat="server">
           <ContentTemplate>
     
           </ContentTemplate>
       
       </asp:UpdatePanel>

 

3) Fill in the UI

The full default.aspx page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
 <head id="Head1" runat="server">
    <title>VE Web Services Imagery Tile Sample</title>
</head>
<body style="font-family:Arial; font-size:small">
    <form id="form1" runat="server">
    <div style="font-weight:bold">
        VE Web Services Imagery Tile Sample
    </div>
    <br />
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1" DisplayAfter="20">
            <ProgressTemplate>
                <img alt="updatepannel" src="Images/Update.gif" />
            </ProgressTemplate>
        </asp:UpdateProgress>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                Latitude: <asp:TextBox runat="server" ID="TextBox_Latitude" Width="125" />
                Longitude: <asp:TextBox runat="server" ID="TextBox_Longitude" Width="125" />
                Zoom Level: <asp:DropDownList runat="server" ID="DropDownList_ZoomLevel" />
                <br />
                <asp:Button runat="server" Text="Load Tile" ID="Button_LoadTile" 
                    onclick="Button_LoadTile_Click" />
                <br /><br />
                <div runat="server" id="Div_Info" />
                <asp:PlaceHolder runat="server" ID="PlaceHolder_MapImages" />
            </ContentTemplate>
        </asp:UpdatePanel>
    
    </div>
    </form>
</body>
</html>

4) Add the token to the web.config

<appSettings>
<!--
  This username and password is supplied for demo purposes only.  Please do not use this account for 
  anything other than this demo.  This account is monitored very closely and will be deactivated if used improperly
  To get your own Virtual Earth account, go to https://mappoint-css.live.com/MwsSignup/.
-->
<add key="VEUsername" value="YourToken"/>
<add key="VEPassword" value="YourPassword"/>
 
appSettings>

5) Add the Utility Class

You can do this as you like. I like to keep it separate. This takes the user key and password out of the web.config and news up a new VECredential for you

using System.Net;
using VEAuthenticationService;
using System.Text.RegularExpressions;
using System.Configuration;
    public static class Utils
    {
        private static string GetVEUsername() { return ConfigurationManager.AppSettings["VEUsername"].ToString(); }
        private static string GetVEPassword() { return ConfigurationManager.AppSettings["VEPassword"].ToString(); }
 
        public static string StripHTMLTags(string HtmlToStrip)
        {
            return Regex.Replace(HtmlToStrip, @"<(.|\n)*?>", string.Empty);
        }
 
        /// <summary>Returns a token from the Virtual Earth web service</summary>
        public static string Token(string ClientIP)
        {
            // This token will expire so that should be handled appropriately
            
                // Create a CommonService so we can make the request
                CommonService commonService = new CommonService
                {
                    // Supply your Virtual Earth credentials
                    // to get a Virtual Earth developer account, go to https://mappoint-css.live.com/MwsSignup/
                    Credentials = new NetworkCredential(Utils.GetVEUsername(), Utils.GetVEPassword())
                };
 
                // Create a token specification
                TokenSpecification tokenSpecification = new TokenSpecification
                {
                    // Token will expire in 60 minutes, max is 480 minutes
                    TokenValidityDurationMinutes = 60,
                    // Supply the client's IP address
                    ClientIPAddress = ClientIP
                };
                return commonService.GetClientToken(tokenSpecification);
          }
    }
 
 
 
 
 
 
 
 

6) Add the Update Image of your choice to to images folder for the update panel progress bar. –> this might make more sense after you download the project

7) add  your web service reference

Add a web service by right clicking on the project

image 

Imagery Service

http://dev.virtualearth.net/webservices/v1/imageryservice/imageryservice.svc?wsdl

8) Add the Guts

Now we add the GUTS to the code behind of the default.aspx page

First I am going to load the page up with some default values for testing purposes

Now for the fun stuff Getting the map from Microsoft

/// <summary>Loads a tile map tile that contains the specified latitude and longitude</summary>
   /// <param name="sender">The sender</param>
   /// <param name="e">Event arugments</param>
   protected void Button_LoadTile_Click(object sender, EventArgs e)
   {
       // Clear our outputs before we start.
       this.PlaceHolder_MapImages.Controls.Clear();
       this.Div_Info.InnerHtml = "";
 
       // Create a ImageryMetadataOptions object
       ImageryMetadataOptions imageryMetadataOptions = new ImageryMetadataOptions
       {
           // Specify the location, this will not necessarly be the middle of the tile
           Location = new Location
           {
               Altitude = 0,
               Latitude = Convert.ToDouble(this.TextBox_Latitude.Text),
               Longitude = Convert.ToDouble(this.TextBox_Longitude.Text)
           },
           ReturnImageryProviders = true,
           ZoomLevel = Convert.ToInt32(this.DropDownList_ZoomLevel.SelectedItem.ToString()),
       };
 
       // Create the metadata request, set the credentials, options and a map style
       ImageryMetadataRequest imageryMetadataRequest = new ImageryMetadataRequest
       {
           //add the metadata options object from above
           Options = imageryMetadataOptions,
           Style = MapStyle.AerialWithLabels
       };
 
       //New up a credentials object and set the token
       imageryMetadataRequest.Credentials = new VEImageryService.Credentials();
       imageryMetadataRequest.Credentials.Token = Utils.Token(Request.UserHostAddress);
 
       // Create the ImageryServiceClient
       ImageryServiceClient imageryServiceClient = new ImageryServiceClient();
 
       //and make the request
       ImageryMetadataResponse imageryMetadataResponse = imageryServiceClient.GetImageryMetadata(imageryMetadataRequest);
 
       // Write out the tile metadata to the UI
       foreach (ImageryMetadataResult imageryMetadataResult in imageryMetadataResponse.Results)
       {
           Image image = new Image();
           image.ImageUrl = imageryMetadataResult.ImageUri;
           this.PlaceHolder_MapImages.Controls.Add(image);
 
           this.WritePair("Image URI", imageryMetadataResult.ImageUri);
           if (imageryMetadataResult.Vintage != null)
           {
               this.WritePair("Vintage From", imageryMetadataResult.Vintage.From.ToString());
               this.WritePair("Vintage To", imageryMetadataResult.Vintage.To.ToString());
           }
           this.WritePair("Zoom Range From", imageryMetadataResult.ZoomRange.From.ToString());
           this.WritePair("Zoom Range To", imageryMetadataResult.ZoomRange.To.ToString());
           this.WriteInfo("");
       }
   }

And finally add a handler for the button click

/// <summary>Writes a name/value pair to the UI, name is bolded.</summary>
    /// <param name="name">Name of the name/value pair</param>
    /// <param name="value">Value of the name/value pair</param>
    protected void WritePair(string name, string value)
    {
        this.WriteInfo("<B>" + name + ":</B> " + value);
    }
 
    /// <summary>Writes information to the UI</summary>
    /// <param name="html">HTML to write to the UI</param>
    protected void WriteInfo(string html)
    {
        this.Div_Info.InnerHtml += html + "<br/>\n";
    }

and Bam there you have a map coming at you from a longitude latitude and you are spitting out the the map tiles information.

If you need to do this from a address look at this example.

http://blog.geoffreyemery.com/post/Virtual-Earth-Web-Services----GeoCoding-and-Reverse-GeoCoding.aspx

After you geocode it you can then send in another request to get a map.

Download the code here.

image

One Last look at the finished Product

image


Related posts

Comments are closed