Geoffrey Emery
Tech Goodness

Virtual Earth Web Service – Get your search on

January 23, 2009 08:28 by gemery

In this tutorial we are going to look at what you need to get search going using virtual earth web services. Search provides a robust way to find local businesses and attractions around a given location.

 

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 Search Sample</title>
</head>
<body style="font-family:Arial; font-size:small">
    <form id="form1" runat="server">
    <div style="font-weight:bold">
        Virtual Earth Web Services Search 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>
                <table>
                    <tr>
                        <td>What:</td>
                        <td><asp:TextBox runat="server" ID="TextBox_What" Width="250" /></td>
                    </tr>
                    <tr>
                        <td>Where:</td>
                        <td><asp:TextBox runat="server" ID="TextBox_Where" Width="250" /></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td align="right">
                            <asp:Button runat="server" Text="Search and show map" ID="Button_SearchWithMap" 
                                onclick="Button_SearchWithMap_Click" />
                        </td>
                    </tr>
                </table>
 
                <table>
                    <tr>
                        <td>
                            <div runat="server" id="Div_SearchResults" style="width:300px; height:400px; overflow:auto"></div>
                        </td>
                        <td>
                            <asp:Image runat="server" ID="Image_Map" Visible="false" Height="400" Width="400" />
                        </td>
                    </tr>
                </table>
            </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

Geocode Service

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

Imagery Service

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

Search Service

http://staging.dev.virtualearth.net/webservices/v1/searchservice/searchservice.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

protected void Page_Load(object sender, EventArgs e)
 {
     if (Page.IsPostBack == false)
     {
         this.TextBox_What.Text = "Coffee Shops";
         this.TextBox_Where.Text = "Fullerton California";
     }
 }

 

protected void Page_Load(object sender, EventArgs e)
  {
      if (Page.IsPostBack == false)
      {
          this.TextBox_From.Text = "State College Blvd , Fullerton, CA 92831";
          this.TextBox_To.Text = "Golden Gate Bridge";  //Safeco Field
      }
  }

 

And finally add a handler for the button click there are a ton of comments in here so ill those be your guide feel to ping me with more questions plus down load the code and run it is the best way to go.

 

Start our search request

/// <summary>Executes a search with the what and where supplied in the UI</summary>
    /// <returns>SearchResponse for the executed search</returns>
    protected SearchResponse ExecuteSearch()
    {
        // Create a SearchRequest with a StructuredQuery
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.Credentials = new VESearchService.Credentials();
        searchRequest.Credentials.Token = Utils.Token(Request.UserHostAddress);
 
        //Create a structured Search Query object
        VESearchService.StructuredSearchQuery structuredQuery = new StructuredSearchQuery();
        structuredQuery.Keyword = this.TextBox_What.Text.Trim();
        structuredQuery.Location = this.TextBox_Where.Text.Trim();
 
        searchRequest.StructuredQuery = structuredQuery;
 
        // Execute the search
        SearchServiceClient searchServiceClient = new SearchServiceClient();
        SearchResponse searchResponse = searchServiceClient.Search(searchRequest);
 
        return searchResponse;
    }

Now add the search results to a map!

/// <summary>Executes a search and creates a map that displays the search results.</summary>
  /// <param name="sender">The sender</param>
  /// <param name="e">Event arguments</param>
  protected void Button_SearchWithMap_Click(object sender, EventArgs e)
  {
      // Clear our results output
      this.Div_SearchResults.InnerHtml = "";
 
      // Execute a search
      SearchResponse searchResponse = this.ExecuteSearch();
      bool foundSearchResult = false;
 
      // Create a map, specify search results with the map request so pushpins will be rendered on the map
      if (searchResponse != null)
      {
          // Create a new MapUriRequest
          VEImageryService.MapUriRequest mapUriRequest = new MapUriRequest();
 
          // Create a new Credential object and provide the token
          mapUriRequest.Credentials = new VEImageryService.Credentials();
          mapUriRequest.Credentials.Token = Utils.Token(Request.UserHostAddress);
 
          //Set the size of the map requested to the size of the image control
          mapUriRequest.Options = new MapUriOptions
          {
              ImageSize = new VEImageryService.SizeOfint
              {
                  Height = Convert.ToInt32(this.Image_Map.Height.Value),
                  Width = Convert.ToInt32(this.Image_Map.Width.Value)
              }
          };
 
          // Create a new pushpin list
          List<VEImageryService.Pushpin> pushpinList = new List<Pushpin>();
 
          // Add each of the search results to the pushpin list
          foreach (SearchResultSet searchResultSet in searchResponse.ResultSets)
          {
              int businessCounter = 0;
              foreach (BusinessSearchResult busniessSearchResult in searchResultSet.Results)
              {
                  foundSearchResult = true;
 
                  // Write the search result data to the info box
                  this.WriteInfo(++businessCounter + ") <b>" + busniessSearchResult.Name + "</b>");
                  this.WriteInfo("&nbsp;&nbsp;&nbsp;&nbsp;" + busniessSearchResult.Address.FormattedAddress);
                  string website = "";
                  if (busniessSearchResult.Website != null)
                      website = "<a href='" + busniessSearchResult.Website.ToString() + "'>Website</a>";
                  this.WriteInfo("&nbsp;&nbsp;&nbsp;&nbsp;" + busniessSearchResult.PhoneNumber + "&nbsp;&nbsp;&nbsp;&nbsp;" + website);
                  this.WriteInfo("");
 
                  // Build out the pushpin and add it to the list
                  Pushpin pushpin = new Pushpin();
                  // push pin labels only support 2 characters
                  pushpin.Label = businessCounter.ToString(); // += "asdf";
 
                  // Just get the first location returned
                  if (busniessSearchResult.LocationData.Locations.Length > 0)
                  {
                      //this.WriteInfo("Location: " + busniessSearchResult.LocationData.Locations[0].Latitude + "," + busniessSearchResult.LocationData.Locations[0].Longitude);
                      pushpin.Location = new VEImageryService.Location();
                      pushpin.Location.Latitude = busniessSearchResult.LocationData.Locations[0].Latitude;
                      pushpin.Location.Longitude = busniessSearchResult.LocationData.Locations[0].Longitude;
                  }
 
                  pushpinList.Add(pushpin);
              }
          }
 
          // Add the pushpin list (as an array) to the MapUriRequest
          mapUriRequest.Pushpins = pushpinList.ToArray();
          ImageryServiceClient imageryServiceClient = new ImageryServiceClient();
 
          // Get the map and render it on the UI
          MapUriResponse mapUriResponse = imageryServiceClient.GetMapUri(mapUriRequest);
          this.Image_Map.ImageUrl = mapUriResponse.Uri;
          this.Image_Map.Visible = true;
      }
 
      if (foundSearchResult == false)
          this.WriteInfo("No search results for query");
  }

One Little helper function

/// <summary>Writes information to the UI</summary>
 /// <param name="html">HTML to write to the UI</param>
 protected void WriteInfo(string html)
 {
     this.Div_SearchResults.InnerHtml += html + "<br/>\n";
 }

 

Bam there you have Search with map imagery of where everything is.

There is a ton more information that you can pull out of the objet I kept to just a few things for simplicity.

Download the code here.

image

One Last look at the finished Product

image

 

 

 

 

 

 

 

 


Related posts

Comments

November 11. 2009 01:51

payday loans

Hmmm interesting stuff

payday loans

Comments are closed