Geoffrey Emery
Tech Goodness

Virtual Earth And PHP MySQL Intergration.

September 14, 2009 17:56 by Geoffrey Emery

Microsoft pushing an open source programming language? Indeed, there is an integration kit that gives PHP developers a boost creating a database-powered Bing Maps sites.

As most of you know who read  my blog virtual earth has a javascript api and could always be used in whatever programming or scripting language you wanted including plain old html.

In this case they are showing how you can use php specifically to form a GIS application with  options for MySQL and SQL Server Lite, though the latter also requires Windows hosting. In either case, you’ll also need PHP 5.2+ (required because the kit uses JSON). PHP and MySQL are the most common programming language and database, supported by almost every host, so these requirements are truly open to everyone, compared to usual examples of Microsoft technologies.

Bing Maps demo using PHP

The project site has a working demo, including the ability to add points. Or, download the code and try it on your own server. One of the best parts about this kit is that it comes ready to go with the same code as the demo. All you need to provide are database connection details.

The project was sponsored by Microsoft’s interoperability initiative and like their PHP on Windows efforts, it shows Microsoft is willing to reach out beyond their usual constituency to attract new developers. As a result, this useful resource gives PHP programmers and those that haven’t already adopted Microsoft’s suite of tools an easy introduction to programming Bing Maps.


Microsoft Virtual Earth Changes to Microsoft Bing Maps…Bing Bing.

May 28, 2009 15:09 by gemery

Microsoft announced that Microsoft® Virtual Earth™ is getting a new name.
Microsoft today announced the launch of an exciting new search product called Bing™. The new site will begin rolling out on June 1st and will be available to the world on June 3rd at www.Bing.com. Location information, mapping, and imagery are important investment areas for online search. Therefore, we have taken this opportunity to align the brand names of our mapping products offered to consumers and businesses with Bing.
On June 1, our mapping platform brand will change from Microsoft Virtual Earth to Bing maps for enterprise. Bing maps for enterprise is the mapping platform that underpins the Bing maps service (Bing.com/maps) and serves you and the thousands of organizations that use Microsoft mapping technology on their Web sites and in their applications. For more than 10 years, we have been providing mapping services to enterprises and organizations, and we continue to be committed to supporting you in achieving your goals.
What this means to you:
• • If you’re using the Virtual Earth AJAX, Virtual Earth Web Services, MapPoint™ Web Service, or Multimap APIs, the logo on your maps will change to Bing automatically on June 1. This is a logo change and does not affect performance or functionality.
• You will see updates to our Web sites and case studies over the coming weeks, where Bing maps for enterprise will replace references to Virtual Earth.
• If you have implemented the Virtual Earth logo in your application rather than using the APIs for logo implementation, please see the FAQs for more information about next steps.
We have prepared some additional FAQs at the end of this message to answer any questions you might have. If you don’t find the answer you need, please don’t hesitate to contact your Bing maps solution specialist or maplic@microsoft.com.
 

I liked virtual earth and I think they should have left the name alone. For SEO Alone.. What a mess. I have to change so much stuff this is going to suck.

CP did a great video on why they did this.

Click video to view. Double click to view full screen


FAQ

Q. How will this affect my organization’s solution?

A. If you are using our mapping APIs, you will see the Bing watermark on content starting on June 1. This is a logo change only. This update will not introduce changes in performance or functionality of your application. The contract for your mapping service does not change in terms or duration. There is no action that you need to take.

Q. Do the API calls change?

A. No, the API calls will not change. They will still refer to Virtual Earth and MapPoint to help make sure that your implementation does not break and you do not need to make changes.

Q. Will the API Terms of Use change?

A. The API Terms of Use will be updated to replace the Microsoft Virtual Earth name with Bing Maps for Enterprise, but there is no other change to the terms.

Q. What if I have implemented the logo myself?

A. If you are not implementing the logo through the Virtual Earth, MapPoint Web Service, or Multimap APIs, please update your application to use the new Bing logo by September 1, 2009, at the latest. Logos may be obtained from your Microsoft contact for use with the mapping content in your application.

Q. My organization is featured in a Virtual Earth case study or press release. Will you be updating it with the new brand?

A. All new case studies and press releases after May 28, 2009, should feature the new brand. We will be updating some case studies to reflect the new brand and will contact you if necessary. We will not be updating press releases that predate the change.

Q. What if I refer to the Microsoft Virtual Earth brand on my Web site?

A. If you refer to Microsoft Virtual Earth on your Web site, we would like you to change your implementation to use the new name as soon as possible. If you would like to use the Bing logo or brand treatments on your Web site, please contact your Microsoft contact for approval and permission.


Best Practices for Virtual Earth development (AJAX control)

May 7, 2009 22:04 by gemery

 

Great posts in the forum I thought i would share here

Best Practices for Virtual Earth development (AJAX control)

General

1. To ensure proper rendering of the map use the following meta-tag and DOCTYPE:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

2. Always specify a position, width, and height style property for the map div.

3. If possible specify starting coordinate and zoom level in the VEMap.LoadMap method. This will reduce the number of unneeded tiles that are loaded.

4. If a lot of panning is expected then set the tileBuffer property of the VEMap.LoadMap method for better user experience.

5. Minify JavaScript files and CSS style sheets.

6. If making multiple Find calls in sequence use recursion: http://rbrundritt.spaces.live.com/blog/cns!E7DBA9A4BFD458C5!739.entry

7. Use VEMap.SetCenterAndZoom function instead of two separate function calls to VEMap.SetCenter and VEMap.SetZoom.

8. Use VEMap.Dispose map on page unload to release browser resources.

9. If loading multiple shape layers and allowing user to switch between layers then hide/show layers rather than deleting and reloading.

10. UseVEMap. onLoadMap property to process post map load functions: http://msdn.microsoft.com/en-us/library/bb412504.aspx

11. Hide birdseye pop-up for better user experience:

document.getElementById(‘MSVE_obliqueNotification’).style.display = “none”;

document.getElementById(‘MSVE_obliqueNotification’).style.visibility = “hidden”;

12. Create custom navigation dashboard rather than modifying the existing one. This will make it easier to migrate to newer versions of the map control.

13. If 3D is not required then disable hotkeys (the number 3), and hide the 3D button. This will ensure that the user will not accidentally navigate into 3D.

Rather than hide the 3D button (using CSS), you should set the showSwitch parameter of the LoadMap() method to false. (I'm sure this is what you meant, but just to clarify)

14. If expecting user to only search within one country then append the country’s name to the end of all addresses being used in find searches if the user has not already specified the country. This will prevent Virtual Earth from searching against the worldwide data and will increase the chances of relevant results being returned. The same applies for addresses being used for driving directions.

15. If user is required to scroll the web page to see the map, then consider disabling the mouse scroll wheel event on the map. This will keep the user from accidentally zooming the map.

16. Disable the VE disambiguation box that occurs for find searches and create your own. This will give you the developer greater control over its functionality.

17. Ensure to enable printing for maps that the users may print. http://msdn.microsoft.com/en-us/library/cc469977.aspx

18) Add the following to the <head> of your web page:

<meta http-equiv="Accept-Encoding" content="gzip, deflate" />

This will also help when you're serving vector data via AJAX - but don't forget to set your web server compression on.

Shapes only in 2D:

 

1. add pushpins to a div rather than a VEShapeLayer for performance increases: http://blogs.msdn.com/virtualearth/archive/2009/04/09/virtual-earth-api-release-information-april-2009.aspx

2. If you need a custom pop-up, overlay an absolutely positioned div over the map and move it around. Otherwise use the custom the VEMap.ClearInfoBoxStyles method and specify your own styles. http://msdn.microsoft.com/en-us/library/bb412441.aspx

3. Disable shape display threshold when working with only a few polygons/polygons so that there is no loss in shape precision: http://msdn.microsoft.com/en-us/library/bb964367.aspx

Shapes in 3D

1.              1. Always use the VECustomIconSpecification for custom pushpins.

VECustomIconSpecification

1.               1. Use an absolute path for icon images.

2.               2. If not using the TextContent property of the VECustomIconSpecification, add a space character instead of an empty string. This is a work around for a bug in VE.

Data

1. Ensure that client data is in the proper projection system, WGS84. NAD83 will also work (~1m offset from WGS84 in certain areas of the world).

Absolutely! It might be worth mentioning that if you do have data projected in NAD27, or the British National Grid, for example, then you can reproject it into WGS84 using freely-available FWTools (http://fwtools.maptools.org/)

2. Use AJAX to retrieve data rather than post backs. This will allow you to retrieve your data without having to reload the map. This is much faster.

3. When working with latitude and longitude coordinates only six decimal places are needed. Any more decimal places will not change the pixel position on the map. This will reduce the overall size of the data being retrieved.

4. If there are a lot of pushpins (20+) on the map then clustering should be used.

a. If there is 100 of less pushpins then use the VEClusterSpecification: http://msdn.microsoft.com/en-us/library/bb412546.aspx

b. If there are 100 – 1000 pushpins use custom client side clustering algorithm: http://msdn.microsoft.com/en-us/library/cc161072.aspx

c. If there are 1000+ pushpins use server side clustering  (many algorithms exist)

5. Watch for floating point issues when doing calculations with coordinates. http://en.wikipedia.org/wiki/Floating_point#Problems_with_floating-point

6. When there is a lot of data, only load data for the current map view. Update data as the user navigates the map.

7. If possible run ESRI shapefile polygons/polyline data through a reduction algorithm to reduce the number of coordinates used to represent the shapes. ESRI shapefiles typically are large and use multiple coordinates (20+) to represent a straight line when only two are needed.

I agree with the comment that shapefiles should be reduced, but we need to be careful about the concept of 'straight lines' and how many coordinates are needed... because I would argue that it is Virtual Earth that handles these incorrectly rather than shapefiles.
Consider an ESRI shapefile with a single 'straight' linestring drawn between two coordinates at (34, -118) and (52 ,0), representing a route between Los Angeles and London. These coordinates are measured in WGS84, which uses geographic coordinates on an ellipsoidal model of the Earth. The shortest 'straight' line route between these two points, when projected onto a Mercator map, is therefore:

8. Polygon and Polyline data can be encoded to reduce its size: http://www.soulsolutions.com.au/Articles/Encodingforperformance.aspx

9  "If plotting complex shapes that are relatively static, and which you don't need to be able to interact with, use a tile layer rather than a shape layer."
10  "To generate your own background tiles you can use MSR mapcruncher. If you want to replace the default VE tileset completely with your own tiles then set the LoadBaseTiles map option to false when calling the LoadMap method"

 

Most of this came from the most awsome

and some from the sql spatial guru himselft

Ricky Brundritt

http://rbrundritt.spaces.live.com/default.aspx?sa=324131751

aitchison

http://www.beginningspatial.com/

Great Job


Microsoft's 196 Megapixel Camera

April 8, 2009 07:29 by gemery

Microsoft announced a new larger format 92 megapixel camera for aerial photography. You may not have even known that Microsoft makes cameras, but this is how they get the really good quality from the Bird's Eye view on Live Maps. Stemming from an acquisition of Vexcel several years ago, the UltraCamLp is the latest in aerial photography. Whereas the previous UltraCamL was 64 megapixel, the UltraCamLp at 92 megapixels takes photos that are natively 11,704 x 7,920 pixels, making it the largest footprint medium format camera system for small aircraft.
Wait, you say, medium format? Does that mean there is a large format camera? Why yes, that would be the UltraCamXp coming in at a whopping 196 megapixels. The UltraCamLp will be in service in flying season 2010.

OMG


Virtual Earth Developer Toolkit For MVC Framework

April 7, 2009 23:22 by gemery

A good friend and Fellow Live Services MVP Chris Pietschmann has just released a javascript control that is ideal for the mvc framework. Check it out here.

http://www.codeplex.com/VEToolkit

A great post describing how to use it.

http://pietschsoft.com/post/2009/03/Prototype-of-VEToolkit-2b-ASPNET-MVC-10-Component-Checked-In.aspx


Virtual Earth to be included with with BizSpark

March 30, 2009 14:31 by gemery

In a major announcement Microsoft has just said that it will include virtual Earth in its free software/service to bizspark customers . Cost has  been a major barrier to the adoption of the new online mapping services for commercial applications . Typical subscription costs are extremely high for small business startups.This stifles innovation - especially in the current economic climate.  BizSpark members can now get a commercial Microsoft Virtual Earth account for 75% off (ie. $2000/annum).  There are some restrictions, and the BizSpark program is also only applicable for companies that are less than 3 years old and have less than $1 million in annual revenue.

Further details (including contact details) can be found in Chris Pendleton's announcement blog post:

BizSpark Program Changes Virtual Earth Licensing for Startups


InfoStrat.VE launches Virtual Earth 3D control for WPF and surface

March 10, 2009 15:02 by gemery

 

http://virtualearthwpf.codeplex.com/

This control comes in two versions: one for regular WPF applications and one with Microsoft Surface enhancements (multitouch pan and zoom gestures).

Previous implementation of Virtual Earth on Surface were done using transparent windows and the map itself had limitations (no rotation or transforms, etc.) due to Win32 interop.
InfoStrat.VE uses some magic to eliminate these restrictions. It also takes advantage of WPF data binding for controlling various properties such as the camera location. You can add pushpins by simply adding a WPF-based VEPushPin as a child element. VEPushPins can also be provided by a data-bound collection.

Obviously this is a wpf control but via wpf you can run it on a surface..

I can see some fun times ahead wait till you see what Virtual Earth has in store for you at mix!


Really Cool Virtual Earth Apps On A Microsoft Surface

February 25, 2009 11:15 by gemery

Josh Wall from Information Strategies shows Some cool apps they are working on using the Surface using virtual earth. These are really cool so I thought I would go and checkout there website for more fun.

Some other awesome surface apps that they have.

 

 


Virtual Earth Server Side Control – Changing the Map Properties on the Server

February 24, 2009 13:15 by gemery

If you a have landed on this page please go ahead and take a gander at the Getting Started Page

 http://blog.geoffreyemery.com/post/Virtual-Earth-Server-Side-Control-ndash3b-Getting-Started.aspx

Next we have the setting the properties tutorial to browse

Now lets jump into setting the map control using server side components as well

First lets take a look at the final product.

So we are getting a standarrd map. but we are adding a bunch of server side buttons to interact with map…Namely ZoomIn, ZoomOut, Change the map to Arial,and Road, and Arial With Labels.

So how are hooking into these controls?

On the server just as we normally wood. Lets take a look at the code behind.

  protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void ZoomIn_Click(object sender, EventArgs e)
    {
        Map1.ZoomIn();
    }
    protected void ZoomOut_Click(object sender, EventArgs e)
    {
        Map1.ZoomOut();
    }
    protected void Aerial_Click(object sender, EventArgs e)
    {
        Map1.MapStyle = MapStyle.Aerial;
        
    }
    protected void Road_Click(object sender, EventArgs e)
    {
        Map1.MapStyle = MapStyle.Road;
    }
    protected void Hybrid_Click(object sender, EventArgs e)
    {
        Map1.MapStyle = MapStyle.Shaded;
    }

we also need to add a reference to the VE Class that was added to our bin when we dragged the control onto the web page.

using Microsoft.Live.ServerControls.VE;

 

And you will see that every time we click the button that the page posts back to the server and modifies the map. This is incredibly inefficient but the purpose was to demonstrate how you can change the map from the server! Sweet Lets take a look at that final product one more time.

image_thumb1[4]


Virtual Earth Server Side Control – Setting Map Properties

February 24, 2009 02:20 by gemery

image_thumb2If you a have landed on this page please go ahead and take a gander at the Getting Started Page http://blog.geoffreyemery.com/post/Virtual-Earth-Server-Side-Control-ndash3b-Getting-Started.aspx

So now that you have the got the control installed on your computer and you have installed the ctp you can then go ahead and get started.

Starting It up so go ahead and drag over the server control over to the page

Drag and drop control onto your web page - You can drag and drop the control from toolbox onto your web page and set some properties and you are ready to go.

clip_image002

Now we are going to go ahead and set some properties.  First we should have a look at the parameters created when dragging the control from the Toolbox and dropping it on a Web page. The default values in the description are also those created when dragging the control from the Toolbox and dropping it on a Web page.

ID

Required. The unique identifier for the control on the Web page. The default value is Map1.

Height

Optional. The height of the control on the Web page. The default value is 400px.

Width

Optional. The width of the control on the Web page. The default value is 400px.

ZoomLevel

Optional. The zoom level of the map on the Web page. The default value is 4.

Altitude

Optional. The altitude, in meters.

Center-Latitude

Optional. The latitude, in degrees, of the center of the map. The allowed range is from -90 (south pole) to 90 (north pole). The default value is 40.

Center-Longitude

Optional. The longitude, in degrees, of the center of the map. The allowed range is from -180 to 180. The default value is -104.

ClearInfoBoxStyles

Optional. Whether to clear any style settings for the information boxes. If true, the styles are cleared. The default value is false.

ClientToken

Optional. The unique client token from the Virtual Earth Platform service. Used to enable paid features and also track usage the token is received server side from the Virtual Earth Platform Web service. The default value is empty (""). Client tokens are required to get traffic information.

DashBoard

Optional. Whether to display the dashboard. If true, the dashboard is shown. The default value is true.

DashBoardSize

Optional. The size of the dashboard, if displayed. The allowed values are Tiny, Small, and Normal. The default value is Normal.

DisambiguationDialog

Optional. Whether to show the default disambiguation dialog is displayed when multiple results are returned from a location query. If true, the disambiguation dialog is displayed. The default value is true.

EnableShapeDisplayThreshold

Optional. Whether shapes are drawn below a threshold zoom level. If true, shapes are drawn below the threshold level. The default value is false.

Of going this for real first lets start off with blank ajax web site…

<%@ Page Language="VB"  AutoEventWireup="false" CodeFile="Default.aspx.vb" 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 runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager runat="server" ID="script1" />
    <div>
    </div>
    </form>
</body>
</html>

 

Now we are going to add the mapping control. Simply drag it across.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<%@ Register Assembly="Microsoft.Live.ServerControls.VE" Namespace="Microsoft.Live.ServerControls.VE"
    TagPrefix="ve" %>
<!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 runat="server">
    <title>Setting Map Porperties with the Virtual Earth Server Side Control</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager runat="server" ID="SM1" />
    <div>
        <ve:Map ID="Map1" runat="server" Height="400px" Width="400px" ZoomLevel="4" />
    </div>
    </form>
</body>
</html>

 

You will notice that you have a user control registered at the top and that the ve map control, and also notice that there is now a new dll in the bin folder that is inserted from dragging on the control.

image_thumb

Now you are ready go press f5 and lets see what you get…

image_thumb21

A ma centered on the US.  Awesome So lets set some properties.

Since mix is right around the corner lets set the map on the The belagio hotel.

change the map style to aerial , turn on the minmap and make the default measurement into kilometers not to mention play with the zoom level a bit.

 

<ve:Map ID="Map1" runat="server" Center-Latitude="36.11285" 
        Center-Longitude="-115.174" Height="600px" MapStyle="Aerial" MiniMap="True" 
        MiniMapSize="Large" MiniMapXoffset="520" MiniMapYoffset="5" 
        ScaleBarDistanceUnit="Kilometers" Width="720px" ZoomLevel="18" />

 

Now lets take a look at what we get.

image_thumb4

And that's its now we have set up our first virtual earth server side control.


Virtual Earth Server Side Control – Getting Started

February 22, 2009 21:25 by gemery

Key Links

Feature Overview

· Visual Studio toolbox - Map control is available right in your toolbox of Visual Studio

clip_image001

· Drag and drop control onto your web page - You can drag and drop the control from toolbox onto your web page and set some properties and you are ready to go.

clip_image002 clip_image003

clip_image004

· Server side events - Server side events for panning/zooming, find/directions are available in addition to client side events for the map control.

clip_image005 clip_image006

· Display and control the map - You can control how map displays on your web page with standard functionality like MapMode (2D/3D), MapStyle(Road/Aerial), displaying dashboard and setting its size, setting the zoom levels, zooming in/out, panning etc.

· Adding shapes to the map - You can add shapes to map from ASP.NET Server Side using provided methods. You can query different shapes/layers in the Map and delete them as well.

· Using directions - You can get the directions between multiple points using methods GetDirections. You can specify different routing options like distance unit, color etc. Once the direction information is received, Map control raises event OnServerDirections where you can process/render the returned information in way that suites your scenario.

clip_image007

clip_image008

clip_image009

· Using local search and mapping results - Map control provides with find method where you can search for local businesses in a specified location.

clip_image010

clip_image011

· Working with bird's eyes - Map control has support for bird's eye view similar to JavaScript control.

· Getting Traffic information - You can get traffic information and display on your web page. For this, you need to have an account with Virtual Earth Platform. You first need to get a client token:

Important: To get a Developer Evaluation account for Virtual Earth go to this link here and request one, https://mappoint-css.live.com/mwssignup/

clip_image012

· You can then use this client token to display the traffic of the location you are interested in:

clip_image013

Development stage

The suite of tools is currently a community technology preview, which means they would love feedback, but strongly discourage any web site from going live using these controls.

Original Post By Mark Brown… Reposting here for SEO… Mark has left VE Team so please Contact Chris Pendleton over at VE Blog

All this and more to come in the following tutorials


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

 

 

 

 

 

 

 

 


Virtual Earth Web Services – Create A Map Image from a Latitude Longitude

January 23, 2009 07:37 by gemery

In this tutorial we are going to look at what you need to get a map from a  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>Virtual Earth Web Services Imagery Map Creation 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 Map Creation 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" 
                    onselectedindexchanged="DropDownList_ZoomLevel_SelectedIndexChanged" AutoPostBack="true" />
                <br />
 
                <table>
                    <tr>
                        <td>&nbsp;</td>
                        <td>
                            <asp:Image ID="Image_Map" runat="server" Height="432px" Width="585px" />
                            <br />
                        </td>
                        <td align="center">&nbsp;</td>
                    </tr>
                </table>
                
                <br />
                <div runat="server" id="Div_Info" />
                
            </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 userkey and passowrd out of the webconfig 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

protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack == false)
        {
            // Load some default data into the UI
 
            //Hotel Bonaventure, ( 34.052563, -118.256012 )
            //this.TextBox_Latitude.Text = "34.052563";
            //this.TextBox_Longitude.Text = "-118.256012";
 
            //Los Angeles Convention Center, ( 34.0404, -118.2688 )
            this.TextBox_Latitude.Text = "34.0404";
            this.TextBox_Longitude.Text = "-118.2688";
             
 
            //One Microsoft Way
            //this.TextBox_Latitude.Text = "47.64";
            //this.TextBox_Longitude.Text = "-122.13";
 
            for (int i = 1; i <= 20; i++)
                this.DropDownList_ZoomLevel.Items.Add(i.ToString());
            this.DropDownList_ZoomLevel.SelectedIndex = 18;     // Default the zoom level to 19
 
            // Load a default map
            this.RenderMap(Convert.ToDouble(this.TextBox_Latitude.Text),
                Convert.ToDouble(this.TextBox_Longitude.Text),
                Convert.ToInt32(this.DropDownList_ZoomLevel.SelectedValue));
        }
    }

Now for the fun stuff Getting the map from Microsoft

/// <summary>Renders and places a map image on the page</summary>
    /// <param name="centerLatitude">Latitude that the map should be centered on</param>
    /// <param name="centerLongitude">Longitude that the map should be centered on</param>
    /// <param name="zoomLevel">Zoom level of the map image</param>
    private void RenderMap(double centerLatitude, double centerLongitude, int zoomLevel)
    {
        Image mapImage = (Image)this.FindControl("Image_Map");
 
        // 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 Center point for the imagery request
        mapUriRequest.Center = new VEImageryService.Location
        {
            Altitude = 0,
            Latitude = centerLatitude,
            Longitude = centerLongitude
        };
 
        // Set the size and ZoomLevel we want on the returned map
        mapUriRequest.Options = new MapUriOptions
        {
            // Specify the map size, we get this from the size of the image on the web page
            ImageSize = new VEImageryService.SizeOfint
            {
                Height = (int)mapImage.Height.Value,
                Width = (int)mapImage.Width.Value
            },
            // Set the ZoomLevel for the returned map
            ZoomLevel = (int)zoomLevel,
 
            //Set the Map Style (only road and aerial types are available)
            Style = MapStyle.AerialWithLabels
        };
 
        // Create a new ImageryServiceClient to make the service request
        ImageryServiceClient imageryServiceClient = new ImageryServiceClient();
 
        // Execute GetMapUri
        MapUriResponse mapUriResponse = imageryServiceClient.GetMapUri(mapUriRequest);
 
        // Display the map on the web page.
        mapImage.ImageUrl = mapUriResponse.Uri;
 
        // Write out the uri to the page
        this.WriteInfo("<b>Map uri: </b>" + mapUriResponse.Uri);
    }

And finally add a handler for when people change the zoom level and a small helper function

/// <summary>Event handler for the Zoom level drop down list, re-renders the map at the specified zoom level</summary>
   /// <param name="sender">The sender</param>
   /// <param name="e">Event arguments</param>
   protected void DropDownList_ZoomLevel_SelectedIndexChanged(object sender, EventArgs e)
   {
       this.RenderMap(Convert.ToDouble(this.TextBox_Latitude.Text),
           Convert.ToDouble(this.TextBox_Longitude.Text),
           Convert.ToInt32(this.DropDownList_ZoomLevel.SelectedValue));
   }
 
   /// <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. 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

  

Have fun!


Virtual Earth Web Service – Get Routing information

January 22, 2009 08:01 by gemery

In this tutorial we are going to look at what you need to get Routing information from a start and end point and then display them.

 

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>Vritual Earth Web Services Route Sample</title>
</head>
<body style="font-family:Arial; font-size:small">
    <form id="form1" runat="server">
    <div style="font-weight:bold">
        Vritual Earth Web Services Route 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>From Address:</td>
                        <td><asp:TextBox runat="server" ID="TextBox_From" Width="250" /></td>
                    </tr>
                    <tr>
                        <td>To Address:</td>
                        <td><asp:TextBox runat="server" ID="TextBox_To" Width="250" /></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td align="right">
                            <asp:Button runat="server" Text="Get Directions" ID="Button_GetDirections" onclick="Button_GetDirections_Click" />
                        </td>
                    </tr>
                </table>
                <br />
 
                <div runat="server" id="Div_Directions" />
                <br />
                <asp:Image runat="server" ID="Image_Map" Visible="false" />
            </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

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

 

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_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 commonts in here so ill those be your guide feel to ping me iwth more questions plus down load the code and run it is the best way to go.

/// <summary>Displays directions from a point to another point based on the address supplied in the UI</summary>
    /// <param name="sender">The sender</param>
    /// <param name="e">Event arguments</param>
    protected void Button_GetDirections_Click(object sender, EventArgs e)
    {
        // Create a new RouteRequest and set our credentials
        RouteRequest routeRequest = new RouteRequest();
        routeRequest.Credentials = new VERouteService.Credentials();
        routeRequest.Credentials.Token = Utils.Token(Request.UserHostAddress);
 
 
        // Create a new list of Waypoints and add start and end locations to the list
        List<Waypoint> wayPointList = new List<Waypoint>();
        wayPointList.Add(this.GetWayPointFromAddress("Start", this.TextBox_From.Text.Trim()));
        wayPointList.Add(this.GetWayPointFromAddress("End", this.TextBox_To.Text.Trim()));
 
        // Add the list of waypoints to the route request
        routeRequest.Waypoints = wayPointList.ToArray();
 
        // New up a RouteServiceClient
        RouteServiceClient routeServiceClient = new RouteServiceClient();
 
 
        //and calculate the route
        RouteResponse routeResponse = routeServiceClient.CalculateRoute(routeRequest);
 
        // Write the route directions back to the UI
        int legCounter = 0;
        foreach (RouteLeg routeLeg in routeResponse.Result.Legs)
        {
            foreach (ItineraryItem itineraryItem in routeLeg.Itinerary)
                this.WriteInfo((++legCounter) + ") " + itineraryItem.Text);
        }
    }
 
    /// <summary>Returns a waypoint given from the specified address</summary>
    /// <param name="description">Waypoint description</param>
    /// <param name="address">Address to geocode against</param>
    protected Waypoint GetWayPointFromAddress(string description, string address)
    {
        // Create a waypoint, new up the a location object and set the description
        Waypoint wayPoint = new Waypoint
        {
            Description = description,
            Location = new VERouteService.Location()
        };
 
        // New up a geocode request and supply the credentials 
        GeocodeRequest geocodeRequest = new GeocodeRequest();
        geocodeRequest.Credentials = new VEGeocodeService.Credentials();
        geocodeRequest.Credentials.Token = Utils.Token(Request.UserHostAddress);
 
        //pass the address of the location
        geocodeRequest.Query = address;
 
 
        // Create a GeocodeService client and execute the Geocode method
        GeocodeServiceClient geocodeServiceClient = new GeocodeServiceClient();
        GeocodeResponse geocodeResponse = geocodeServiceClient.Geocode(geocodeRequest);
 
        // If we have a geocode result, set the first result to our waypoint location
        if (geocodeResponse.Results.Length > 0)
        {
            if (geocodeResponse.Results[0].Locations.Length > 0)
            {
                wayPoint.Location.Latitude = geocodeResponse.Results[0].Locations[0].Latitude;
                wayPoint.Location.Longitude = geocodeResponse.Results[0].Locations[0].Longitude;
            }
        }
 
        return wayPoint;
    }

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_Directions.InnerHtml += html + "<br/>\n";
   }

Bam there you have a routing simply from two peoples address… Sweet.

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