Ricky's profileRicky's Bing Maps BlogBlogSkyDrive Tools Help

Blog


    9/13/2009

    Panning and Zooming with the Bing Map Imagery Web Services

    The Bing Maps Imagery service is commonly used for mobile applications. A common issue people have when using the Bing map imagery web services is figure out how to take a map and navigate around it by panning and zooming. Zooming is pretty straight forward as all the user has to do is increase or decrease the zoom level that was used to initially retrieve the map image. Panning on the other hand is much more complicated. Generally when panning you want to move a certain pixel distance from where the user is currently viewing. To calculate the coordinate of a new location knowing our current location, direction (heading) and a distance to travel we can use the method described in this post: http://rbrundritt.spaces.live.com/blog/cns!E7DBA9A4BFD458C5!400.entry 

    The distance you will want to pan will depend on the size of your map. Generally you will pick a distance in pixels. To use this pixel distance we will have to convert into a physical distance on the earth. To do this we can calculate the resolution of the ground in pixels for a particular zoom level. To calculate the resolution at a particular zoom level and latitude we can use the following formula.

    clip_image002

    This formula came from the following article on the Bing Maps tiling system: http://msdn.microsoft.com/en-us/library/bb259689.aspx 

    The final piece of information that is needed is the direction (heading). Headings generally are an angle in degrees from 0 to 360 with 0 being North, 90 degrees being East, 180 degrees being south and west being 270 degrees. If you want to pan your map North East you will set your heading to 45 degrees.

    I’ve thrown together a simple application that pulls all this together. Complete source code can be found here: http://cid-e7dba9a4bfd458c5.skydrive.live.com/self.aspx/VE%20Sample%20code/BingMapsPanZoom.zip

    BingPanZoom


    2/22/2009

    Drawing Routes with the VE Web Service

    The Virtual Earth web services are fairly new and as such it does not currently have all the capabilities of it's JavaScript counter part. One key functionality that is not currently available is the ability to draw routes on a map image. This can be done by extending the methods described in the article "VE Imagery Service Polygons and Polylines" found here: http://rbrundritt.spaces.live.com/blog/cns!E7DBA9A4BFD458C5!497.entry 

    In order to display a route on a map image the following steps will have to be taken:

    1) Geocode the start and end points of the route using the Geocoding service.

    2) Calculate a Route and have the route geometry returned using the Routing Service.

    3) Calculate the best map view for the route path.

    4) Request map image from the imagery service that matches the best map view calculated in step 3.

    5) Draw the route line on the map image using .NET drawing tools.

    6) Draw the route turn points on the map image using .NET drawing tools.

    Below is an example of a route that was created using the above method. Complete sample code can be found here:

    http://cid-e7dba9a4bfd458c5.skydrive.live.com/self.aspx/VE%20Sample%20code/VERouteImageryService.zip 

    image

    2/14/2009

    VEImagery Service Pixel to LatLong calculations

     

    The VEImagery service gives us the ability to render static versions of Virtual Earth Maps. As handy as this is it would also be handy to be able to georeference the image that is returned. The article found here:

    http://rbrundritt.spaces.live.com/blog/cns!E7DBA9A4BFD458C5!488.entry

    explains how to convert from LatLong to Pixel so that custom icons could be added to the map, however the conversion from Pixel to LatLong was not needed at that time. Building on top of the code that was provided in that article the following method can be used to calculate a LatLong value based on the pixel coordinate of a static image. The following formula can be used to perform this calculation.

            /// <summary>
            /// Convert Pixel coordinates to LatLong coordinates
            /// Based on code found here: http://msdn.microsoft.com/en-us/library/cc161076.aspx
            /// </summary>
            /// <param name="offset"></param>
            /// <returns></returns>
            public LatLong PixelToLatLong(Point offset)
            {
                int x = TopLeftCorner.X + offset.X;
                int y = TopLeftCorner.Y + offset.Y;

                double Longitude = (((double)x * 360) / (256 * Math.Pow(2, view.zoom))) - 180;

                double efactor = Math.Exp((0.5 - (double)y / 256 / Math.Pow(2, view.zoom)) * 4 * Math.PI);

                double Latitude = Math.Asin((efactor - 1) / (efactor + 1)) * 180 / Math.PI;

                LatLong latlong = new LatLong();
                latlong.Latitude = Latitude;
                latlong.Longitude = Longitude;

                return latlong;
            }

     

    The complete source code can be downloaded here:

    http://cid-e7dba9a4bfd458c5.skydrive.live.com/self.aspx/VE%20Sample%20code/CustomIconVEService.zip

    Here is a screen shot of this application in action.

    image

    1/7/2009

    Birds Eye Imagery Extraction Via the Virtual Earth Web Services - Part 1

    Using the Imagery service available in the Virtual Earth Web Services, it is possible to retrieve a map image for a specific location (as specified by specific latitude and longitude values). This method however, is not available to the Birds Eye imagery. Rather further functionality must be applied within the Web Services in order to retrieve accurate Birds Eye Imagery Metadata. The information on the Birds Eye scene for the desired location is present in the URI that is used to retrieve the map tiles which make up the Birds Eye scene. To return the tile in which the specified coordinate exits currently a tile id for the map image must first be provided. The extraction of the correct tile id for alternate map styles, using the Quad Key notation is described in the article, Virtual Earth Tile System (http://msdn.microsoft.com/en-us/library/bb259689.aspx).

    The methodology described in the Virtual Earth Tile System article is unfortunately not applicable to Birds Eye imagery as a standard Birds Eye scene does not fit perfectly into a quad key frame (for example, a Birds Eye scene at zoom level 19 consists of 4 tiles in the x-axis and 6 tiles in the y-axis and at zoom level 20 there are 8 tiles in the x-axis and 12 tiles in the y-axis).  Furthermore the Birds Eye scenes do not populate the quad key format properly, rather tiles that are on the edge of a scene, only fill a portion of a standard map tile. This behavior is caused because the Birds Eye images are geo-referenced, high resolution images which are then overlayed onto the Virtual Earth map differently than a standard tile.

    The following (figure 1), is a Birds Eye scene shown over a standard road view in Virtual Earth at zoom level 19. The red boxes represent the Birds Eye tiles, and the black boxes represent the VE road tiles over the same area. As is evident, the Birds Eye tiles do not properly line up with the edges of the Virtual Earth tiles, which are placed on the map according to the quad key notation. The Birds Eye imagery therefore must be retrieved using a difference methodology than would be used for a standard VE tile.

    image001

    Figure 1 - Birds Eye over standard map tile at zoom level 19

    The Birds Eye geo-referencing information is stored in a database that can only be extracted using the backend web services the Virtual Earth Map Control implements. The data is returned as JavaScript, and can be extracted from the feed using another step, such as regular expressions. With the information retrieved, it is possible to then geo-reference the Birds Eye tiles, or calculate the specific tile id that a coordinate falls into. Note that this is a hack and is completely unsupported as it's possible that a change on VE's side will cause this URL or method to break.

    The following are the necessary steps to calculate the tile id based on an input coordinate:

    1)      Retrieve the Birdseye Imagery Metadata for a coordinate using the Virtual Earth Web Services.

    2)      Retrieve geo-referencing data for the Birdseye scene in which the coordinate resides using backend Virtual Earth web service.

    3)      Extract geo-reference data from web service response using regular expressions.

    4)      Convert LatLong to pixel coordinate, relative to top left corner of Birdseye scene.

    5)      Calculate the x and y tile positions.

    6)      Calculate tile id from x and y tile positions.

    7)       Retrieve Birds Eye tile in which the coordinate resides.

    Retrieve Birds Eye Imagery from Virtual Earth Web Services

     

    Retrieving the Imagery Metadata for a Birds Eye Scene in which a coordinate exists can be accomplished using the following simple example on how to build the request;

    Code Sample

    double latitude = 40.68;

    double longitude = -73.93;

    int zoom = 19;

    int heading = 0;

     

    ImageryMetadataRequest metadataRequest = new ImageryMetadataRequest();

     

    // Set credentials using a valid Virtual Earth Token

    metadataRequest.Credentials = new VEImageryService.Credentials();

    metadataRequest.Credentials.Token = clientToken;

     

    // Set the imagery metadata request options

    VEImageryService.Location centerLocation = new VEImageryService.Location();

    centerLocation.Latitude = latitude;

    centerLocation.Longitude = longitude;

     

    metadataRequest.Options = new ImageryMetadataOptions();

    metadataRequest.Options.Location = centerLocation;

     

    metadataRequest.Options.ZoomLevel = zoomLevel;

     

    metadataRequest.Options.Heading = new Heading();

    metadataRequest.Options.Heading.Orientation = heading;

     

    metadataRequest.Style = MapStyle.BirdseyeWithLabels;

     

    // Make the imagery metadata request

    ImageryServiceClient imageryService = new ImageryServiceClient();

    ImageryMetadataResponse metadataResponse = imageryService.GetImageryMetadata(metadataRequest);

     

    The ImageryMetadataResult object contains several properties; the following variables will be needed in either the calculations that follow or in creating the URI to the map tile:

    Variable

    Value

    ImageSize.Height

    Height of a single tile

    ImageSize.Width

    Width of a single tile

    ImageUriSubdomains

    An array of sub-domains that can be used to construct the URI

    ImageUri

    A string specifying the URI for the image

     

    Additional information on how to use the Virtual earth web services can be found in the article, Developing a .NET Application Using Virtual Earth Web Services (http://msdn.microsoft.com/en-us/library/dd221354.aspx).

    Retrieve Geo-Referencing Data for a Birds Eye scene

     

    Geo-Referencing data for Birds Eye scenes is not available through the Virtual Earth Web Services rather the information needs to be retrieved from a backend web service. The following is an example web service request that can be used to access the service:

    http://dev.virtualearth.net/services/v1/ImageryMetadataService/ImageryMetadataService.asmx/GetBirdsEyeSceneByLocation?latitude=40.77638178482896&longitude=-73.61663818359376&level=20&spinDirection=%22NoSpin%22&orientation=%22North%22&culture=%22en-us%22&format=json&rid=1227643110358&

    This request contains multiple variables:

    Variable

    Value

    latitude

    Latitude value

    longitude

    Longitude value

    level

    Zoom level of Birds Eye image

    orientation

    Direction of Orientation (North, South, East, West)

    culture

    The culture in which the labels should be in

    format

    This is the return format of the data. Currently “json” is the only available format.

    rid

    This is an id used for the request. This needs to be in the request however using the same rid for each request is acceptable.

     

    The following is an example of a response from the web service:

    Example Response

    function _f1227643110358(){return {"__type":"Microsoft.VirtualEarth.Engines.Core.ImageryMetadata.PublicTypes.BirdsEyeSearchResponse","Scene":{"S":8110562,"O":0,"Q":"03201011103","RI":4354,"L":20,"Fcx":16,"Fcy":12,"Hcx":8,"Hcy":6,"QA":-0.40797472410705138,"QB":20.928199325031251,"QC":165807.88732506905,"QD":0.22288172553678412,"QE":-11.587628391710947,"QF":-91840.5941131519,"QG":0.0054790346170970417,"QH":-0.28430088283524946,"QI":-2252.1714401186127,"XA":-207.10129411915017,"XB":-86.358261661444089,"XC":-11725.499006073529,"XD":-19.539468822757811,"XE":164.61435354728968,"XF":-8151.2791376682235,"XG":0.0019627160694678978,"XH":-0.020990038814928769,"XI":1},"ResponseSummary":{"Copyright":"Copyright © 2008 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.","StatusCode":0,"AuthResultCode":0,"ErrorMessage":null,"TraceId":"2cb7463b-dc46-4a21-8ba5-25bd825845fb"}};} if(typeof closeDependency !== 'undefined'){closeDependency('1227643110358');}

    Extract Geo-Reference Data from Web Service Response

     

    The web service response contains more information than necessary; the following is the only portion that is needed:

    {"S":8110562,"O":0,"Q":"03201011103","RI":4354,"L":20,"Fcx":16,"Fcy":12,"Hcx":8,"Hcy":6,"QA":-0.40797472410705138,"QB":20.928199325031251,"QC":165807.88732506905,"QD":0.22288172553678412,"QE":-11.587628391710947,"QF":-91840.5941131519,"QG":0.0054790346170970417,"QH":-0.28430088283524946,"QI":-2252.1714401186127,"XA":-207.10129411915017,"XB":-86.358261661444089,"XC":-11725.499006073529,"XD":-19.539468822757811,"XE":164.61435354728968,"XF":-8151.2791376682235,"XG":0.0019627160694678978,"XH":-0.020990038814928769,"XI":1}

     

    Each variable is defined with a variable name and value in the format:  “name”: value. An explanation as to what some variable names means is as follows:

    Variable

    Value

    S

    Scene ID

    O

    Direction in degrees (North, East, South, West)

    Q

    Quad key Birds Eye scene is contained in at zoom level 11

    L

    Maximum zoom level available for this scene

    Hcx

    Number of tiles used in the x-axis

    Fcy

    Number of tiles used in the y-axis

    QA - QI

    Geo-referencing constants needed to convert Pixel to LatLong

    XA - XI

    Geo-referencing constants needed to convert LatLong to Pixel

     

    These variables can be extracted using regular expressions similar to the following:

    C# Example

    Regex QArx = new Regex("\"QA\":(-?\\d+\\.?\\d*)");

    Match match = QArx.Match(response);

    double QA = double.Parse(match.Groups[1].Value.ToString());

     

    Java Example

    Pattern QArx = Pattern.compile("\"QA\":(-?\\d+\\.?\\d*)");

    Matcher match = QArx.matcher(response);

    double QA = Double.parseDouble(match.group(1));



    Birds Eye Imagery Extraction Via the Virtual Earth Web Services - Part 2

     

    Convert Latitude & Longitude to Pixel Coordinate

     

    The calculated pixel will be the pixel coordinates relative to the top left corner of the scene.  The first step in this calculation is to create a 1x3 matrix of the LatLong coordinate.

    image002

    Once the LatLong matrix is created a second matrix is needed to store the geo-referencing data XA-XI. This will require a 3x3 matrix.

     image003

    These matrices need to be multiplied together in the following fashion:

    image004

    Before the pixel coordinates can be calculated a zoom factor constant is needed.

    image005

    The following formula’s can then be used to calculate the pixel coordinates:

    image006

    image007

    By expanding out the calculations the pixel coordinates can be calculated as follows:


    image008

    image009

    Calculate X and Y Tile Positions

     

    The X tile position can be calculated by dividing the x pixel location by the width of a tile and rounding this number down to an integer value.

    image010

    The Y tile position can be calculated by dividing the y pixel location by the height of a tile and rounding this number down to an integer value.

    image011

    Calculate tile id from x and y tile positions

     

    The X and Y tile positions along with the tileId are calculated for zoom level 19 using the following grid pattern:

    X = 0

    Y = 0

    tileID = 0

    X = 1

    Y = 0

    tileID = 1

    X = 2

    Y = 0

    tileID = 2

    X = 3

    Y = 0

    tileID = 3

    X = 0

    Y = 1

    tileID = 4

    X = 1

    Y = 1

    tileID = 5

    X = 2

    Y = 1

    tileID = 6

    X = 3

    Y = 1

    tileID = 7

    X = 0

    Y = 2

    tileID =8

    X = 1

    Y = 2

    tileID = 9

    X = 2

    Y = 2

    tileID = 10

    X = 3

    Y = 2

    tileID = 11

    X = 0

    Y = 3

    tileID = 12

    X = 1

    Y = 3

    tileID = 13

    X = 2

    Y = 3

    tileID = 14

    X = 3

    Y = 3

    tileID = 15

    X = 0

    Y = 4

    tileID = 16

    X = 1

    Y = 4

    tileID = 17

    X = 2

    Y = 4

    tileID = 18

    X = 3

    Y = 4

    tileID = 19

    X = 0

    Y = 5

    tileID = 20

    X = 1

    Y = 5

    tileID = 21

    X = 2

    Y = 5

    tileID = 22

    X = 3

    Y = 5

    tileID = 23

     

    Zoom level 20 uses a similar method, however the grid is 8 tiles in the x-axis and 12 tiles in the y-axis. The number of tiles in the x-axis for a particular Birds Eye Scene is stored in the Hcx value and the number of tiles in the y-axis is stored in the Fcy value of the web response to the back end web service. The following formula calculates a tile id from the X and Y tile positions:

    image012

    Retrieve Birds Eye tile

     

    Here is an example of a URI to a hybrid Birds Eye tile that is provided by the ImageryMetadataResult.ImageUri property:

    http://{subdomain}.staging.tiles.virtualearth.net/tiles/cmd/ObliqueHybrid?a=03201011031-7384-19-{tileId}&g=213&token={token}

    There are three properties which have to be set; subdomain, tileId, and token.  The subdomain can be assigned any value that is in the ImageUriSubdomains array. The token value should be assigned as a valid client token. The tileId is the id of a specific tile in a Birds Eye scene.

    Birds Eye Imagery Extraction Via the Virtual Earth Web Services - Part 3

     

    Pixel to Latitude & Longitude

     

    The following calculation show how to convert a Pixel coordinate which is relative to the top left corner of the Birds Eye scene into a LatLong coordinate. The first step in this calculation is to calculate the zoom factor:

    image005

    Next a 1x3 matrix of the pixel coordinate is created.

     image013

    Once the pixel matrix is created a second matrix is needed to store the geo-referencing data QA-QI. This will require a 3x3 matrix.

    image014

    These matrices need to be multiplied together in the following fashion:

    image015

    The following formula’s can then be used to calculate the pixel coordinates:

    image016 

    image017

    By expanding out the calculations the pixel coordinates can be calculated as follows:

    image018 

    image019

    Application

     

    A sample application can be downloaded here: http://cid-e7dba9a4bfd458c5.skydrive.live.com/self.aspx/VE%20Sample%20code/VEImagery%5E_Birdseye.zip

    The following is an example of this application in use. The first image is the test coordinate. The second image is the output of the application.

    image020

    Figure 2 – Birdseye image of a coordinate in Virtual Earth

     

    image021

    Figure 3 - Birdseye tile of a coordinate generated using the VE Web Services




    11/2/2008

    VE Imagery Service, Polygons and Polylines

    Currently the VE Imagery service does not have the ability to render polygons or polylines on a map image. The high level steps involved to accomplish this are as follows:

    1) Calculate the best map view for an array of Location objects.

    2) Request map image from the imagery service that matches the best map view calculated in step 1.

    3) Calculate the pixel coordinate of each location.

    4) Use .NET drawing tools to draw polygons and polylines.

    Many of the steps in this article are explained in the article title VE Imagery Service and Custom Icons

    The following code block shows how to draw a polygon on a map image from an array of points that form a polygon.

    private void AddPolygon(BestView view, Image map, Location[] polygon)
    {
    //define the map as a gaphics object Graphics graphics = Graphics.FromImage(map); Point[] points = new Point[polygon.Length];

    //calculate pixel points for (int i = 0; i < polygon.Length; i++)
    {
    points[i] = LatLongToPixel(polygon[i], view);
    }

    // Create blue pen for outline of polygon. Pen bluePen = new Pen(Color.Blue, 1);

    //Create brush to fill polygon. Color transparentGreen = Color.FromArgb(50, 0, 255, 0); Brush greenBrush = new SolidBrush(transparentGreen);

    graphics.DrawPolygon(bluePen, points);
    graphics.FillPolygon(greenBrush, points);
    }

    The following code block shows how to draw a polyline on a map image from an array of points that form a polyline.

    private void AddPolyline(BestView view, Image map, Location[] polyline)
    {
    //define the map as a gaphics object Graphics graphics = Graphics.FromImage(map); Point[] points = new Point[polyline.Length];

    //calculate pixel points for (int i = 0; i < polyline.Length; i++)
    {
    points[i] = LatLongToPixel(polyline[i], view);
    }

    // Create pen. Pen bluePen = new Pen(Color.Blue, 1);

    graphics.DrawLines(bluePen, points);
    }

    By combining these algorithms with the code in the article; VE Imagery Service and Custom Icons you can add your polygons and polylines to a VE map image. This can be useful to create tile layers when wanting to display a large number of polygons in the JavaScript version of Virtual Earth without having performance issues.

    Complete source code can be downloaded here: http://cid-e7dba9a4bfd458c5.skydrive.live.com/self.aspx/VE%20Sample%20code/VEPolygonsImageryService.zip

    image




    10/25/2008

    VE Imagery Service and Custom Icons

    Currently the VE Imagery service has the ability to display 26 different icons on the map. Oddly enough the default pushpin icon from the JavaScript version of Virtual Earth is not one of these icons. Unfortunately there is currently no built in method to display custom icons on the map image. There is also currently a limitation of 10 pushpins being passed to the imagery service. This article shows how to add any number of custom icons to the map image in the correct location. The default pushpin icon from the JavaScript version of Virtual Earth will be used as the custom icon. The high level steps involved to accomplish this are as follows:

    1. Calculate the best map view for an array of Location objects.
    2. Request map image from the imagery service that matches the best map view calculated in step 1.
    3. Calculate the pixel coordinate of each location and display custom icon on map image.
    Calculate the Best Map View

    The best map view is the zoom level and center point of a map image that contains all locations with the closest zoom level. The best map view will be stored using a structure.

    /// <summary>
    /// Structure to define a BestView object which defines a map view (centerpoint and zoom level)
    /// </summary>
    struct BestView
    {
    public Location center;
    public int zoom;

    //Constructor public BestView(Location _center, int _zoom)
    {
    center = _center;
    zoom = _zoom;
    }
    }

    Listing 1Structure to define a BestView object

    The following method calculates the best map view for an array of locations. This results in a map image similar to what is displayed if the VEMap.SetMapView function is used in the JavaScript version of Virtual Earth.

    /// <summary>
    /// Calculates best map view for an array of points. Similar to VEMap.SetMapView method
    /// </summary>
    /// <param name="points">Array of Location objects</param>
    /// <returns></returns>
    private BestView CalculateMapView(Location[] points)
    {
    //Calculate bounding rectangle double maxLat = -90, minLat = 90, maxLon = -180, minLon = 180;

    //default zoom scales in km/pixel from http://msdn2.microsoft.com/en-us/library/aa940990.aspx double[] defaultScales = { 78.27152, 39.13576, 19.56788, 9.78394, 4.89197, 2.44598, 1.22299,
    0.61150, 0.30575, 0.15287, .07644, 0.03822, 0.01911, 0.00955, 0.00478, 0.00239, 0.00119, 0.0006, 0.0003 };

    //Calculate bounding box for array of locations for (int i = 0; i < points.Length; i++)
    {
    if (points[i].Latitude > maxLat)
    maxLat = points[i].Latitude;

    if (points[i].Latitude < minLat)
    minLat = points[i].Latitude;

    if (points[i].Longitude > maxLon)
    maxLon = points[i].Longitude;

    if (points[i].Longitude < minLon)
    minLon = points[i].Longitude;
    }

    //calculate center coordinate of bounding box double centerLat = (maxLat + minLat) / 2;
    double centerLong = (maxLon + minLon) / 2;

    //create a Location object for the center point Location centerPoint = new Location();
    centerPoint.Latitude = centerLat;
    centerPoint.Longitude = centerLong;

    //want to calculate the distance in km along the center latitude between the two longitudes double meanDistanceX = HaversineDistance(centerLat, minLon, centerLat, maxLon);

    //want to calculate the distance in km along the center longitude between the two latitudes double meanDistanceY = HaversineDistance(maxLat, centerLong, minLat, centerLong) * 2;

    //calculates the x and y scales var meanScaleValueX = meanDistanceX / mapWidth; var meanScaleValueY = meanDistanceY / mapHeight; double meanScale;

    //gets the largest scale value to work with if (meanScaleValueX > meanScaleValueY)
    meanScale = meanScaleValueX;
    else meanScale = meanScaleValueY; //intialize zoom level variable int zoom = 1;

    //calculate zoom level for (var i = 1; i < 19; i++)
    {
    if (meanScale >= defaultScales[i])
    {
    zoom = i;
    break;
    }
    }

    //return a BestView object with the center point and zoom level to use return new BestView(centerPoint, zoom);
    }

    Listing 2 Method to calculate the best map view for an array of Locations

    The method that calculates the best map view uses a method called HaversineDistance. This method calculates the distance in kilometers between two coordinates using the Haversine formula. The code for this method is as follows:

    /// <summary>
    /// Calculate the distance in kilometers between two coordinates
    /// </summary>
    /// <param name="lat1"></param>
    /// <param name="lon1"></param>
    /// <param name="lat2"></param>
    /// <param name="lon2"></param>
    /// <returns></returns>
    private double HaversineDistance(double lat1, double lon1, double lat2, double lon2)
    {
    double earthRadius = 6371;
    double factor = Math.PI / 180;
    double dLat = (lat2 - lat1) * factor;
    double dLon = (lon2 - lon1) * factor;
    double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(lat1 * factor) * Math.Cos(lat2 * factor)
    * Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
    double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

    return earthRadius * c;
    }

    Listing 3 Haversine distance method

    Request Map Image from the Imagery Service

    By specifying a specific zoom level and center point for a map, this ensures that we have at least one point of reference between pixel coordinates and a latitude/longitude coordinate. The following method retrieves an image URL of a map for a specific map view. The image is then retrieves using a stream.

    /// <summary>
    /// Gets map from VE Imagery Web Service
    /// </summary>
    /// <param name="view">Map view</param>
    /// <returns></returns>
    private Image GetMapImage(BestView view)
    {
    //Map uri request object is created MapUriRequest mapUriRequest = new MapUriRequest();

    // Credentials are set using a valid Virtual Earth Token mapUriRequest.Credentials = new VEImageryService.Credentials();
    mapUriRequest.Credentials.Token = clientToken;

    //Pass centerpoint of map mapUriRequest.Center = view.center; // Map style and zoom level are set MapUriOptions mapUriOptions = new MapUriOptions();
    mapUriOptions.Style = MapStyle.Road;

    //Set zoom level of map mapUriOptions.ZoomLevel = view.zoom; // Size of the requested image in pixels is set mapUriOptions.ImageSize = new VEImageryService.SizeOfint();
    mapUriOptions.ImageSize.Height = mapHeight;
    mapUriOptions.ImageSize.Width = mapWidth;

    //Map options are added to the request mapUriRequest.Options = mapUriOptions; //ImageryServiceClient object created ImageryServiceClient imageryService = new ImageryServiceClient();

    //A request for a map uri is made MapUriResponse mapUriResponse = imageryService.GetMapUri(mapUriRequest); //Get image from URI System.Net.WebRequest request =
    System.Net.WebRequest.Create(mapUriResponse.Uri.Replace("{token}", clientToken));
    System.Net.WebResponse response = request.GetResponse(); System.IO.Stream responseStream = response.GetResponseStream(); //return image return Image.FromStream(responseStream);
    }

    Listing 4 Method to retrieve map image from the VE Web Services for best map view

    Calculate Pixel Coordinate for a Location

    Virtual Earth tiles are positioned using quad key tile positioning. In Virtual Earth a map tile is 256 pixels by 256 pixels. For zoom level one, there are 4 map tiles displayed, making the total map width and height to display the whole world 512 pixels by 512 pixels. If the zoom level is 2, there are 16 map tiles being displayed, making the total map width and height to display the whole world 1024 pixels by 1024 pixels. Additional information the Virtual Earth tiling system can be found here: http://msdn.microsoft.com/en-us/library/bb259689.aspx

    With the Virtual Earth tiling system in mind, all pixel coordinates for a set of latitude/longitude coordinates can be calculated. Using the center point of the map image the top left hand corner of the map image that is returned by the Virtual Earth imagery service can be calculated as a pixel location on a map that displays the whole world. Relative pixel coordinates can be then calculated for all location latitude/longitude coordinates.

    The following method takes in a Location object and a BestView object and returns a Point object which refers to the pixel location of a latitude/longitude coordinate on the map image.

    /// <summary>
    /// Converts a latlitude longitude coordinate to a pixel coordinate of a map based on the map view
    /// </summary>
    /// <param name="latlong"></param>
    /// <param name="view"></param>
    /// <returns></returns>
    private Point LatLongToPixel(Location latlong, BestView view)
    {
    //Formulas based on following article: //http://msdn.microsoft.com/en-us/library/bb259689.aspx //calcuate pixel coordinates of center point of map double sinLatitudeCenter = Math.Sin(view.center.Latitude * Math.PI / 180);
    double pixelXCenter = ((view.center.Longitude + 180) / 360) * 256 * Math.Pow(2, view.zoom);
    double pixelYCenter = (0.5 - Math.Log((1 + sinLatitudeCenter) / (1 - sinLatitudeCenter)) / (4 * Math.PI))
    * 256 * Math.Pow(2, view.zoom);

    //calculate pixel coordinate of location double sinLatitude = Math.Sin(latlong.Latitude * Math.PI / 180);
    double pixelX = ((latlong.Longitude + 180) / 360) * 256 * Math.Pow(2, view.zoom);
    double pixelY = (0.5 - Math.Log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI))
    * 256 * Math.Pow(2, view.zoom);

    //calculate top left corner pixel coordiates of map image double topLeftPixelX = pixelXCenter - (mapWidth / 2);
    double topLeftPixelY = pixelYCenter - (mapHeight / 2);

    //calculate relative pixel cooridnates of location double x = pixelX - topLeftPixelX;
    double y = pixelY - topLeftPixelY;

    return new Point((int)Math.Floor(x), (int)Math.Floor(y));
    }

    Listing 5 LatLong to Pixel coordinate method

    Putting it all together

    In order for these methods to work in a WinForm application the following references will have to be made:

    using System.Drawing.Design;
    using System.Drawing.Drawing2D;
    using System.IO;

    Listing 6 Required References

    A reference to the Virtual Earth Imagery Service and the Virtual Earth token service will also be required.

    The following global variables will also be needed:

    string clientToken;
    int mapWidth = 600;
    int mapHeight = 400;

    Listing 7 Global Variables

    The following method will calculate the best map view for an array of locations, retrieve a map image from the imagery service, add custom icons to the map image and then display the map image in a picture box.

    /// <summary>
    /// Generate map image with custom icons
    /// </summary>
    /// <param name="points">Array of Location objects</param>
    private void GenerateImage(Location[] points)
    {
    //Get Best Map View BestView mapView = CalculateMapView(points); //Generate default map for best view Image map = GetMapImage(mapView); //add custom icons to map image AddCustomIcon(mapView, map, points); //display map MapImageBox.Image = map; }

    Listing 8 Method to Generate map image with custom icons

    The following method can be used to add the custom icons to a map image:

    /// <summary>
    /// Adds custom icon image to map image
    /// </summary>
    /// <param name="view"></param>
    /// <param name="map"></param>
    /// <param name="points"></param>
    private void AddCustomIcon(BestView view, Image map, Location[] points)
    {
    //define the map as a gaphics object Graphics graphics = Graphics.FromImage(map); //Define custom icon Image customIcon = Image.FromFile("../../VEDefaultPin.gif");

    //custom icon offset with respect to the top left corner of icon Point imageOffset = new Point(12, 12);

    //Add custom icons to map image for (int i = 0; i < points.Length; i++)
    {
    Point point = LatLongToPixel(points[i], view);
    int x = point.X - imageOffset.X;
    int y = point.Y - imageOffset.Y;
    graphics.DrawImageUnscaled(customIcon, x, y);
    }
    }

    Listing 9 Method to add custom icons to a map image

    This method can add a custom icon image and specify an image offset similar to the VECustomIconSpecification.

    Here is an example of five locations plotted onto a map using Virtual Earth:

    clip_image002

    Figure 2 Points plotted using the JavaScript version of Virtual Earth

    Here is an example of the same points being plotted onto a map image that is generated from the Virtual Earth Imagery Service using the methods in this article.

    clip_image004

    Figure 3 Custom icons on a VE Imagery Service image

    Conclusion

    Combine these methods with a valid client token and you will be able to add your custom icons to a map image. Complete sample code can be found here:
    http://cid-e7dba9a4bfd458c5.skydrive.live.com/self.aspx/VE%20Sample%20code/CustomIconVEService.zip

    This article was written by Richard Brundritt. Richard works for Infusion Development.