Bing Pdf

Document Sample
Bing Pdf Powered By Docstoc
					Contents
Bing Spatial Data Services .............................................................................................................. 3
  Getting Started with the Spatial Data Services ............................................................................ 4
  What's New in Bing Spatial Data Services ................................................................................... 6
  Public Data Sources ..................................................................................................................... 7
    FourthCoffeeSample ................................................................................................................. 7
    NAVTEQNA .............................................................................................................................. 9
    NAVTEQEU ............................................................................................................................ 11
    Traffic Incident Data Source ................................................................................................... 12
    POI Entity Types ..................................................................................................................... 19
  Bing Spatial Data Services API Reference ................................................................................ 25
    Dataflow and Data Source Job Requirements ....................................................................... 26
    Geocode Dataflow API ........................................................................................................... 26
      Create a Geocode Job and Upload Data ............................................................................ 28
      Get Status of a Geocode Job .............................................................................................. 34
      Download Geocode Job Results ......................................................................................... 38
      Geocode Dataflow Response Description .......................................................................... 42
      Geocode Dataflow Walkthrough .......................................................................................... 49
      Geocode Dataflow Sample Code ........................................................................................ 56
      Geocode Dataflow Data Schema ........................................................................................ 67
      Geocode Dataflow Sample Input and Output Data ............................................................. 75
      Entity Types ......................................................................................................................... 86
    Data Source Management API ............................................................................................... 98
      Load Data Source Dataflow ................................................................................................ 99
        Create a Load Data Source Job and Input Entity Data.................................................. 101
        Get Status of a Load Data Source Job .......................................................................... 110
        Load Data Source Dataflow Response Description ....................................................... 117
        Load Data Source Data Schema and Sample Input ...................................................... 124
        Helpful Tips for Entity Data ............................................................................................ 130
        Load Data Source Dataflow Sample Code (C#) ............................................................ 131
        Load Data Source Dataflow Sample Code (VB) ............................................................ 139
      Get Data Source Information ............................................................................................. 146
      Data Source Download Dataflow ...................................................................................... 153
        Create a Download Job ................................................................................................. 154
        Get Status of a Download Data Source Job .................................................................. 158
        Get Downloaded Data .................................................................................................... 162
        Download Data Source Walkthrough ............................................................................. 165
        Download Data Source Dataflow Response Description............................................... 170
      Delete a Data Source ........................................................................................................ 176
Query API ............................................................................................................................. 178
  Query by Area ................................................................................................................... 179
  Query Near a Route .......................................................................................................... 194
  Query by Property ............................................................................................................. 204
  Query by ID ....................................................................................................................... 217
  Query Options ................................................................................................................... 226
  Query Response Description ............................................................................................ 231
  Query API Sample Code (C#) ........................................................................................... 233
  Query API Sample Code (VB) ........................................................................................... 240
Status Codes and Errors ...................................................................................................... 247
Bing Spatial Data Services
The Bing™ Spatial Data Services Application Programming Interface (API) provides a
Representational State Transfer (REST) interface that can geocode, store and query spatial data.
This simple REST interface accomplishes tasks by setting parameters in a URL and then
submitting the URL as an HTTP request. The HTTP response returns the results of the request.


     If you would like to request access to Bing Spatial Data Services, email
     MAPLIC@microsoft.com with your Bing Maps Account ID and (for publicly-accessible
     sites) top level domains. You must email this request from the email account associated
     with your Bing Maps Account in the Bing Maps Account Center
     (http://www.bingmapsportal.com).
     As an enterprise user, you can also use the Bing Maps Account Center to geocode, edit
     and upload entity data to a new or existing data source. You can also download and
     delete data sources. For more information, see Creating and Managing Data Sources.
With the Bing Spatial Data Services, you can:
   Geocode and Reverse-Geocode large numbers of locations with the Geocode Dataflow API.
   Store and query sets of properties for an entity type that you define, such as set of retail
     stores or restaurants. The Load Data Source Dataflow creates a data store called a data
     source for an entity type that you define and uploads entity data to that data source. The data
     schema and input data you provide can be specified by using XML or as a set of values
     separated by commas, tabs or pipe (|) characters. After a data source is created, use the
     URLs in the Query API to make queries. You can Query by Area, Query by Property and
     Query Near a Route. You can also Query by ID.
   Download geocoded entity data from your data source with the Data Source Download
     Dataflow.
   Delete a data source. For more information, see Deleting a Data Source.
You must be an enterprise customer and you need Bing Maps Keys to use the Bing Spatial Data
Services. For more information about how to get Bing Maps Keys, see Getting a Bing Maps Key.
To become an enterprise customer, email maplic@microsoft.com.
If you are reading this documentation online, you can download the Bing Spatial Data Services
CHM file or PDF file for offline viewing.
The Bing Spatial Data Services documentation contains reference topics for the following API:


Geocode Dataflow API                               Use this API to geocode a set of spatial data.

Data Source Management API                         Use this API to create, update, and delete data
                                                   sources. A data source is a type of data store
                                                   that stores entities of a user-defined entity type.


                                                                                                     3
Query API                                         Use this API to query a data source.




Transaction accounting is provided when you use the Bing Spatial Data Services. For more
information about billable and non-billable transactions for the Bing Spatial Data Services, see
Usage Transactions.


In this Section
Getting Started with the Spatial Data Services    Provides information to help you get started
                                                  with the Bing Spatial Data Services.

Public Data Sources                               Includes descriptions of public data sources
                                                  that you can query.

Bing Spatial Data Services API Reference          Includes detailed descriptions and examples for
                                                  the Bing Spatial Data Services API.




See Also
Terms and Conditions


Getting Started with the Spatial Data Services
Bing Spatial Data Services provides REST APIs that work with large sets of spatial data. With
these APIs you can geocode spatial data and you can store data that has a spatial component in
data sources that you can query.
See the links in the How to: sections below to find out more information.


Get started by signing up for a Bing Maps Account and
requesting access
To get started with the Bing Spatial Data Services, you must have a Bing Maps Account. For
information about getting a Bing Maps Account, see Getting a Bing Maps Key.
After you have a Bing Maps Account, you can request access to Bing Spatial Data Services by
emailing MAPLIC@microsoft.com with your Bing Maps Account ID and (for publicly-accessible
sites) top level domains. You must email this request from the email account associated with your
Bing Maps Account in the Bing Maps Account Center (http://www.bingmapsportal.com).
When you have access, you can create and use Bing Maps Keys with the Bing Spatial Data
Services.

                                                                                                   4
    If you are an enterprise customer, you can use the Bing Maps Account Center to create
    and manage data sources. You can also download and delete a data source. For more
    information, see Creating and Managing Data Sources.


How to: Geocode and reverse-geocode spatial data
Use the Geocode Dataflow API to create dataflow jobs that geocode and reverse-geocode large
sets of data. For more information, see Geocode Dataflow API. For an example of the complete
process, see the Geocode Dataflow Walkthrough


How to: Create a data source
Use the Load Data Source Dataflow to create a new data source.


How to: Update a data source
Use the Load Data Source Dataflow to update an existing data source.


How to: Download a data source
Use the Data Source Download Dataflow API to download a data source.


How to: Delete a data source
Use the Delete a Data Source API to delete a data source.


How to: Query a data source
Use the Query API to query for entities in a data source.


How to: Get information about data sources
Use the Get Data Source Information API to get information about a data source such as the
entity type and properties that it stores. You can also request information about all of the data
sources that belong to a Bing Maps Account.


How to: Use the Spatial Data Services with other Bing Maps APIs
Read the Show Spatial Data Search Results on a Map and Searching for Traffic Incidents Along
a Route articles to learn how integrate Bing Spatial Data Services with Bing Maps Rest Services
and the Bing Maps AJAX Control, Version 7.0.


Public Data Sources
The following are public data sources that you can access with any Bing Maps Key.

                                                                                                    5
NAVTEQNA                                             NavTechNA is a data source that contains
                                                     points of interest in North America.

NAVTEQEU                                             NavTechEU is a data source that contains
                                                     points of interest in Europe.

Traffic Incident Data Source                         TrafficIncident is a data source that contains
                                                     traffic incidents data in the United States and
                                                     Canada.

FourthCoffeeSample                                   FourthCoffeeSample is a data source with
                                                     sample data.



Transaction Accounting
Transactions are counted for each Bing Spatial Data Services request sent with a valid Bing
Maps Key. For information about billable and non-billable transactions for the Bing Spatial Data
Services and how to view them, see Viewing Bing Maps Usage Reports.


What's New in Bing Spatial Data Services
The latest release of the Bing Spatial Data Services contains the following new features.
   Query Near a Route: Use the Query Near a Route API to get entities within one (1) mile or
     1.6 kilometers of a walking or driving route.
       http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acd
       f9496133d4f23/FourthCoffeeSample/FourthCoffeeShops?spatialFilter
       =nearRoute('Webster,TX','Kemah,TX')&$select=EntityID,Latitude,Longitud
       e,Name,Phone&$top=10&key=queryKey
   Make Incremental Data Source Updates: Update existing entities and add new entities to a
     data source Load Data Source Dataflow.
     An incremental data source update uses the same process (Load Data Source Dataflow) as
     creating a data source or completely replacing its content. For an incremental update, set the
     loadOperation parameter to incremental and then upload the data schema and only the
     entities that you want to update or add. The data schema must match the current data source
     data schema.
   Get Traffic Incident Data: Use the Traffic Incident Data Source and the Query by Area API
     to find traffic incidents near a location or in a specified area. See Traffic Incident Data Source
     for an example.
   Wildcard Data Source Search: Use the StartsWith and EndsWith OData Query Options to
     perform wildcard searches on data source properties. See Query Options for a description of
     these options.



                                                                                                       6
      http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acd
      f9496133d4f23/FourthCoffeeSample/FourthCoffeeShops?spatialFilter
      =nearby(27.894007,-
      82.670776,10)&$filter=StartsWith(PrimaryCity,'Clear')%20eq%20true&$orderby
      =IsWheelchairAccessible&$select=DisplayName,IsWheelChairAccessib
      le,Latitude,Longitude&$format=json&key=queryKey


Public Data Sources
The Bing Spatial Data Services provide the following public data sources for your use.


Data Source                                        Description

FourthCoffeeSample                                 This data source contains sample data. The
                                                   examples provided in the Query API
                                                   documentation use this data source.

NAVTEQNA                                           This data source contains points of interest for
                                                   North America.

NAVTEQEU                                           This data source contains points of interest for
                                                   Europe.

Traffic Incident Data Source                       This data source contains traffic incident data
                                                   that you can use to query for traffic incidents in
                                                   an area by using the Query by Area API.


For the list of Standard Industry Code (SIC) entity type IDs that you can query for the
NAVTEQNA and NAVTEQEU data sources, see POI Entity Types.


FourthCoffeeSample
The FourthCoffeeSample data source is a sample data source that you can use to learn how to
query and get data source information by using the Bing Spatial Data Services.


    All Query API transactions are billable transactions including queries to the
    FourthCoffeeSample data source. Therefore, you may want to create an evaluation
    account to use with this data source. For more information about how to create an
    evaluation account, see Getting a Bing Maps Key.


Entity Properties
The following table describes the properties that you can query. These properties make up the
FourthCoffeeShops entity type that is used by the FourthCoffeeSample data source.


                                                                                                      7
Property                 Data Type      Example Value

EntityID (Primary Key)   Edm.String     -18147

Latitude                 Edm.Double     50.792458

Longitude                Edm.Double     -1.146712

AddressLine              Edm.String     Bury Road

PrimaryCity              Edm.String     Alverstoke

SecondaryCity            Edm.String     Gosport

Subdivision              Edm.String     Hampshire

CountryRegion            Edm.String     United Kingdom

PostalCode               Edm.String     PO123

Phone                    Edm.String     800-555-0111

Manager                  Edm.String     Aaron Con

StoreOpen                Edm.String     Y

StoreType                Edm.String     Kiosk

Name                     Edm.String     Fourth Coffee Store #18147

DisplayName              Edm.String     Fourth Coffee Store #18147,
                                        Alverstoke, Hampshire,
                                        United Kingdom

IsWiFiHotSpot            Edm.Boolean    0 [false]

SeatingCapacity          Edm.Int64      50

IsWheelChairAccessible   Edm.Boolean    1 [true]

AcceptsOnlineOrders      Edm.Boolean    0 [false]

AcceptsCoffeeCards       Edm.Boolean    1 [true]

Open                     Edm.Int64      800

Close                    Edm.Int64      2200

CreatedDate              Edm.DateTime   2010-11-10T17:19:36

LastUpdatedDate          Edm.DateTime   2010-11-15T17:19:36




                                                                 8
You can also retrieve the data schema by using the following URL with any Bing Maps Key. For
more information, see Get Data Source Information.
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/$metadata?key=anyBingMapsKey


How to query the FourthCoffeeSample data source
You can query FourthCoffeeShops entities in the FourthCoffeeSample data source by using the
following base URL and adding additional parameters such a geographical area to search and
the properties you want to return.
Base Query URL
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops

Query Example
The following query example queries for FourthCoffeeShops entities within 5 kilometers of a
location that is specified as a latitude and longitude pair. Because this is a sample data source,
the query key you use can be any Bing Maps Key. For more information, see Query API.
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops?spatialFilter=nearby(40.83274904439099,-
74.3163299560546935,5)&$select=EntityID,Latitude,Longitude,__Distance&$top=3&key=anyBingM
apsKey



NAVTEQNA
The NAVTEQNA data source contains information about points of interest (POIs) in North
America. You can query this data source by using the Bing Spatial Data Services Query API and
any Bing Maps Key.


    When you query this data source for specific property values, you must include a
    geographical area to search. This does not apply if you are querying for specific entities
    using entity ID. See Query by Area and Query by ID for details. Query Near a Route is
    not supported for this data source.


POI Entity Properties
The following table describes the properties that you can query to get information about a point of
interest in North America. These properties make up the NAVTEQPOIs entity type that is used by
the NAVTEQNA data source.


Property                           Data Type                         Example Value

EntityID (Primary Key)             Edm.String                        111

                                                                                                     9
Property                           Data Type                         Example Value

Name                               Edm.String                        Coho Vineyard & Winery

DisplayName                        Edm.String                        Coho Vineyard & Winery

Latitude                           Edm.Double                        50.792458

Longitude                          Edm.Double                        -1.146712

AddressLine                        Edm.String                        1234 Main Street

Locality                           Edm.String                        Helena

AdminDistrict                      Edm.String                        Montana

AdminDistrict2                     Edm.String                        Lewis and Clark

PostalCode                         Edm.String                        98146

CountryRegion                      Edm.String                        USA

Phone                              Edm.String                        800-5550111

EntityTypeID                       Edm.String                        2084



Entity Types
For a complete list of the entity type IDs that you can query, see POI Entity Types.


How to query the NAVTEQNA data source
You can query NAVTEQNA data source by using the following base URL and adding additional
parameters such a geographical area to search and the properties you want to return. For a
complete description of query options and more examples, see Query API.


    When you query this data source for specify property values, you must include a
    geographical area to search. This does not apply if you are querying for specific entities
    using entity ID. See Query by Area and Query by ID for details.
Base Query URL
http://spatial.virtualearth.net/REST/v1/data/f22876ec257b474b82fe2ffcb8393150/NavteqNA/Na
vteqPOIs

Query Example
The following query example queries for banks within 5 kilometers of the specified latitude and
longitude. The query key you use can be any Bing Maps Key. For complete information about
querying a data source, see Query API.



                                                                                                  10
http://spatial.virtualearth.net/REST/v1/data/f22876ec257b474b82fe2ffcb8393150/NavteqNA/Na
vteqPOIs?spatialFilter=nearby(40.83274904439099,-
74.3163299560546935,5)&$filter=EntityTypeID%20eq%20'6000'&$select=EntityID,DisplayName,La
titude,Longitude,__Distance&$top=3&key=anyBingMapsKey



NAVTEQEU
The NAVTEQEU data source contains information about points of interest (POIs) in Europe. You
can query this data source by using the Bing Spatial Data Services Query API and any Bing
Maps Key.


    When you query this data source for specific property values, you must include a
    geographical area to search. This does not apply if you are querying for specific entities
    using entity ID. See Query by Area and Query by ID for details. Query Near a Route is
    not supported for this data source.


POI Entity Properties
The following table describes the properties that you can query to get information about a point of
interest. These properties make up the NAVTEQPOIs entity type that is used by the NAVTEQEU
data source.


Property                           Data Type                         Example Value

EntityID (Primary Key)             Edm.String                        111

LanguageCode                       Edm.String                        GER

Name                               Edm.String                        Contoso, Ltd

DisplayName                        Edm.String                        Contoso, Ltd

Latitude                           Edm.Double                        36.7222

Longitude                          Edm.Double                        -4.4450

AddressLine                        Edm.String                        Calle Rodriguez, 1234

Locality                           Edm.String                        Malaga

AdminDistrict                      Edm.String                        Andalucia

AdminDistrict2                     Edm.String                        MA

PostalCode                         Edm.String                        28146

CountryRegion                      Edm.String                        España

Phone                              Edm.String                        +34 xx xxx xxxx


                                                                                                 11
Property                            Data Type                         Example Value

EntityTypeID                        Edm.String                        3000



Entity Types
For a complete list of the entity type IDs that you can query, see POI Entity Types.


How to query the NAVTEQEU data source
You can query the NAVTEQEU data source by using the following base URL and adding
additional parameters such a geographical area to search and the properties you want to return.
For a complete description of query options and more examples, see Query API.
Base Query URL
http://spatial.virtualearth.net/REST/v1/data/c2ae584bbccc4916a0acf75d1e6947b4/NavteqEU/Na
vteqPOIs

Query Example
The following query example queries for banks within 5 kilometers of the specified latitude and
longitude. The query key you use can be any Bing Maps Key.
http://spatial.virtualearth.net/REST/v1/data/c2ae584bbccc4916a0acf75d1e6947b4/NavteqEU/Na
vteqPOIs?spatialFilter=nearby(50.1120796203613,8.68340969085693,100)&$select=EntityID,Lat
itude,Longitude,DisplayName,__Distance,LanguageCode&$top=3&key=anyBingMapsKey



Traffic Incident Data Source
The TrafficIncident data source contains information traffic incidents. You can query for traffic
incidents in a specified area by using the Bing Spatial Data Services Query by Area API and the
Query Near a Route API and any Bing Maps Key.


Traffic Incident Properties
The following table describes the information provided for a traffic incident.


Property                           Data Type                        Description and Values

IncidentId                         Edm.Int64                        A unique ID for the incident.
                                                                    Example: 210546697

Latitude                           Edm.Double                       The latitude of the incident.
                                                                    Example: 38.64829

Longitude                          Edm.Double                       The longitude of the incident.
                                                                    Example: -94.36405


                                                                                                     12
Property          Data Type      Description and Values

LastModifiedUTC   Edm.DateTime   The time the incident
                                 information was last updated
                                 specified as a Coordinated
                                 Universal Time (UTC) time.
                                 Example: 2011-12-
                                 05T17:18:21.67Z

StartTimeUTC      Edm.DateTime   The time the incident occurred
                                 specified as a Coordinated
                                 Universal Time (UTC) time..
                                 Example: 2011-12-
                                 05T17:16:00Z

EndTimeUTC        Edm.DateTime   The time that the traffic incident
                                 will end specified as a
                                 Coordinated Universal Time
                                 (UTC).
                                 Example: 2011-12-
                                 05T17:46:00Z

Type              Edm.Int64      The type of incident specified
                                 by one of the following values.
                                    Accident
                                    Congestion
                                    DisabledVehicle
                                    MassTransit
                                    Miscellaneous
                                    OtherNews
                                    PlannedEvent
                                    RoadHazard
                                    Construction
                                    Alert
                                    Weather
                                 Example: Accident

Severity          Edm.Int64      The level of importance of
                                 incident specified by one of the
                                 following values.
                                    LowImpact
                                    Minor


                                                                 13
Property          Data Type     Description and Values
                                   Moderate
                                   Serious
                                Example: Minor

Verified          Edm.Boolean   A value of true indicates that
                                the incident has been visually
                                verified or otherwise officially
                                confirmed by a source like the
                                local police department.
                                Example: true

RoadClosed        Edm.Boolean   A value of true indicates that
                                there is a road closure.
                                Example: false

Description       Edm.String    A description of the incident.
                                Examples:
                                   W 95th St between Switzer
                                     Rd and Bluejacket Dr -
                                     construction
                                   WB Johnson Dr at I-435 -
                                     bridge repair

DetourInfo        Edm.String    A description of a detour.
                                Examples:
                                   Take 63rd St to Roe Ave
                                     and head south to 67th St
                                   take US-40 to Blue Ridge
                                     Cut-Off

LaneInfo          Edm.String    A description specific to lanes,
                                such as lane closures.
                                Examples:
                                   All lanes blocked
                                   Left lane blocked

CongestionInfo    Edm.String    A description of the congestion.
                                Examples:
                                   generally slow
                                   sluggish

ToPointLatitude   Edm.Double    The latitude of the point that
                                specifies the end of a traffic

                                                                 14
Property                           Data Type                         Description and Values
                                                                     incident, such as the end of a
                                                                     construction zone.
                                                                     Example: 38.65831

ToPointLongitude                   Edm.Double                        The longitude of the point that
                                                                     specifies the end of a traffic
                                                                     incident, such as the end of a
                                                                     construction zone.
                                                                     Example: -94.36706



How to query the TrafficIncidents data source
You can query the TrafficIncidents data source by using the following base URL and specifying
an area to search by using the Query by Area API or the Query Near a Route API.
Base Query URL
http://spatial.virtualearth.net/REST/v1/data/8F77935E46704C718E45F52D0D5550A6/TrafficInci
dents/TrafficIncident

Query Example
The following query example queries for traffic incidents along a route from Houston, Texas to
Galveston, Texas by using the Query Near a Route API. The query key you use can be any Bing
Maps Key.
http://spatial.virtualearth.net/REST/v1/data/8F77935E46704C718E45F52D0D5550A6/TrafficInci
dents/TrafficIncident?spatialFilter=nearRoute('Houston,TX','Galveston,Tx')&key=anyBingMap
sKey




XML Response
This request returns traffic incident information in the following format.
<?xml version="1.0" encoding="utf-8"?>

<feed xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
xmlns="http://www.w3.org/2005/Atom">

  <title type="text"></title>

  <id>uuid:e767cc8a-6932-4ec1-9b78-d2c36aa81989;id=45353</id>

  <rights type="text">© 2012 Microsoft and its suppliers.          This API and any results
cannot be used or accessed without Microsoft's express written permission.</rights>

  <updated>2012-02-01T19:08:15Z</updated>


                                                                                                      15
 <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/8f77935e46704c718e45f52d0d5550a6/Traffi
cIncidents/TrafficIncident('277303858')</id>

   <title type="text"></title>

   <updated>2012-02-01T19:08:15Z</updated>

   <content type="application/xml">

     <m:properties>

       <d:IncidentId>277303858</d:IncidentId>

       <d:Latitude m:type="Edm.Double">29.378040</d:Latitude>

       <d:Longitude m:type="Edm.Double">-95.020810</d:Longitude>

       <d:LastModifiedUTC>2012-01-25T14:29:02.01Z</d:LastModifiedUTC>

       <d:StartTimeUTC>2011-10-17T12:00:00Z</d:StartTimeUTC>

       <d:EndTimeUTC>2012-02-12T14:00:00Z</d:EndTimeUTC>

       <d:Type>Construction</d:Type>

       <d:Severity>Minor</d:Severity>

       <d:Verified>true</d:Verified>

       <d:RoadClosed>true</d:RoadClosed>

       <d:Description>FM-1765 is closed in both directions between Delaney Rd to FM-2004
- construction</d:Description>

       <d:DetourInfo>follow the posted signage</d:DetourInfo>

       <d:LaneInfo></d:LaneInfo>

       <d:CongestionInfo></d:CongestionInfo>

       <d:ToPointLatitude m:type="Edm.Double">0</d:ToPointLatitude>

       <d:ToPointLongitude m:type="Edm.Double">0</d:ToPointLongitude>

       <d:LocationCodes></d:LocationCodes>

     </m:properties>

   </content>

 </entry>

 <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/8f77935e46704c718e45f52d0d5550a6/Traffi
cIncidents/TrafficIncident('277303880')</id>

   <title type="text"></title>

   <updated>2012-02-01T19:08:15Z</updated>

                                                                                       16
     <content type="application/xml">

       <m:properties>

          <d:IncidentId>277303880</d:IncidentId>

          <d:Latitude m:type="Edm.Double">29.769700</d:Latitude>

          <d:Longitude m:type="Edm.Double">-95.358560</d:Longitude>

          <d:LastModifiedUTC>2012-01-25T14:29:02.01Z</d:LastModifiedUTC>

          <d:StartTimeUTC>2011-08-08T11:54:00Z</d:StartTimeUTC>

          <d:EndTimeUTC>2012-10-01T22:00:00Z</d:EndTimeUTC>

          <d:Type>Construction</d:Type>

          <d:Severity>Minor</d:Severity>

          <d:Verified>true</d:Verified>

          <d:RoadClosed>true</d:RoadClosed>

          <d:Description>N Main St is closed in both directions between Naylor St and
Franklin St - construction</d:Description>

          <d:DetourInfo>Follow posted signage</d:DetourInfo>

          <d:LaneInfo></d:LaneInfo>

          <d:CongestionInfo></d:CongestionInfo>

          <d:ToPointLatitude m:type="Edm.Double">0</d:ToPointLatitude>

          <d:ToPointLongitude m:type="Edm.Double">0</d:ToPointLongitude>

          <d:LocationCodes></d:LocationCodes>

       </m:properties>

     </content>

    </entry>

</feed>




JSON Response
When you specify $format=json in the URL, the response returns traffic incident information in the
following JSON format.
{

    "d":{



                                                                                               17
     "__copyright":"\u00a9 2012 Microsoft and its suppliers.   This API and any results
cannot be used or accessed without Microsoft's express written permission.",

     "results":[

        {

             "__metadata":{



"uri":"https:\/\/spatial.virtualearth.net\/REST\/v1\/data\/8f77935e46704c718e45f52d0d5550
a6\/TrafficIncidents\/TrafficIncident('277303858')"

             },

             "IncidentId":"277303858",

             "Latitude":29.378040,

             "Longitude":-95.020810,

             "LastModifiedUTC":"2012-01-25T14:29:02.01Z",

             "StartTimeUTC":"2011-10-17T12:00:00Z",

             "EndTimeUTC":"2012-02-12T14:00:00Z",

             "Type":"Construction",

             "Severity":"Minor",

             "Verified":"true",

             "RoadClosed":"true",

             "Description":"FM-1765 is closed in both directions between Delaney Rd to FM-
2004 - construction",

             "DetourInfo":"follow the posted signage",

             "LaneInfo":"",

             "CongestionInfo":"",

             "ToPointLatitude":0,

             "ToPointLongitude":0,

             "LocationCodes":""

        },

        {

             "__metadata":{



"uri":"https:\/\/spatial.virtualearth.net\/REST\/v1\/data\/8f77935e46704c718e45f52d0d5550
a6\/TrafficIncidents\/TrafficIncident('277303880')"

             },

             "IncidentId":"277303880",

                                                                                          18
                "Latitude":29.769700,

                "Longitude":-95.358560,

                "LastModifiedUTC":"2012-01-25T14:29:02.01Z",

                "StartTimeUTC":"2011-08-08T11:54:00Z",

                "EndTimeUTC":"2012-10-01T22:00:00Z",

                "Type":"Construction",

                "Severity":"Minor",

                "Verified":"true",

                "RoadClosed":"true",

                "Description":"N Main St is closed in both directions between Naylor St and
Franklin St - construction",

                "DetourInfo":"Follow posted signage",

                "LaneInfo":"",

                "CongestionInfo":"",

                "ToPointLatitude":0,

                "ToPointLongitude":0,

                "LocationCodes":""

            }

        ]

    }

}




POI Entity Types
The following table shows the Standard Industry Code (SIC) entity IDs that are returned by the
NAVTEQNA and NAVTEQEU data sources.


Entity Type ID                                   Entity Type Name

2084                                             Winery

3578                                             ATM

4013                                             Train Station

4100                                             Commuter Rail Station

4170                                             Bus Station



                                                                                                 19
Entity Type ID   Entity Type Name

4444             Named Place

4482             Ferry Terminal

4493             Marina

4580             Public Sports Airport

4581             Airport

5000             Business Facility

5400             Grocery Store

5511             Auto Dealerships

5512             Auto Dealership-Used Cars

5540             Petrol/Gasoline Station

5571             Motorcycle Dealership

5800             Restaurant

5813             Nightlife

5999             Historical Monument

6000             Bank

6512             Shopping

7011             Hotel

7012             Ski Resort

7013             Other Accommodation

7014             Ski Lift

7389             Tourist Information

7510             Rental Car Agency

7520             Parking Lot

7521             Parking Garage/House

7522             Park & Ride

7538             Auto Service & Maintenance

7832             Cinema

7897             Rest Area


                                              20
Entity Type ID   Entity Type Name

7929             Performing Arts

7933             Bowling Centre

7940             Sports Complex

7947             Park/Recreation Area

7985             Casino

7990             Convention/Exhibition Centre

7992             Golf Course

7994             Civic/Community Centre

7996             Amusement Park

7997             Sports Centre

7998             Ice Skating Rink

7999             Tourist Attraction

8060             Hospital

8200             Higher Education

8211             School

8231             Library

8410             Museum

8699             Automobile Club

9121             City Hall

9211             Court House

9221             Police Station

9500             Business Service

9501             Other Communication

9502             Telephone Service

9503             Cleaning & Laundry

9504             Hair & Beauty

9505             Health Care Service

9506             Mover


                                                21
Entity Type ID   Entity Type Name

9507             Photography

9508             Video & Game Rental

9509             Storage

9510             Tailor & Alteration

9511             Tax Service

9512             Repair Service

9513             Retirement/Nursing Home

9514             Social Service

9515             Utilities

9516             Waste & Sanitary

9517             Campground

9518             Auto Parts

9519             Car Wash/Detailing

9520             Local Transit

9521             Travel Agent & Ticketing

9522             Truck Stop/Plaza

9523             Church

9524             Synagogue

9525             Government Office

9527             Fire Department

9528             Road Assistance

9529             Funeral Director

9530             Post Office

9531             Banquet Hall

9532             Bar or Pub

9533             Cocktail Lounge

9534             Night Club

9535             Convenience Store


                                            22
Entity Type ID   Entity Type Name

9536             Specialty Food Store

9537             Clothing Store

9538             Men's Apparel

9539             Shoe Store

9540             Specialty Clothing Store

9541             Women's Apparel

9542             Check Cashing Service

9543             Currency Exchange

9544             Money Transferring Service

9545             Department Store

9546             Discount Store

9547             Other General Merchandise

9548             Variety Store

9549             Garden Center

9550             Glass & Window

9551             Hardware Store

9552             Home Center

9553             Lumber

9554             Other House & Garden

9555             Paint

9556             Entertainment Electronics

9557             Floor & Carpet

9558             Furniture Store

9559             Major Appliance

9560             Home Specialty Store

9561             Computer & Software

9562             Flowers & Jewelry

9563             Gift, Antique, & Art


                                              23
Entity Type ID   Entity Type Name

9564             Optical

9565             Pharmacy

9566             Record, CD, & Video

9567             Specialty Store

9568             Sporting Goods Store

9569             Wine & Liquor

9570             Boating

9571             Theater

9572             Race Track

9573             Golf Practice Range

9574             Health Club

9575             Bowling Alley

9576             Sports Activities

9577             Recreation Center

9578             Attorney

9579             Dentist

9580             Physician

9581             Realtor

9582             RV Park

9583             Medical Service

9584             Police Service

9585             Veterinarian Service

9586             Sporting & Instructional Camp

9587             Agricultural Product Market

9589             Public Restroom

9590             Residential Area/Building

9591             Cemetery

9592             Highway Exit


                                                 24
Entity Type ID                                   Entity Type Name

9593                                             Transportation Service

9594                                             Lottery Booth

9707                                             Public Transit Stop

9708                                             Public Transit Access

9709                                             Neighborhood

9710                                             Weigh Station

9714                                             Cargo Centre

9715                                             Military Base

9717                                             Tollbooth (China/Korea)

9718                                             Animal Park

9719                                             Truck Dealership

9720                                             Truck Parking

9986                                             Home Improvement & Hardware Store

9987                                             Consumer Electronics Store

9988                                             Office Supply & Services Store

9989                                             Taxi Stand

9990                                             Premium Default

9991                                             Industrial Zone

9992                                             Place of Worship

9993                                             Embassy

9994                                             County Council

9995                                             Bookstore

9996                                             Coffee Shop

9998                                             Hamlet

9999                                             Border Crossing




Bing Spatial Data Services API Reference
This section contains reference documentation for the Bing Spatial Data Services.

                                                                                     25
In this section

Dataflow and Data Source Job Requirements         Defines limits on the total number of dataflow
                                                  and data source jobs, such as the number of
                                                  jobs that can be in process at the same time.

Geocode Dataflow API                              Describes the API that geocodes sets of spatial
                                                  data.

Data Source Management API                        Describes the API that creates and manages
                                                  data sources.

Query API                                         Describes the API that queries a data source.
                                                  You can query for entities in a given area,
                                                  along a route, or search by entity property or
                                                  ID.

Status Codes and Errors                           Describes the HTTP errors that can occur when
                                                  you use the Bing Spatial Data Services APIs.



Dataflow and Data Source Job Requirements
Dataflow jobs and Data source jobs have the following limits:
   You can have a total of 10 dataflow and data source jobs in process at the same time for a
     specified Bing Maps Account.
   You can run a total of 50 dataflow and data source jobs in a 24 hour period for a Bing Maps
     Account.
These totals include Geocode Dataflow jobs, Load Data Source Dataflow jobs, and Delete Data
Source jobs and apply to all jobs that have a status of “Pending”. Dataflow and data source jobs
have a status of “Pending” until they have completed processing at which time the status is set to
“Complete”.
A job is associated with a Bing Maps Account if it is using a Bing Maps Key that is from that
account. Therefore, if you created two jobs using two different Bing Maps Keys from the same
account, both jobs count towards the total number of jobs in process.


Geocode Dataflow API
The Geocode Dataflow API is a component of the Bing Spatial Data Services. You can use the
Geocode Dataflow API to geocode and reverse-geocode large sets of spatial data.


     To use the Geocode Dataflow API, you must have access to Bing Spatial Data Services.
     If you would like to request access to Bing Spatial Data Services, email
     MAPLIC@microsoft.com with your Bing Maps Account ID and (for publicly-accessible


                                                                                                   26
     sites) top level domains. You must email this request from the email account associated
     with your Bing Maps Account in the Bing Maps Account Center
     (http://www.bingmapsportal.com).
The Geocode Dataflow API specifies two URL templates. The Create a Geocode Job and Upload
Data URL uploads your data and creates a geocode job. The Get Status of a Geocode Job URL
gets the status of a geocode job. The same templates are used to both geocode and reverse-
geocode spatial data. You can combine data to geocode and data to reverse geocode and
process the combined data with one geocode job.
When your job has completed, the response to the Get Status of a Geocode Job URL provides
URLs to use to download data. Different URLs are provided for data that was processed
successfully and for data that encountered errors during processing. For more information, see
Download Geocode Job Results.
The spatial data you upload can be in XML format, or it can be provided as sets of values that
use commas, tabs, or pipe (|) characters to separate the values. For more information, see
Geocode Dataflow Data Schema and Geocode Dataflow Sample Input and Output Data. The
data that you download from a geocode job is provided in the same format as the data that you
upload.
For an overview of the Geocode Dataflow process, see Geocode Dataflow Walkthrough. For a
complete code sample, see Geocode Dataflow Sample Code.


     The data you upload with a Geocode Dataflow job must meet the following requirements:
   The size of the data must be no more than 300 MB. If the data is compressed, the size of the
     uncompressed data must be no more than 300 MB. Input data must use UTF-8 encoding.
   The data must contain no more than 200,000 location entities.
     You can download geocode results for up to 14 calendar days after a geocode job
     completes.
     There are limits on the number of dataflow and dataflow jobs that you can create. For
     more information, see Dataflow and Data Source Job Requirements.


In this Section

Create a Geocode Job and Upload Data              Describes how to create a job to geocode and
                                                  reverse-geocode the data.

Get Status of a Geocode Job                       Describes how to get the status of a geocode
                                                  job.

Download Geocode Job Results                      Describes how to download geocoded results.

Geocode Dataflow Response Description             Describes the information returned in the HTTP
                                                  responses.



                                                                                                 27
Geocode Dataflow Walkthrough                     Provides a detailed overview of how to use the
                                                 Geocode Dataflow.

Geocode Dataflow Sample Code                     Provides complete sample code that uses the
                                                 Geocode Dataflow to geocode data.

Geocode Dataflow Data Schema                     Describes the data schema for the input data
                                                 and the geocoded results.

Geocode Dataflow Sample Input and Output         Shows examples of all types of accepted input
Data                                             formats. This includes XML examples and
                                                 examples of sets of values separated by pipe
                                                 (|), comma, or tab characters

Entity Types                                     Provides a list of supported entity types.



Create a Geocode Job and Upload Data
Use the following URL to upload a set of spatial data and to create a job to geocode and reverse-
geocode the data.

Supported HTTP Methods
POST

URL template


    This template supports both HTTP and HTTPS protocols. URLs in the response use
    HTTPS protocol.
Upload locations and points and create a geocode job.
You can upload up to 300 MB of data for each job, and the number of location entities cannot be
larger than 200,000. If your data is compressed, the size of the uncompressed data must be no
more than 300 MB. Input data must use UTF-8 encoding.
The data that you upload can contain both data to geocode and data to reverse geocode. The
geocode process detects the type of data for each entry and performs the appropriate action.
There are limits on the number of dataflow and data source jobs that you can create. For more
information, see Dataflow and Data Source Job Requirements.
http://spatial.virtualearth.net/REST/v1/Dataflows/Geocode?description=description&input=i
nput&output=output&dataLocation=dataLocation&key=BingMapsKey

Template Parameters


    Parameter names and values are not case-sensitive except for the key parameter value.



                                                                                                28
Parameter     Alia   Description           Values
              s

dataLocati           Optional.             A Windows Azure™ Blob Service location that contains
on                   Specifies the         the data to process. The data must be in XML format.
                     location of the       The Blob Service uses the following URL formats:
                     data to download.     http://account-name.blob.core.windows.net/myDataFile
                                           https://account-name.blob.core.windows.net/myDataFile
                         You must          For more information, see Addressing Blob Service
                         set the           Requests.
                         dataLocati        Before you make your request to start the dataflow job,
                         on                make sure that the Blob Service URL is available publicly
                         parameter         or shared with a signature key. If the URL is shared with
                         to the            a signature key, it must be encoded. For more
                         location of       information, see Managing Access to Containers and
                         the data          Blobs.
                         or include
                                           The following content types are supported for data that is
                         the data          retrieved from an HTTP server.
                         to process
                                              application/xml
                         in the
                         HTTP                 text/xml
                         request. If          text/plain
                         you do               application/octet-stream
                         both, the         Example:
                         URL               dataLocation=http://myServer.myDomain.com/spatialDat
                         returns an        aSource
                         error.

description          Optional. A           A user-defined string that identifies the dataflow.
                     description of the    Example: description=Seattle Stores Geocode
                     geocode dataflow.

input                Required. The         One of the following values:
                     format of the input      xml
                     data file.               csv
                                              tab
                                              pipe
                                           For more information about input files for a Geocode
                                           Dataflow, see Geocode Dataflow Data Schema.
                                           Example: input=csv

key                  Required. A Bing      A Bing Maps Key obtained from the Bing Maps Account
                     Maps Key to use       Center.

                                                                                                   29
Parameter     Alia   Description           Values
              s
                     for the geocode
                     job.

output        o      Optional. The         One of the following values:
                     output format for     json [default]
                     the response.
                                           xml
                                           Example: output=xml


Input
This URL supports the following input formats. For examples, see Geocode Dataflow Sample
Input and Output Data.
When you create the HTTP request to upload data and create a geocode job, you must post the
input data in the body of the request or set the dataLocation parameter to a URL where your data
can be retrieved. You must also set the content type in the request to one of the following values,
depending on the format of the input data.
   XML (application/xml)
   Comma-delimited values (text/plain)
   Tab-delimited values (text/plain)
   Pipe-delimited values (text/plain)
   Binary (application/octet-stream)

Examples
This example creates a geocode job for spatial data that is provided in an xml format.
http://spatial.virtualearth.net/REST/v1/Dataflows/Geocode?input=xml&key=BingMapsKey



This example creates a geocode job for spatial data that is provided in an xml format and assigns
a description “My dataflow” to the job.
http://spatial.virtualearth.net/REST/v1/Dataflows/Geocode?input=xml&description=My
dataflow&key=BingMapsKey




Response
The response to this URL contains a representation of the geocode dataflow job instance.
This URL supports the following response formats.
   JSON (application/json)
   XML (application/xml)
For information about the response, see Geocode Dataflow Response Description.

                                                                                                 30
Sample Code
The following code shows how to create a job to geocode spatial data. The data you want to
geocode is uploaded as part of the job creation process. This code is part of a complete Geocode
Dataflow code sample. To view the complete code sample, see Geocode Dataflow Sample Code.
You may also want to read the Geocode Dataflow Walkthrough to get a step-by-step description
of how to use the Geocode Dataflow. The walkthrough includes example URLs and HTTP
responses.
        //Creates a geocode dataflow job and uploads spatial data to process.

        //Parameters:

        //     dataFilePath: The path to the file that contains the spatial data to
geocode.

        //     dataFormat: The format of the input data. Possible values are xml, csv, tab
and pipe.

        //     key: The Bing Maps Key to use for this job. The same key is used to get job
status and download results.

        //     description: Text that is used to describe the geocode dataflow job.

        //Return value : A URL that defines the location of the geocode dataflow job that
was created.

        static string CreateJob(string dataFilePath, string dataFormat, string key,
string description)

        {

             //Define parameters for the HTTP request

             //

             // The 'Content-Type' header of the HTTP Request must be "text/plain" or
"application/xml"

             // depending on the input data format.

             //

             string contentType = "text/plain";

             if (dataFormat.Equals("xml", StringComparison.OrdinalIgnoreCase))

                  contentType = "application/xml";



             StringBuilder queryStringBuilder = new StringBuilder();



             //

             // The 'input'(input format) and 'key' (Bing Maps Key) parameters are
required.


                                                                                             31
           //

           queryStringBuilder.Append("input=").Append(Uri.EscapeUriString(dataFormat));

           queryStringBuilder.Append("&");

           queryStringBuilder.Append("key=").Append(Uri.EscapeUriString(key));



           if (!String.IsNullOrEmpty(description))

           {

                //

                // The 'description' parameter is optional.

                //

                queryStringBuilder.Append("&");



queryStringBuilder.Append("description=").Append(Uri.EscapeUriString(description));

           }



           //Build the HTTP URI that will upload and create the geocode dataflow job

           UriBuilder uriBuilder = new UriBuilder("http://spatial.virtualearth.net");

           uriBuilder.Path = "/REST/v1/dataflows/geocode";

           uriBuilder.Query = queryStringBuilder.ToString();



           //Include the data to geocode in the HTTP request

           using (FileStream dataStream = File.OpenRead(dataFilePath))

           {

                HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(uriBuilder.Uri);



                //

                // The HTTP method must be 'POST'.

                //

                request.Method = "POST";

                request.ContentType = contentType;



                using (Stream requestStream = request.GetRequestStream())

                {


                                                                                        32
                   byte[] buffer = new byte[16384];

                   int bytesRead = dataStream.Read(buffer, 0, buffer.Length);

                   while (bytesRead > 0)

                   {

                        requestStream.Write(buffer, 0, bytesRead);



                        bytesRead = dataStream.Read(buffer, 0, buffer.Length);

                   }

               }



               //Submit the HTTP request and check if the job was created successfully.

               using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())

               {

                   //

                   // If the job was created successfully, the status code should be

                   // 201 (Created) and the 'Location' header should contain a URL

                   // that defines the location of the new dataflow job. You use this

                   // URL with the Bing Maps Key to query the status of your job.

                   //

                   if (response.StatusCode != HttpStatusCode.Created)

                        throw new Exception ("An HTTP error status code was encountered
when creating the geocode job.");



                   string dataflowJobLocation = response.GetResponseHeader("Location");

                   if (String.IsNullOrEmpty(dataflowJobLocation))

                        throw new Exception ("The 'Location' header is missing from the
HTTP response when creating a goecode job.");



                   return dataflowJobLocation;

               }

           }

       }




                                                                                          33
HTTP Status Codes


     For more details about these HTTP status codes, see Status Codes and Errors.
When the request is successful, the following HTTP status code is returned.
   201
When the request is not successful, the response returns one of the following errors.
   400
   500
   503


           The response may contain a 503 HTTP status error code when the number of
           pending geocode dataflow jobs is exceeded. The maximum number of pending
           geocode dataflow jobs that can be associated with a Bing Maps Key is 10.


Get Status of a Geocode Job
Use the following URL to get the status of a geocode job.

Supported HTTP Methods
GET

URL template


     This template supports both HTTP and HTTPS protocols. URLs in the response use
     HTTPS protocol.
Get status information for a geocode job.
The Bing Maps Key that you specify must be the same Bing Maps Key that you used to create
the job. A URL in the following format without the Bing Maps Key is provided in the response to
the URL request that you made to Create a Geocode Job and Upload Data. The URL is specified
in a link field with an attribute of self. For more information, see Geocode Dataflow Response
Description.
http://spatial.virtualearth.net/REST/v1/Dataflows/Geocode/jobID?output=output&key=BingMap
sKey

Template Parameters


     Parameter names and values are not case-sensitive except for the key parameter value.




                                                                                             34
Parameter         Alias        Description         Values

jobID                          Required. The       When you request a dataflow job, the job ID is
                               ID of the job.      returned in the ID field of the response. For
                                                   more information, see Geocode Dataflow
                                                   Response Description.
                                                   Example:
                                                   e14b1d9bd65c4b9d99d267bbb8102ccf

key                            Required. The       A Bing Maps Key from the Bing Maps Account
                               Bing Maps Key       Center.
                               that you used to    Example:
                               create the          key=abc123def456ghi789abc123def456ghi789
                               geocode job.

output            o            Optional. The       One of the following values:
                               output format for   json [default]
                               the response.
                                                   xml
                                                   Example: o=xml


Examples
This example requests resource information for the job with an ID of
e14b1d9bd65c4b9d99d267bbb8102ccf that was created by using the Bing Maps Key
b1c323ea234b1c323ea234b1c323ea234.
http://spatial.virtualearth.net/REST/v1/Dataflows/Geocode/e14b1d9bd65c4b9d99d267bbb8102cc
f?key=b1c323ea234b1c323ea234b1c323ea234


Response
This URL supports the following response formats.
    JSON: application/json
    XML: application/xml
For information about the response, see Geocode Dataflow Response Description.

Sample Code
The following code shows how to get the status of a geocode job. This code is part of a complete
Geocode Dataflow code sample. To view the complete code sample, see Geocode Dataflow
Sample Code. You may also want to read the Geocode Dataflow Walkthrough to get a step-by-
step description of how to use the Geocode Dataflow. The walkthrough includes example URLs
and HTTP responses.
class DownloadDetails

{



                                                                                               35
     public string jobStatus { get; set; }

     public string suceededlink { get; set; }

     public string failedlink { get; set; }



}



//Checks the status of a dataflow job and defines the URLs to use to download results
when the job is completed.

//Parameters:

//    dataflowJobLocation: The URL to use to check status for a job.

//    key: The Bing Maps Key for this job. The same key is used to create the job and
download results.

//Return value: A DownloadDetails object that contains the status of the geocode dataflow
job (Completed, Pending, Aborted).

//                When the status is set to Completed, DownloadDetails also contains the
links to download the results



static DownloadDetails CheckStatus(string dataflowJobLocation, string key)

{



     DownloadDetails statusDetails = new DownloadDetails();

     statusDetails.jobStatus = "Pending";



     //Build the HTTP Request to get job status

     UriBuilder uriBuilder = new UriBuilder(dataflowJobLocation + @"?key=" + key +
"&output=xml");

     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriBuilder.Uri);



     request.Method = "GET";



     //Submit the request and read the response to get job status and to retrieve the
links for

     //   downloading the job results

     //Note: The following conditional statements make use of the fact that the 'Status'
field will


                                                                                           36
   //   always appear after the 'Link' fields in the HTTP response.

   using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())

   {



        if (response.StatusCode != HttpStatusCode.OK)

            throw new Exception ("An HTTP error status code was encountered when checking
job status.");



        using (Stream receiveStream = response.GetResponseStream())

        {

            XmlTextReader reader = new XmlTextReader(receiveStream);

            while (reader.Read())

            {

                 if (reader.IsStartElement())

                 {

                     if (reader.Name.Equals("Status"))

                     {

                         //return job status

                         statusDetails.jobStatus = reader.ReadString();



                         return (statusDetails);

                     }

                     else if (reader.Name.Equals("Link"))

                     {

                         //Set the URL location values for retrieving

                         // successful and failed job results

                         reader.MoveToFirstAttribute();

                         if (reader.Value.Equals("output"))

                         {

                             reader.MoveToNextAttribute();

                             if (reader.Value.Equals("succeeded"))

                             {

                                 statusDetails.suceededlink = reader.ReadString();




                                                                                       37
                               }

                               else if (reader.Value.Equals("failed"))

                               {

                                   statusDetails.failedlink = reader.ReadString();

                               }

                           }

                       }

                   }

               }



           }



     }

     return (statusDetails);

}




HTTP Status Codes


     For more details about these HTTP status codes, see Status Codes and Errors.
When the request is successful, the following HTTP status code is returned.
   200
When the request is not successful, the response returns one of the following HTTP status codes.
   400
   500
   503


Download Geocode Job Results
The URLs to download results from a Geocode Job are provided when your job has completed
and you request job status. When your job has completed, the Status field in the job status
response is set to Completed and the URLs to use to download processed data are defined in the
response as XML Link values, or as part of a JSON links collection. You can distinguish these
link elements in the response because they have the attribute role set to output. These link
elements also specify the name attribute and set it to succeeded or failed to identify a download
URL for data that was processed successfully or for data that encountered errors during
processing. A link does not appear if there is no data to download. Therefore, if all your data was


                                                                                                 38
processed successfully, a link with the name attribute and set it to failed will not appear in the
response. The following are examples of these link elements.
XML
<Link role="output"
name="succeeded">https://spatial.virtualearth.net/REST/v1/dataflows/Geocode/5bf10c37df944
083b1879fbb0556e67e/output/succeeded</Link>

<Link role="output"
name="failed">https://spatial.virtualearth.net/REST/v1/dataflows/Geocode/5bf10c37df944083
b1879fbb0556e67e/output/failed</Link>



JSON
"links":[

       {

            "name":"succeeded",

            "role":"output",

            "url":"https:\/\/spatial.virtualearth.net\/REST\/v1\/dataflows\/Geocode\/5bf10c3
7df944083b1879fbb0556e67e\/output\/succeeded"

       },

       {

            "name":"failed",

            "role":"output",

            "url":"https:\/\/spatial.virtualearth.net\/REST\/v1\/dataflows\/Geocode\/5bf10c3
7df944083b1879fbb0556e67e\/output\/failed"

       }

]



To use these URLs, you must add the Bing Maps Key parameter that you used to create the job.
For example, to download the data that was processed successfully in the above example, you
would add the parameter key MyDataflowJobKey where MyDataflowJobKey is the Bing Maps
Key that you used to create the job.
https://spatial.virtualearth.net/REST/v1/dataflows/Geocode/5bf10c37df944083b1879fbb0556e6
7e/output/succeeded?key=MyDataflowJobKey

For information about the Geocode Dataflow data schema, see Geocode Dataflow Data Schema.

Sample Code
The following code shows how to download the results of a geocode job. The geocoded results
are saved in text files. This code is part of a complete Geocode Dataflow code sample. To view

                                                                                                     39
the complete code sample, see Geocode Dataflow Sample Code. You may also want to read the
Geocode Dataflow Walkthrough to get a step-by-step description of how to use the Geocode
Dataflow. The walkthrough includes example URLs and HTTP responses.
//Downloads job results to files names Success.txt (successfully geocoded results) and

//    Failed.txt (info about spatial data that was not geocoded successfully).

//Parameters:

//    statusDetails: Inclues job status and the URLs to use to download all geocoded
results.

//    key: The Bing Maps Key for this job. The same key is used to create the job and get
job status.



static void DownloadResults(DownloadDetails statusDetails, string key)

{

     //Write the results for data that was geocoded successfully to a file named
Success.xml

     if (statusDetails.suceededlink != null &&
!statusDetails.suceededlink.Equals(String.Empty))

     {

         //Create a request to download successfully geocoded data. You must add the Bing
Maps Key to the

         //   download location URL provided in the response to the job status request.

         UriBuilder successUriBuilder = new UriBuilder(statusDetails.suceededlink +
@"?key=" + key);

         HttpWebRequest request1 =
(HttpWebRequest)WebRequest.Create(successUriBuilder.Uri);



         request1.Method = "GET";



         using (HttpWebResponse response = (HttpWebResponse)request1.GetResponse())

         {

              if (response.StatusCode != HttpStatusCode.OK)

                  throw new Exception ("An HTTP error status code was encountered when
downloading results.");



              using (Stream receiveStream = response.GetResponseStream())

              {

                                                                                          40
                   StreamWriter successfile = new StreamWriter("Success.txt");

                   using (StreamReader r = new StreamReader(receiveStream))

                   {

                       string line;

                       while ((line = r.ReadLine()) != null)

                       {

                           successfile.Write(line);

                       }

                   }

                   successfile.Close();

               }



          }

   }



   //If some spatial data could not be geocoded, write the error information to a file
called Failed.xml

   if (statusDetails.failedlink != null &&
!statusDetails.failedlink.Equals(String.Empty))

   {

          //Create an HTTP request to download error information. You must add the Bing
Maps Key to the

          //   download location URL provided in the response to the job status request.

          UriBuilder failedUriBuilder = new UriBuilder(statusDetails.failedlink + @"?key="
+ key);

          HttpWebRequest request2 =
(HttpWebRequest)WebRequest.Create(failedUriBuilder.Uri);



          request2.Method = "GET";



          using (HttpWebResponse response = (HttpWebResponse)request2.GetResponse())

          {

               if (response.StatusCode != HttpStatusCode.OK)

                   throw new Exception ("An HTTP error status code was encountered when
downloading results.");

                                                                                           41
             using (Stream receiveStream = response.GetResponseStream())

             {

                 StreamWriter failedfile = new StreamWriter("Failed.txt");

                 using (StreamReader r = new StreamReader(receiveStream))

                 {

                      string line;

                      while ((line = r.ReadLine()) != null)

                      {

                          failedfile.Write(line);

                          }

                 }

                 failedfile.Close();

             }



        }

    }

}




Geocode Dataflow Response Description
The following tables describe the response syntax for a Geocode Dataflow request in a set of
hierarchical tables. Examples in JSON and XML formats are also provided.

Response
The following fields are the top-level fields in the Geocode Dataflow response. Additional tables
describe the fields in each of the collections.


JSON                          XML                          Type                    Description

copyright                     Copyright                    string                  A copyright
                                                                                   notice.

brandLogoUri                  BrandLogoUri                 string                  A URL that
                                                                                   references a
                                                                                   brand image to
                                                                                   support
                                                                                   contractual


                                                                                                    42
JSON                       XML                        Type                   Description
                                                                             branding
                                                                             requirements.

statusCode                 StatusCode                 integer                The HTTP
                                                                             Status code for
                                                                             the request.

statusDescription          StatusDescription          string                 A description of
                                                                             the HTTP
                                                                             status code.

authenticationResultCode   AuthenticationResultCode   One of the following   A status code
                                                      values:                that offers
                                                      ValidCredentials       additional
                                                                             information
                                                      InvalidCredentials
                                                                             about
                                                      CredentialsExpired
                                                                             authentication
                                                      NotAuthorized          success or
                                                      NoCredentials          failure.
                                                      None

traceId                    TraceId                    string                 A unique
                                                                             identifier for the
                                                                             request.

resourceSets               ResourceSets               collection             A collection of
                                                                             ResourceSet
                                                                             objects. A
                                                                             ResourceSet is
                                                                             a container of
                                                                             Resources
                                                                             returned by the
                                                                             request. For
                                                                             more
                                                                             information,
                                                                             see the
                                                                             ResourceSet
                                                                             section below.

errorDetails               ErrorDetails               string[]               A collection of
                                                                             error
                                                                             descriptions.
                                                                             For example,
                                                                             ErrorDetails


                                                                                            43
JSON                        XML                           Type                   Description
                                                                                 can identify
                                                                                 parameter
                                                                                 values that are
                                                                                 not valid or are
                                                                                 missing.


ResourceSet
The ResourceSet container provides the following information.


JSON                     XML                       Type                   Description

estimatedTotal           EstimatedTotal            long                   An estimate of the total
                                                                          number of resources in
                                                                          the ResourceSet.

resources                Resources                 collection             A collection of one or
                                                                          more DataflowJob
                                                                          resources. Information
                                                                          about the DataflowJob
                                                                          resource is found in
                                                                          the DataflowJob
                                                                          section.


DataflowJob
The DataflowJob resource container provides the following information.


JSON                       XML                        Type               Description

id                         Id                         string             A unique string that
                                                                         identifies the dataflow
                                                                         job. There are no
                                                                         requirements for the
                                                                         string format.

links                      Link                       URL                A URL that is defined
                                                                         by its role and name
                                                                         attributes.
                                                                         “role”:”self”: Use to
                                                                         check the status of your
                                                                         job.
                                                                         “role”:”output”   and

                                                                                                 44
JSON            XML             Type               Description
                                                   “name”:“succeeded”:
                                                   Use to download data
                                                   that was processed
                                                   successfully.
                                                   “role”:”output” and
                                                   “name”:“failed”: Use to
                                                   download data that was
                                                   not processed
                                                   successfully.

description     Description     string             A user-defined
                                                   description of the
                                                   dataflow job. If a
                                                   description is not
                                                   specified when the
                                                   workflow is created, this
                                                   field is not included or
                                                   the value is null.

status          Status          One of the        The status of the
                                following values: dataflow job.
                                Pending: The
                                dataflow job is
                                processing.
                                Completed:  The
                                dataflow job has
                                completed. A
                                status of
                                completed does
                                not indicate
                                success.
                                Aborted: The
                                workflow
                                stopped
                                because of an
                                error.

createdDate     CreatedDate     DateTime           The date and time that
                                                   the dataflow job was
                                                   created.

completedDate   CompletedDate   DateTime           The date and time that
                                                   the dataflow job is

                                                                         45
JSON                      XML                        Type           Description
                                                                    completed. If the Status
                                                                    field is set to Pending,
                                                                    the CompletedDate field
                                                                    is not shown or is
                                                                    empty.

totalEntityCount          TotalEntityCount           integer        The total number of
                                                                    entities that were
                                                                    uploaded.

processedEntityCount      ProcessedEntityCount       integer        The number of entities
                                                                    that were processed.
                                                                    This number included
                                                                    entities that were
                                                                    processed successfully
                                                                    and those that failed. If
                                                                    the field is set to 0, the
                                                                    number of processed
                                                                    entries is not known.

failedEntityCount         FailedEntityCount          integer        The number of entities
                                                                    that did not process
                                                                    successfully because of
                                                                    an error.

errorMessage              ErrorMessage               string         Additional error
                                                                    information that is
                                                                    provided when the
                                                                    Status is set to Aborted.



DataflowJob Response Examples
The following examples show DataflowJob resource content in JSON and XML formats.
JSON Example
{

    "authenticationResultCode":"ValidCredentials",

    "brandLogoUri":"http:\/\/spatial.virtualearth.net\/Branding\/logo_powered_by.png",

    "copyright":"© 2010 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.",

    "resourceSets":[

       {

                                                                                            46
        "estimatedTotal":1,

        "resources":[

           {



"__type":"DataflowJob:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",

               "id":"5bf10c37df944083b1879fbb0556e67e",

               "links":[

                    {

                         "role":"self",



"url":"https:\/\/spatial.virtualearth.net\/REST\/v1\/dataflows\/Geocode\/5bf10c37df944083
b1879fbb0556e67e"

                    },

                    {

                         "name":"succeeded",

                         "role":"output",



"url":"https:\/\/spatial.virtualearth.net\/REST\/v1\/dataflows\/Geocode\/5bf10c37df944083
b1879fbb0556e67e\/output\/succeeded"

                    },

                    {

                         "name":"failed",

                         "role":"output",



"url":"https:\/\/spatial.virtualearth.net\/REST\/v1\/dataflows\/Geocode\/5bf10c37df944083
b1879fbb0556e67e\/output\/failed"

                    }

               ],

               "completedDate":"Mon, 10 May 2010 20:23:49 GMT",

               "createdDate":"Mon, 10 May 2010 20:22:35 GMT",

               "description":"Xml",

               "failedEntityCount":2,

               "processedEntityCount":12,

               "status":"Completed",

               "totalEntityCount":12


                                                                                       47
                 }

             ]

         }

    ],

    "statusCode":200,

    "statusDescription":"OK",

    "traceId":"e8bfe25fdc4f4bc5824cda4e568e1c19"

}

XML Example
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">

    <Copyright>© 2010 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.</Copyright>



<BrandLogoUri>http://spatial.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>

    <StatusCode>200</StatusCode>

    <StatusDescription>OK</StatusDescription>

    <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>

    <TraceId>f65bd9af90e241b3a7d52316314eb352|BL12080319|02.00.103.1000|</TraceId>

    <ResourceSets>

     <ResourceSet>

         <EstimatedTotal>1</EstimatedTotal>

         <Resources>

             <DataflowJob>

              <Id>5bf10c37df944083b1879fbb0556e67e</Id>

              <Link role="self">https://spatial.virtualearth.net
/REST/v1/dataflows/Geocode/5bf10c37df944083b1879fbb0556e67e</Link>

              <Link role="output"
name="succeeded">https://spatial.virtualearth.net/REST/v1/dataflows/Geocode/5bf10c37df944
083b1879fbb0556e67e/output/succeeded</Link>

              <Link role="output"
name="failed">https://spatial.virtualearth.net/REST/v1/dataflows/Geocode/5bf10c37df944083
b1879fbb0556e67e/output/failed</Link>



                                                                                         48
          <Description>Xml</Description>

          <Status>Completed</Status>

          <CreatedDate>2010-05-10T13:22:35.0553408-07:00</CreatedDate>

          <CompletedDate>2010-05-10T13:23:49.1959658-07:00</CompletedDate>

          <TotalEntityCount>12</TotalEntityCount>

          <ProcessedEntityCount>12</ProcessedEntityCount>

          <FailedEntityCount>2</FailedEntityCount>

        </DataflowJob>

      </Resources>

    </ResourceSet>

  </ResourceSets>

</Response>


Geocode Dataflow Walkthrough
Use the Geocode Dataflow API to geocode large sets of spatial data by using the following steps.

Uploading Your Spatial Data
Format the data
To create a job to geocode a set of spatial data, your data must conform to the input schema as
defined in Geocode Dataflow Data Schema and be provided in XML format, or as text strings
delimited by the comma, tab, or pipe (|) character.
The following is an XML example that contains data to geocode. You can find examples in other
formats in Geocode Dataflow Sample Input and Output Data.
<GeocodeFeed xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

  <GeocodeEntity Id="0">

    <GeocodeRequest Culture="en-US">

      <Address AddressLine="1601 15th St NW # B" AdminDistrict="WA" Locality="Auburn"
CountryRegion="US" PostalCode="98001" />

    </GeocodeRequest>

  </GeocodeEntity>

  <GeocodeEntity Id="1">

    <GeocodeRequest Culture="en-US">

      <Address AddressLine="36215 55th Ave S" AdminDistrict="WA" Locality="Auburn"
CountryRegion="US" PostalCode="98001" />

    </GeocodeRequest>

  </GeocodeEntity>

                                                                                              49
  <GeocodeEntity Id="2">

    <GeocodeRequest Culture="en-US">

      <Address AddressLine="10 2nd St SW" AdminDistrict="WA" Locality="Auburn"
CountryRegion="US" PostalCode="98001" />

    </GeocodeRequest>

  </GeocodeEntity>

  <GeocodeEntity Id="3">

    <GeocodeRequest Culture="en-US">

      <Address AddressLine="35217 56th Ave S # B" AdminDistrict="WA" Locality="Auburn"
CountryRegion="US" PostalCode="98001" />

    </GeocodeRequest>

  </GeocodeEntity>

  <GeocodeEntity Id="4">

    <GeocodeRequest Culture="en-US">

      <Address AddressLine="4303 S 296th Pl" AdminDistrict="WA" Locality="Auburn"
CountryRegion="US" PostalCode="98001" />

    </GeocodeRequest>

  </GeocodeEntity>

  <GeocodeEntity Id="5">

    <GeocodeRequest Culture="en-US">

      <Address AddressLine="" AdminDistrict="" />

    </GeocodeRequest>

  </GeocodeEntity>

</GeocodeFeed>

Upload the data and create the geocode job
To geocode the data, you upload the data and create a geocode job with a URL. The URL for this
example has the following format. For more information, see Create a Geocode Job and Upload
Data.


   Both HTTP and HTTPS protocols are supported. The HTTPS protocol is recommended
   for geocode jobs that require you to secure your information.
http://spatial.virtualearth.net/REST/v1/Dataflows/Geocode?description=Geocode
Demo&input=xml&output=xml&key=YourBingMapsKey




                                                                                           50
When you make this request, the resource provided by the response is provided as a
DataflowJob. This structure of this resource includes a set of URLs defined as Link elements. You
can download the results of your job by using the URLs defined by the Link elements that have
name attributes set to succeeded and failed. However, before downloading you must first confirm
that your job has completed by checking the job status, as discussed in the next section. Notice
that the status for the resource in this example indicates that the geocode job is Pending. For
more information about the DataflowJob resource, see Geocode Dataflow Response Description.
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">

  <Copyright>Copyright © 2010 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.</Copyright>



<BrandLogoUri>http://spatial.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>

  <StatusCode>201</StatusCode>

  <StatusDescription>Created</StatusDescription>

  <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>

  <TraceId>b1aae77f9b9145ffa87d97d7d405cffd</TraceId>

  <ResourceSets>

    <ResourceSet>

      <EstimatedTotal>1</EstimatedTotal>

      <Resources>

        <DataflowJob>

          <Id>e14b1d9bd65c4b9d99d267bbb8102ccf</Id>

          <Link
role="self">https://spatial.virtualearth.net/REST/v1/dataflows/geocode/e14b1d9bd65c4b9d99
d267bbb8102ccf</Link>

          <Description>Geocode Demo</Description>

          <Status>Pending</Status>

          <CreatedDate>2010-03-09T15:15:51.8326153-08:00</CreatedDate>

          <CompletedDate xsi:nil="true" />

          <TotalEntityCount>0</TotalEntityCount>

          <ProcessedEntityCount>0</ProcessedEntityCount>


                                                                                              51
           <FailedEntityCount>0</FailedEntityCount>

        </DataflowJob>

      </Resources>

    </ResourceSet>

  </ResourceSets>

</Response>


Checking Job Status
To find out the status of a geocode job, use the URL provided in the response to the request to
create the job. The URL is specified in the Link element with the role attribute set to self. You
must specify the Bing Maps Key that you used to create the job. For more information, see Get
Status of a Geocode Job. The URL to request status of a job has the following format.
https://spatial.virtualearth.net/REST/v1/dataflows/geocode/JobID?key=YourBingMapsKey



When you make this request, you receive a response that shows the job status as a DataflowJob
resource. The DataflowJob resource in this example has a status of Completed. You can use the
URLs in the Link elements to download the data as described in the next section.
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">

  <Copyright>Copyright © 2010 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.</Copyright>



<BrandLogoUri>http://spatial.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>

  <StatusCode>200</StatusCode>

  <StatusDescription>OK</StatusDescription>

  <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>

  <TraceId>2a4fcb1fd1274497ab8ed84955012264</TraceId>

  <ResourceSets>

    <ResourceSet>

      <EstimatedTotal>1</EstimatedTotal>

      <Resources>

        <DataflowJob>



                                                                                                    52
           <Id>e14b1d9bd65c4b9d99d267bbb8102ccf</Id>

           <Link
role="self">https://spatial.virtualearth.net/REST/v1/dataflows/geocode/e14b1d9bd65c4b9d99
d267bbb8102ccf</Link>

           <Link role="output"
name="succeeded">https://spatial.virtualearth.net/REST/v1/dataflows/geocode/e14b1d9bd65c4
b9d99d267bbb8102ccf/output/succeeded</Link>

           <Description>Geocode Job 1</Description>

           <Status>Completed</Status>

           <CreatedDate>2010-03-08T16:35:00.2429749-08:00</CreatedDate>

           <CompletedDate>2010-03-08T16:44:00.9349209-08:00</CompletedDate>

           <TotalEntityCount>6</TotalEntityCount>

           <ProcessedEntityCount>6</ProcessedEntityCount>

           <FailedEntityCount>0</FailedEntityCount>

        </DataflowJob>

      </Resources>

    </ResourceSet>

  </ResourceSets>

</Response>

If your job status is Aborted, then the job ended due to an error and an ErrorMessage element
appears in the response and contains error information.

Downloading Results
When the status of your job is set to Completed, you can download the results of the geocode job.
The results are available for download for fourteen (14) calendar days. The URLs to download
data that was geocoded successfully and to download data that was not geocoded successfully
are provided in the DataflowJob resource provided for the job. The URLs are identified by their
name attribute that are set to succeeded and failed. A succeeded or failed Link URL only appears
in the response if there is corresponding data to download. If all the data was geocoded
successfully, a failed Link URL does not appear. To download data with these URLs, you must
add the key parameter and set it to the Bing Maps Key that you used to create the job
The following URL examples show the format for downloading data and include the Bing Maps
Key parameter. The results of geocoding the input in this walkthrough are also provided. Note
that the downloaded results are provided in the same format as the input values. To view
examples in other data formats, see Geocode Dataflow Sample Input and Output Data.
URL (name=succeeded)
https://spatial.virtualearth.net/REST/v1/dataflows/geocode/JobID/output/succeeded?key=Bin
gMapsKey


                                                                                                53
Results
<GeocodeFeed xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode" >

 <GeocodeEntity Id="0" xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <GeocodeRequest Culture="en-US">

     <Address AddressLine="1601 15th St NW # B" AdminDistrict="WA" CountryRegion="US"
Locality="Auburn" PostalCode="98001" />

   </GeocodeRequest>

   <GeocodeResponse DisplayName="1601 15th St NW, Auburn, WA 98001-3501"
EntityType="Address" Confidence="High" StatusCode="Success">

     <Address AddressLine="1601 15th St NW" AdminDistrict="WA" CountryRegion="United
States" FormattedAddress="1601 15th St NW, Auburn, WA 98001-3501" Locality="Auburn"
PostalCode="98001-3501" />

     <RooftopLocation Longitude="-122.254631" Latitude="47.323132" />

     <InterpolatedLocation Longitude="-122.254631" Latitude="47.322481" />

   </GeocodeResponse>

 </GeocodeEntity>

 <GeocodeEntity Id="1" xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <GeocodeRequest Culture="en-US">

     <Address AddressLine="36215 55th Ave S" AdminDistrict="WA" CountryRegion="US"
Locality="Auburn" PostalCode="98001" />

   </GeocodeRequest>

   <GeocodeResponse DisplayName="36215 55th Ave S, Auburn, WA 98001-9383"
EntityType="Address" Confidence="High" StatusCode="Success">

     <Address AddressLine="36215 55th Ave S" AdminDistrict="WA" CountryRegion="United
States" FormattedAddress="36215 55th Ave S, Auburn, WA 98001-9383" Locality="Auburn"
PostalCode="98001-9383" />

     <RooftopLocation Longitude="-122.267006" Latitude="47.276497" />

     <InterpolatedLocation Longitude="-122.266451" Latitude="47.276141" />

   </GeocodeResponse>

 </GeocodeEntity>

 <GeocodeEntity Id="2" xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <GeocodeRequest Culture="en-US">

     <Address AddressLine="10 2nd St SW" AdminDistrict="WA" CountryRegion="US"
Locality="Auburn" PostalCode="98001" />

   </GeocodeRequest>


                                                                                        54
   <GeocodeResponse DisplayName="10 2nd St SW, Auburn, WA 98001-5270"
EntityType="Address" Confidence="High" StatusCode="Success">

     <Address AddressLine="10 2nd St SW" AdminDistrict="WA" CountryRegion="United
States" FormattedAddress="10 2nd St SW, Auburn, WA 98001-5270" Locality="Auburn"
PostalCode="98001-5270" />

     <InterpolatedLocation Longitude="-122.230068" Latitude="47.30564" />

   </GeocodeResponse>

 </GeocodeEntity>

 <GeocodeEntity Id="3" xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <GeocodeRequest Culture="en-US">

     <Address AddressLine="35217 56th Ave S # B" AdminDistrict="WA" CountryRegion="US"
Locality="Auburn" PostalCode="98001" />

   </GeocodeRequest>

   <GeocodeResponse DisplayName="35217 56th Ave S, Auburn, WA 98001-9204"
EntityType="Address" Confidence="High" StatusCode="Success">

     <Address AddressLine="35217 56th Ave S" AdminDistrict="WA" CountryRegion="United
States" FormattedAddress="35217 56th Ave S, Auburn, WA 98001-9204" Locality="Auburn"
PostalCode="98001-9204" />

     <RooftopLocation Longitude="-122.265434" Latitude="47.285744" />

     <InterpolatedLocation Longitude="-122.264971" Latitude="47.285741" />

   </GeocodeResponse>

 </GeocodeEntity>

 <GeocodeEntity Id="4" xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <GeocodeRequest Culture="en-US">

     <Address AddressLine="4303 S 296th Pl" AdminDistrict="WA" CountryRegion="US"
Locality="Auburn" PostalCode="98001" />

   </GeocodeRequest>

   <GeocodeResponse DisplayName="4303 S 296th Pl, Auburn, WA 98001-1566"
EntityType="Address" Confidence="High" StatusCode="Success">

     <Address AddressLine="4303 S 296th Pl" AdminDistrict="WA" CountryRegion="United
States" FormattedAddress="4303 S 296th Pl, Auburn, WA 98001-1566" Locality="Auburn"
PostalCode="98001-1566" />

     <RooftopLocation Longitude="-122.279762" Latitude="47.336163" />

     <InterpolatedLocation Longitude="-122.279762" Latitude="47.33637" />

   </GeocodeResponse>

 </GeocodeEntity>

                                                                                         55
</GeocodeFeed>




URL (name=failed)
https://spatial.virtualearth.net/REST/v1/dataflows/geocode/JobID/output/failed?key=BingMa
psKey

Results
<GeocodeFeed xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode" >

     <GeocodeEntity Id="5" xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

      <GeocodeRequest Culture="en-US">

        <Address AddressLine="" AdminDistrict="" />

      </GeocodeRequest>

      <GeocodeResponse StatusCode="BadRequest" FaultReason="Parameter name: Address" />

     </GeocodeEntity>

</GeocodeFeed>


Geocode Dataflow Sample Code
The following sample code uses the Geocode Dataflow to geocode spatial data.
Notes:
    The code uses the functionality included in Microsoft® .NET 2.0 and is written as a console
      application.
    The code accepts input data in any of the formats supported by the Geocode Dataflow.
      Examples of supported data formats are XML and CSV(comma-separated values). See
      Create a Geocode Job and Upload Data for more information about supported data formats.
    The code processes HTTP requests returned in XML format.
    The results of the geocode job are output to files named succeeded.txt and failed.txt.
using System;

using System.IO;

using System.Net;

using System.Text;

using System.Threading;

using System.Xml;




//This C# code sample shows how to geocode data using the Geocode Dataflow REST API.

//For more information on this API, see the Bing Spatial Data Services SDK on MSDN:

                                                                                                    56
// http://msdn.microsoft.com/en-us/library/ff701734.aspx

namespace GeocodeDataFlowExample

{

    //A summary of status information returned in the response when you check

    // job status.

    class DownloadDetails

    {

        public string jobStatus { get; set; }

        public string suceededlink { get; set; }

        public string failedlink { get; set; }



    }



    class Program

    {

        //Creates a geocode dataflow job and uploads spatial data to process.

        //Parameters:

        //     dataFilePath: The path to the file that contains the spatial data to
geocode.

        //     dataFormat: The format of the input data. Possible values are xml, csv, tab
and pipe.

        //     key: The Bing Maps Key to use for this job. The same key is used to get job
status and download results.

        //     description: Text that is used to describe the geocode dataflow job.

        //Return value : A URL that defines the location of the geocode dataflow job that
was created.

        static string CreateJob(string dataFilePath, string dataFormat, string key,
string description)

        {

             //Define parameters for the HTTP request

             //

             // The 'Content-Type' header of the HTTP Request must be "text/plain" or
"application/xml"

             // depending on the input data format.

             //

                                                                                         57
            string contentType = "text/plain";

            if (dataFormat.Equals("xml", StringComparison.OrdinalIgnoreCase))

                 contentType = "application/xml";



            StringBuilder queryStringBuilder = new StringBuilder();



            //

            // The 'input'(input format) and 'key' (Bing Maps Key) parameters are
required.

            //

            queryStringBuilder.Append("input=").Append(Uri.EscapeUriString(dataFormat));

            queryStringBuilder.Append("&");

            queryStringBuilder.Append("key=").Append(Uri.EscapeUriString(key));



            if (!String.IsNullOrEmpty(description))

            {

                 //

                 // The 'description' parameter is optional.

                 //

                 queryStringBuilder.Append("&");



queryStringBuilder.Append("description=").Append(Uri.EscapeUriString(description));

            }



            //Build the HTTP URI that will upload and create the geocode dataflow job

            UriBuilder uriBuilder = new UriBuilder("http://spatial.virtualearth.net");

            uriBuilder.Path = "/REST/v1/dataflows/geocode";

            uriBuilder.Query = queryStringBuilder.ToString();



            //Include the data to geocode in the HTTP request

            using (FileStream dataStream = File.OpenRead(dataFilePath))

            {

                 HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(uriBuilder.Uri);


                                                                                         58
               //

               // The HTTP method must be 'POST'.

               //

               request.Method = "POST";

               request.ContentType = contentType;



               using (Stream requestStream = request.GetRequestStream())

               {

                    byte[] buffer = new byte[16384];

                    int bytesRead = dataStream.Read(buffer, 0, buffer.Length);

                    while (bytesRead > 0)

                    {

                         requestStream.Write(buffer, 0, bytesRead);



                         bytesRead = dataStream.Read(buffer, 0, buffer.Length);

                    }

               }



               //Submit the HTTP request and check if the job was created successfully.

               using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())

               {

                    //

                    // If the job was created successfully, the status code should be

                    // 201 (Created) and the 'Location' header should contain a URL

                    // that defines the location of the new dataflow job. You use this

                    // URL with the Bing Maps Key to query the status of your job.

                    //

                    if (response.StatusCode != HttpStatusCode.Created)

                         throw new Exception ("An HTTP error status code was encountered
when creating the geocode job.");



                    string dataflowJobLocation = response.GetResponseHeader("Location");

                    if (String.IsNullOrEmpty(dataflowJobLocation))


                                                                                           59
                          throw new Exception ("The 'Location' header is missing from the
HTTP response when creating a goecode job.");



                      return dataflowJobLocation;

                  }

            }

       }




       //Checks the status of a dataflow job and defines the URLs to use to download
results when the job is completed.

       //Parameters:

       //   dataflowJobLocation: The URL to use to check status for a job.

       //   key: The Bing Maps Key for this job. The same key is used to create the job
and download results.

       //Return value: A DownloadDetails object that contains the status of the geocode
dataflow job (Completed, Pending, Aborted).

       //                When the status is set to Completed, DownloadDetails also
contains the links to download the results

       static DownloadDetails CheckStatus(string dataflowJobLocation, string key)

       {



            DownloadDetails statusDetails = new DownloadDetails();

            statusDetails.jobStatus = "Pending";



            //Build the HTTP Request to get job status

            UriBuilder uriBuilder = new UriBuilder(dataflowJobLocation + @"?key=" + key +
"&output=xml");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriBuilder.Uri);



            request.Method = "GET";



            //Submit the request and read the response to get job status and to retrieve
the links for

            //    downloading the job results


                                                                                            60
           //Note: The following conditional statements make use of the fact that the
'Status' field will

           //   always appear after the 'Link' fields in the HTTP response.

           using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())

           {



                if (response.StatusCode != HttpStatusCode.OK)

                      throw new Exception ("An HTTP error status code was encountered when
checking job status.");



                using (Stream receiveStream = response.GetResponseStream())

                {

                      XmlTextReader reader = new XmlTextReader(receiveStream);

                      while (reader.Read())

                      {

                          if (reader.IsStartElement())

                          {

                              if (reader.Name.Equals("Status"))

                              {

                                  //return job status

                                  statusDetails.jobStatus = reader.ReadString();



                                  return (statusDetails);

                              }

                              else if (reader.Name.Equals("Link"))

                              {

                                  //Set the URL location values for retrieving

                                  // successful and failed job results

                                  reader.MoveToFirstAttribute();

                                  if (reader.Value.Equals("output"))

                                  {

                                      reader.MoveToNextAttribute();

                                      if (reader.Value.Equals("succeeded"))

                                      {


                                                                                         61
                                            statusDetails.suceededlink = reader.ReadString();



                                        }

                                        else if (reader.Value.Equals("failed"))

                                        {

                                            statusDetails.failedlink = reader.ReadString();

                                        }

                                  }

                              }

                          }

                      }



                  }



              }

              return (statusDetails);

       }



       //Downloads job results to files names Success.txt (successfully geocoded
results) and

       //      Failed.txt (info about spatial data that was not geocoded successfully).

        //Parameters:

       //      statusDetails: Inclues job status and the URLs to use to download all
geocoded results.

       //      key: The Bing Maps Key for this job. The same key is used to create the job
and get job status.



       static void DownloadResults(DownloadDetails statusDetails, string key)

       {

              //Write the results for data that was geocoded successfully to a file named
Success.xml

              if (statusDetails.suceededlink != null &&
!statusDetails.suceededlink.Equals(String.Empty))

              {



                                                                                              62
               //Create a request to download successfully geocoded data. You must add
the Bing Maps Key to the

               //    download location URL provided in the response to the job status
request.

               UriBuilder successUriBuilder = new UriBuilder(statusDetails.suceededlink
+ @"?key=" + key);

               HttpWebRequest request1 =
(HttpWebRequest)WebRequest.Create(successUriBuilder.Uri);



               request1.Method = "GET";



               using (HttpWebResponse response =
(HttpWebResponse)request1.GetResponse())

               {

                     if (response.StatusCode != HttpStatusCode.OK)

                           throw new Exception ("An HTTP error status code was encountered
when downloading results.");



                     using (Stream receiveStream = response.GetResponseStream())

                     {

                           StreamWriter successfile = new StreamWriter("Success.txt");

                           using (StreamReader r = new StreamReader(receiveStream))

                           {

                               string line;

                               while ((line = r.ReadLine()) != null)

                               {

                                   successfile.Write(line);

                               }

                           }

                           successfile.Close();

                     }



               }

           }



                                                                                             63
           //If some spatial data could not be geocoded, write the error information to
a file called Failed.xml

           if (statusDetails.failedlink != null &&
!statusDetails.failedlink.Equals(String.Empty))

           {

               //Create an HTTP request to download error information. You must add the
Bing Maps Key to the

               //   download location URL provided in the response to the job status
request.

               UriBuilder failedUriBuilder = new UriBuilder(statusDetails.failedlink +
@"?key=" + key);

               HttpWebRequest request2 =
(HttpWebRequest)WebRequest.Create(failedUriBuilder.Uri);



               request2.Method = "GET";



               using (HttpWebResponse response =
(HttpWebResponse)request2.GetResponse())

               {

                    if (response.StatusCode != HttpStatusCode.OK)

                           throw new Exception ("An HTTP error status code was encountered
when downloading results.");



                    using (Stream receiveStream = response.GetResponseStream())

                    {

                           StreamWriter failedfile = new StreamWriter("Failed.txt");

                           using (StreamReader r = new StreamReader(receiveStream))

                           {

                               string line;

                               while ((line = r.ReadLine()) != null)

                               {

                                   failedfile.Write(line);

                               }

                           }

                           failedfile.Close();


                                                                                             64
               }



           }

     }

}




//

// Sample command-line:

// GeocodeDataFlowExample.exe <dataFilePath> <dataFormat> <key> [<description>]

//

// Where:

// <dataFilePath> is a path to the data file containing entities to geocode.

// <dataFormat> is one of these types: xml, csv, tab, pipe.

// <key> is a Bing Maps Key from http://www.bingmapsportal.com.

// <description> is an optional description for the dataflow job.

//




static void Main(string[] args)

{

     string dataFilePath = args[0];

     string dataFormat = args[1];

     string key = args[2];

     string description = null;



     try

     {



           if (args.Length > 3)

               description = args[3];




                                                                                  65
                string dataflowJobLocation = CreateJob(dataFilePath, dataFormat, key,
description);

                Console.WriteLine("Dataflow Job Location: {0}", dataflowJobLocation);



                //Continue to check the dataflow job status until the job has completed

                DownloadDetails statusDetails = new DownloadDetails();

                do

                {

                     statusDetails = CheckStatus(dataflowJobLocation, key);

                     Console.WriteLine("Dataflow Job Status: {0}",
statusDetails.jobStatus);

                     if (statusDetails.jobStatus== "Aborted")

                         throw new Exception("Job was aborted due to an error.");

                     Thread.Sleep(30000); //Get status every 30 seconds

                }

                while (statusDetails.jobStatus.Equals("Pending"));



                //When the job is completed, get the results

                //Two files are created to record the results:

                //   Success.xml contains the data that was successfully geocoded

                //   Failed.mxl contains the data that could not be geocoded



                DownloadResults(statusDetails, key);



            }



            catch (Exception   e)

            {

                Console.WriteLine("Exception :" + e.Message);

            }

        }

    }

}




                                                                                          66
Geocode Dataflow Data Schema
The Geocode Dataflow API supports the following formats for uploading and downloading spatial
data:
   Text files with values separated by comma, tab, or pipe (|) characters.
   XML
This topic describes the spatial data schema for the Geocode Dataflow API. Text file and the XML
schema definitions are provided along with descriptions of the fields. For examples of input and
output spatial data in all formats, see Geocode Dataflow Sample Input and Output Data.

Text File Schema
The following text file schema shows how the input and output values for the Geocode Dataflow
are organized in a text file. Note that there are GeocodeRequest, GeocodeResponse, and
ReverseGeocodeRequest values. The Geocode Request fields define location information to
geocode. The ReverseGeocodeRequest fields provide latitude and longitude information to
reverse geocode. The GeocodeReponse fields are populated with the processed output data.
Each item of data must provide information or a blank entry for each of these fields. Descriptions
of the fields are provided in the Data Schema Definitions section below.
GeocodeEntity/@Id

GeocodeEntity/GeocodeRequest/@Culture

GeocodeEntity/GeocodeRequest/@Query

GeocodeEntity/GeocodeRequest/Address/@AddressLine

GeocodeEntity/GeocodeRequest/Address/@AdminDistrict

GeocodeEntity/GeocodeRequest/Address/@CountryRegion

GeocodeEntity/GeocodeRequest/Address/@District

GeocodeEntity/GeocodeRequest/Address/@FormattedAddress

GeocodeEntity/GeocodeRequest/Address/@Locality

GeocodeEntity/GeocodeRequest/Address/@PostalCode

GeocodeEntity/GeocodeRequest/Address/@PostalTown

GeocodeEntity/GeocodeRequest/ConfidenceFilter/@MinimumConfidence

GeocodeEntity/GeocodeResponse/Address/@AddressLine

GeocodeEntity/GeocodeResponse/Address/@AdminDistrict

GeocodeEntity/GeocodeResponse/Address/@CountryRegion

GeocodeEntity/GeocodeResponse/Address/@District

GeocodeEntity/GeocodeResponse/Address/@FormattedAddress

GeocodeEntity/GeocodeResponse/Address/@Locality


                                                                                                67
GeocodeEntity/GeocodeResponse/Address/@PostalCode

GeocodeEntity/GeocodeResponse/Address/@PostalTown

GeocodeEntity/GeocodeResponse/RooftopLocation/@Latitude

GeocodeEntity/GeocodeResponse/RooftopLocation/@Longitude

GeocodeEntity/GeocodeResponse/InterpolatedLocation/@Latitude

GeocodeEntity/GeocodeResponse/InterpolatedLocation/@Longitude

GeocodeEntity/GeocodeResponse/@Confidence

GeocodeEntity/GeocodeResponse/@DisplayName

GeocodeEntity/GeocodeResponse/@EntityType

GeocodeEntity/GeocodeResponse/@StatusCode

GeocodeEntity/GeocodeResponse/@FaultReason

GeocodeEntity/ReverseGeocodeRequest/Location/@Latitude

GeocodeEntity/ReverseGeocodeRequest/Location/@Longitude

The following two input values show an address to geocode and a latitude and longitude pair to
reverse geocode. Note that both examples contain a value or blank space for each element in the
text file schema.
1,en-US,,16630 Redmond Way,WA,Redmond,98052,,,,,,,,,,,,,,,,,,,,,,,,

2,en-gb,,,,,,,,,,,,,,,,,,,,,,,,,,,,53.77848387,-1.719561517


XML Schema
The following schema is the XML schema for spatial data. Descriptions of the fields are provided
in the Data Schema Definitions section below.
<?xml version="1.0" standalone="yes"?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://schemas.microsoft.com/search/local/2010/5/geocode"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">



  <xs:complexType name="Address">

    <xs:attribute name="AddressLine" type="xs:string"/>

    <xs:attribute name="AdminDistrict" type="xs:string" />

    <xs:attribute name="CountryRegion" type="xs:string" />

    <xs:attribute name="District" type="xs:string" />

    <xs:attribute name="FormattedAddress" type="xs:string" />

    <xs:attribute name="Locality" type="xs:string" />

    <xs:attribute name="PostalCode" type="xs:string" />

    <xs:attribute name="PostalTown" type="xs:string" />

                                                                                               68
 </xs:complexType>

 <xs:element name="Address" type="Address" />



 <xs:complexType name="Location">

   <xs:attribute name="Latitude" type="xs:double" />

   <xs:attribute name="Longitude" type="xs:double" />

 </xs:complexType>

 <xs:element name="Location" type="Location" />

 <xs:element name="RooftopLocation" type="Location" />

 <xs:element name="InterpolatedLocation" type="Location" />



 <xs:complexType name="BaseGeoRequest" abstract="true" >

   <xs:sequence />

   <xs:attribute name="Culture" type="xs:string" />

 </xs:complexType>

 <xs:element name="BaseGeoRequest" type="BaseGeoRequest" abstract="true" />



 <xs:complexType name="GeocodeRequest">

   <xs:complexContent>

     <xs:extension base="BaseGeoRequest">

       <xs:sequence>

         <xs:element ref="Address" minOccurs="0" maxOccurs="1" />

         <xs:element name="ConfidenceFilter" minOccurs="0" maxOccurs="1">

           <xs:complexType>

             <xs:attribute name="MinimumConfidence" type="xs:string" />

           </xs:complexType>

         </xs:element>

       </xs:sequence>

       <xs:attribute name="Query" type="xs:string" />

     </xs:extension>

   </xs:complexContent>

 </xs:complexType>

 <xs:element name="GeocodeRequest" type="GeocodeRequest"
substitutionGroup="BaseGeoRequest" />


                                                                              69
 <xs:complexType name="ReverseGeocodeRequest">

   <xs:complexContent>

     <xs:extension base="BaseGeoRequest">

       <xs:sequence>

         <xs:element ref="Location" />

       </xs:sequence>

     </xs:extension>

   </xs:complexContent>

 </xs:complexType>

 <xs:element name="ReverseGeocodeRequest" type="ReverseGeocodeRequest"
substitutionGroup="BaseGeoRequest" />



 <xs:complexType name="GeocodeResponse">

   <xs:sequence>

     <xs:element ref="Address" minOccurs="0" maxOccurs="1" />

     <xs:element ref="RooftopLocation" minOccurs="0" maxOccurs="1" />

     <xs:element ref="InterpolatedLocation" minOccurs="0" maxOccurs="1" />

   </xs:sequence>

   <xs:attribute name="DisplayName" type="xs:string" />

   <xs:attribute name="EntityType" type="xs:string" />

   <xs:attribute name="Confidence" type="xs:string" />

   <xs:attribute name="StatusCode" type="xs:string" />

   <xs:attribute name="FaultReason" type="xs:string" />

 </xs:complexType>

 <xs:element name="GeocodeResponse" type="GeocodeResponse" />



 <xs:complexType name="GeocodeEntity">

   <xs:sequence>

     <xs:element ref="BaseGeoRequest" minOccurs="0" maxOccurs="1" />

     <xs:element ref="GeocodeResponse" minOccurs="0" maxOccurs="1" />

   </xs:sequence>

   <xs:attribute name="Id" type="xs:string" />

 </xs:complexType>


                                                                             70
     <xs:element name="GeocodeEntity" type="GeocodeEntity" />



     <xs:complexType name="GeocodeFeed">

      <xs:sequence>

        <xs:element ref="GeocodeEntity" maxOccurs="unbounded" />

      </xs:sequence>

     </xs:complexType>

     <xs:element name="GeocodeFeed" type="GeocodeFeed" />

</xs:schema>

The following two input values show a location to geocode and a latitude and longitude pair to
reverse geocode.
<GeocodeFeed>

     <GeocodeEntity Id="001"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

      <GeocodeRequest Culture="en-US">

        <Address AddressLine="16630 Redmond Way" AdminDistrict="WA" Locality="Redmond"
PostalCode="98052" />

      </GeocodeRequest>

     </GeocodeEntity>

     <GeocodeEntity Id="012"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

      <ReverseGeocodeRequest Culture="en-gb">

        <Location Longitude="-1.71956151723862" Latitude="53.7784838676453"/>

      </ReverseGeocodeRequest>

     </GeocodeEntity>

</GeocodeFeed>




Data Schema Definitions
The following table provides descriptions of the fields in the spatial data schema. Field values are
not case-sensitive.


Field                                      Operation              Values

Id                                         Geocode Request         A string that contains the ID of a
                                                                  spatial data input value.
                                                                  Example: 1

                                                                                                  71
Field                      Operation          Values

Culture                    Geocode Request    A string specifying the culture.
                                              Example: en-us [default]

Query                      Geocode Request    A query string that contains
                                              address information to geocode.
                                              Example: 1600 Pennsylvania
                                              Ave NW Washington DC

Address.AddressLine        Geocode Request    A string specifying the street line
                           Geocode Response   of an address. The AddressLine
                                              property is the most precise,
                                              official line for an address
                                              relative to the postal agency that
                                              services the area specified by
                                              the Locality, PostalTown, or
                                              PostalCode properties.
                                              Example: 1 Microsoft Way

Address.AdminDistrict      Geocode Request    A string specifying the
                           Geocode Response   subdivision name within the
                                              country or region for an address.
                                              This element is also commonly
                                              treated as the first order
                                              administrative subdivision; but in
                                              some cases, it is the second,
                                              third, or fourth order subdivision
                                              within a country, a dependency,
                                              or a region.
                                              Example: WA

Address.CountryRegion      Geocode Request    A string specifying the country or
                           Geocode Response   region name of an address.
                                              Example: US

Address.District           Geocode Request    A string specifying the higher
                                              level administrative subdivision
                                              used in some countries or
                                              regions.

Address.FormattedAddress   Geocode Response   A string that contains a full
                                              formatted address
                                              Note: Do not use this field as a
                                              geocode request value. This

                                                                                 72
Field                                Operation          Values
                                                        field is used in the response.

Address.Locality                     Geocode Request    A string specifying the populated
                                     Geocode Response   place for the address. This
                                                        commonly refers to a city, but
                                                        may refer to a suburb or a
                                                        neighborhood in certain
                                                        countries.
                                                        Example: Seattle

Address.PostalCode                   Geocode Request    A string specifying the post
                                     Geocode Response   code, postal code, or ZIP Code
                                                        of an address.
                                                        Example: 98178

Address.PostalTown                   Geocode Request    A string specifying the postal city
                                                        of an address.

ConfidenceFilter.MinimumConfidence   Geocode Request    A string specifying the minimum
                                                        confidence required for the
                                                        result.
                                                        The following are possible
                                                        confidence values:
                                                           Low
                                                           Medium
                                                           High
                                                        Example: High

Location.Latitude                    Reverse Geocode    A set of double values
Location.Longitude                   Request            representing degrees of latitude
                                                        and longitude.
                                                        Valid range of latitude values: [-
                                                        90, +90]
                                                        Example: 47.673099
                                                        Valid range of longitude values:
                                                        [-180, +180]
                                                        Example: -122.11871

RooftopLocation.Latitude             Geocode Response   A pair of double values
RooftopLocation.Longitude                               representing degrees of latitude
                                                        and longitude that are
                                                        associated with an address.


                                                                                         73
Field                            Operation          Values

InterpolatedLocation.Latitude    Geocode Response   A pair of double values
InterpolatedLocation.Longitude                      representing degrees of latitude
                                                    and longitude that are the result
                                                    of interpolating between two
                                                    points.

Confidence                       Geocode Response   A string specifying the
                                                    confidence of the result.
                                                    The following are possible
                                                    confidence values:
                                                       Low
                                                       Medium
                                                       High

DisplayName                      Geocode Response   A string specifying the display
                                                    name for the response.
                                                    Example: 16552 NE 74th St,
                                                    Redmond, WA 98052-7804

EntityType                       Geocode Response   A string specifying the entity
                                                    type of the location.
                                                    For a list of entity types, see
                                                    Entity Types.
                                                    Examples:
                                                    Address
                                                    RoadBlock

StatusCode                       Geocode Response   A string that provides
                                                    information about the success of
                                                    the operation.
                                                    Examples:
                                                    Success
                                                    BadRequest

FaultReason                      Geocode Response   Information about an error that
                                                    occurred during the geocode
                                                    dataflow job. This value is
                                                    provided only for data that was
                                                    not processed successfully.
                                                    Example: The
                                                    Address.FormattedAddress


                                                                                      74
Field                                     Operation            Values
                                                               property must not be specified
                                                               because it is an output-only
                                                               property.



Geocode Dataflow Sample Input and Output Data
The following examples show sample input and output data for the Geocode Dataflow. The input
data can be provided in an XML format or as sets of values separated by pipe (|), comma, or tab
characters. The output data is provided in the same format as the input data. The data in these
examples contains location data to geocode and latitude and longitude pairs to reverse geocode.
For information about the data schema, see Geocode Dataflow Data Schema.
The input data must use UTF-8 encoding.

XML Example


Input
<GeocodeFeed>

  <GeocodeEntity Id="001"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

    <GeocodeRequest Culture="en-US">

        <Address AddressLine="16630 Redmond Way" AdminDistrict="WA" Locality="Redmond"
PostalCode="98052" />

    </GeocodeRequest>

  </GeocodeEntity>

  <GeocodeEntity Id="002"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

    <GeocodeRequest Culture="en-US">

        <Address AddressLine="16552 NE 74th St" AdminDistrict="WA" Locality="Redmond" />

        <ConfidenceFilter MinimumConfidence="High" xmlns="" />

    </GeocodeRequest>

  </GeocodeEntity>

  <GeocodeEntity Id="003"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

    <GeocodeRequest Culture="en-US" Query="Seattle Space Needle">

    </GeocodeRequest>

  </GeocodeEntity>


                                                                                                75
 <GeocodeEntity Id="004"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <GeocodeRequest Culture="en-US" Query="">

     <Address AddressLine="" AdminDistrict="" />

   </GeocodeRequest>

 </GeocodeEntity>

 <GeocodeEntity Id="005"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <GeocodeRequest Culture="en-US">

     <Address AddressLine="W Jefferson Blvd" AdminDistrict="CA" Locality="Los Angeles"
PostalCode="90007" />

   </GeocodeRequest>

 </GeocodeEntity>

 <GeocodeEntity Id="006"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <GeocodeRequest Culture="en-US">

     <Address AdminDistrict="CA" Locality="Los angeles" PostalCode="" />

   </GeocodeRequest>

 </GeocodeEntity>

 <GeocodeEntity Id="007"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <GeocodeRequest Culture="en-ca" Query="Montreal,Canada">

   </GeocodeRequest>

 </GeocodeEntity>

 <GeocodeEntity Id="008"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <GeocodeRequest Culture="en-CA">

     <Address AddressLine="444 Kirkpatrick Cres NW" AdminDistrict="AB"
Locality="Edmonton" PostalCode="" CountryRegion="Canada" />

   </GeocodeRequest>

 </GeocodeEntity>

 <GeocodeEntity Id="009"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <GeocodeRequest Culture="en-gb" Query="BD4 9JB">

   </GeocodeRequest>


                                                                                         76
  </GeocodeEntity>

  <GeocodeEntity Id="010"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

    <ReverseGeocodeRequest Culture="en-US">

      <Location Longitude="-122.11871" Latitude="47.673099"/>

    </ReverseGeocodeRequest>

  </GeocodeEntity>

  <GeocodeEntity Id="011"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

    <ReverseGeocodeRequest Culture="en-ca">

      <Location Longitude="-113.403092450204" Latitude="53.4802172766598"/>

    </ReverseGeocodeRequest>

  </GeocodeEntity>

  <GeocodeEntity Id="012"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

    <ReverseGeocodeRequest Culture="en-gb">

      <Location Longitude="-1.71956151723862" Latitude="53.7784838676453"/>

    </ReverseGeocodeRequest>

  </GeocodeEntity>

</GeocodeFeed>



Successful Output
The following is an example list of locations that were geocoded successfully.
<GeocodeFeed >

  <GeocodeEntity Id="001"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

    <GeocodeRequest Culture="en-US">

      <Address AddressLine="16630 Redmond Way" AdminDistrict="WA" Locality="Redmond"
PostalCode="98052" />

    </GeocodeRequest>

    <GeocodeResponse DisplayName="16630 Redmond Way, Redmond, WA 98052-4434"
EntityType="Address" Confidence="High" StatusCode="Success">

      <Address AddressLine="16630 Redmond Way" AdminDistrict="WA" CountryRegion="United
States" FormattedAddress="16630 Redmond Way, Redmond, WA 98052-4434" Locality="Redmond"
PostalCode="98052-4434" />


                                                                                          77
     <RooftopLocation Latitude="47.673302" Longitude="-122.118576" />

     <InterpolatedLocation Latitude="47.673099" Longitude="-122.11871" />

   </GeocodeResponse>

 </GeocodeEntity>

 <GeocodeEntity Id="002"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <GeocodeRequest Culture="en-US">

     <Address AddressLine="16552 NE 74th St" AdminDistrict="WA" Locality="Redmond" />

     <ConfidenceFilter MinimumConfidence="High" />

   </GeocodeRequest>

   <GeocodeResponse DisplayName="16552 NE 74th St, Redmond, WA 98052-7804"
EntityType="Address" Confidence="High" StatusCode="Success">

     <Address AddressLine="16552 NE 74th St" AdminDistrict="WA" CountryRegion="United
States" FormattedAddress="16552 NE 74th St, Redmond, WA 98052-7804" Locality="Redmond"
PostalCode="98052-7804" />

     <InterpolatedLocation Latitude="47.670211" Longitude="-122.119581" />

   </GeocodeResponse>

 </GeocodeEntity>

 <GeocodeEntity Id="003"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <GeocodeRequest Culture="en-US" Query="Seattle Space Needle" />

   <GeocodeResponse DisplayName="Space Needle, WA" EntityType="LandmarkBuilding"
Confidence="High" StatusCode="Success">

     <Address AdminDistrict="Washington" CountryRegion="United States"
FormattedAddress="Space Needle, WA" Locality="Seattle" />

     <RooftopLocation Latitude="47.620495" Longitude="-122.34931" />

   </GeocodeResponse>

 </GeocodeEntity>

 <GeocodeEntity Id="005"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <GeocodeRequest Culture="en-US">

     <Address AddressLine="W Jefferson Blvd" AdminDistrict="CA" Locality="Los Angeles"
PostalCode="90007" />

   </GeocodeRequest>




                                                                                         78
   <GeocodeResponse DisplayName="W Jefferson Blvd, Los Angeles, CA 90007"
EntityType="RoadBlock" Confidence="High" StatusCode="Success">

     <Address AddressLine="W Jefferson Blvd" AdminDistrict="CA" CountryRegion="United
States" FormattedAddress="W Jefferson Blvd, Los Angeles, CA 90007" Locality="Los Angeles"
PostalCode="90007" />

     <InterpolatedLocation Latitude="34.0236140484618" Longitude="-118.28398661223" />

   </GeocodeResponse>

 </GeocodeEntity>

 <GeocodeEntity Id="006"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <GeocodeRequest Culture="en-US">

     <Address AdminDistrict="CA" Locality="Los angeles" PostalCode="" />

   </GeocodeRequest>

   <GeocodeResponse DisplayName="Los Angeles, CA" EntityType="PopulatedPlace"
Confidence="High" StatusCode="Success">

     <Address AdminDistrict="California" CountryRegion="United States"
FormattedAddress="Los Angeles, CA" Locality="Los Angeles" />

     <RooftopLocation Latitude="34.0532901138067" Longitude="-118.245009407401" />

   </GeocodeResponse>

 </GeocodeEntity>

 <GeocodeEntity Id="007"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <GeocodeRequest Culture="en-ca" Query="Montreal,Canada" />

   <GeocodeResponse DisplayName="Montreal, QC" EntityType="PopulatedPlace"
Confidence="High" StatusCode="Success">

     <Address AdminDistrict="Quebec" CountryRegion="Canada" FormattedAddress="Montreal,
QC" Locality="Montreal" />

     <RooftopLocation Latitude="45.5122858285904" Longitude="-73.5543867945671" />

   </GeocodeResponse>

 </GeocodeEntity>

 <GeocodeEntity Id="008"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <GeocodeRequest Culture="en-CA">

     <Address AddressLine="444 Kirkpatrick Cres NW" AdminDistrict="AB"
CountryRegion="Canada" Locality="Edmonton" PostalCode="" />

   </GeocodeRequest>

                                                                                         79
   <GeocodeResponse DisplayName="444 Kirkpatrick Crescent NW, Edmonton, AB T6L"
EntityType="Address" Confidence="High" StatusCode="Success">

     <Address AddressLine="444 Kirkpatrick Crescent NW" AdminDistrict="AB"
CountryRegion="Canada" FormattedAddress="444 Kirkpatrick Crescent NW, Edmonton, AB T6L"
Locality="Edmonton" PostalCode="T6L" />

     <InterpolatedLocation Latitude="53.4802172766598" Longitude="-113.403092450204" />

   </GeocodeResponse>

 </GeocodeEntity>

 <GeocodeEntity Id="009"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <GeocodeRequest Culture="en-gb" Query="BD4 9JB" />

   <GeocodeResponse DisplayName="BD4 9JB, United Kingdom" EntityType="Postcode1"
Confidence="High" StatusCode="Success">

     <Address CountryRegion="United Kingdom" FormattedAddress="BD4 9JB, United Kingdom"
PostalCode="BD4 9JB" />

     <RooftopLocation Latitude="53.7784838676453" Longitude="-1.71956151723862" />

   </GeocodeResponse>

 </GeocodeEntity>

 <GeocodeEntity Id="010"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <ReverseGeocodeRequest Culture="en-US">

     <Location Latitude="47.673099" Longitude="-122.11871" />

   </ReverseGeocodeRequest>

   <GeocodeResponse DisplayName="16630 Redmond Way, Redmond, WA 98052-4434"
EntityType="Address" Confidence="High" StatusCode="Success">

     <Address AddressLine="16630 Redmond Way" AdminDistrict="WA" CountryRegion="United
States" FormattedAddress="16630 Redmond Way, Redmond, WA 98052-4434" Locality="Redmond"
PostalCode="98052-4434" />

     <RooftopLocation Latitude="47.673302" Longitude="-122.118576" />

   </GeocodeResponse>

 </GeocodeEntity>

 <GeocodeEntity Id="011"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

   <ReverseGeocodeRequest Culture="en-ca">

     <Location Latitude="53.4802172766598" Longitude="-113.403092450204" />

   </ReverseGeocodeRequest>

                                                                                          80
    <GeocodeResponse DisplayName="457 Kirkpatrick Crescent NW, Edmonton Alberta, Canada"
EntityType="Address" Confidence="Medium" StatusCode="Success">

      <Address AddressLine="457 Kirkpatrick Crescent NW" AdminDistrict="Alberta"
CountryRegion="Canada" FormattedAddress="457 Kirkpatrick Crescent NW, Edmonton Alberta,
Canada" Locality="Edmonton" PostalCode="T6L" />

      <InterpolatedLocation Latitude="53.4802068024874" Longitude="-113.403086364269" />

    </GeocodeResponse>

  </GeocodeEntity>

  <GeocodeEntity Id="012"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

    <ReverseGeocodeRequest Culture="en-gb">

      <Location Latitude="53.7784838676453" Longitude="-1.71956151723862" />

    </ReverseGeocodeRequest>

    <GeocodeResponse DisplayName="Fern Street, Bradford BD4 9, United Kingdom"
EntityType="Address" Confidence="Medium" StatusCode="Success">

      <Address AddressLine="Fern Street" AdminDistrict="England" CountryRegion="United
Kingdom" FormattedAddress="Fern Street, Bradford BD4 9, United Kingdom"
Locality="Bradford" PostalCode="BD4 9" />

      <InterpolatedLocation Latitude="53.7784677743912" Longitude="-1.71975195407867" />

    </GeocodeResponse>

  </GeocodeEntity>

</GeocodeFeed>

Error Output
The following is an example list of locations that were not geocoded successfully.
<GeocodeFeed >

  <GeocodeEntity Id="004"
xmlns="http://schemas.microsoft.com/search/local/2010/5/geocode">

    <GeocodeRequest Culture="en-US" Query="">

      <Address AddressLine="" AdminDistrict="" />

    </GeocodeRequest>

    <GeocodeResponse StatusCode="BadRequest" FaultReason="Parameter name: Address" />

  </GeocodeEntity>

</GeocodeFeed>


Pipe (|) Example



                                                                                          81
Input
1|en-US||16630 Redmond Way|WA|USA|||Redmond|98052||||||||||||||||||||||

2|en-US||16552 NE 74th St|WA||||Redmond|||High||||||||||||||||||||||

3|en-US|Seattle Space Needle||||||||||||||||||||||||||||

4|en-US|||||||||||||||||||||||||||||

5|en-US||W Jefferson Blvd|CA||||Los Angeles|90007||||||||||||||||||||||||

6|en-US|||CA||||Los angeles|||||||||||||||||||||||||

7|en-ca|Montreal Canada||||||||||||||||||||||||||||

8|en-CA||444 Kirkpatrick Cres NW|AB|Canada|||Edmonton||||||||||||||||||||||||

9|en-gb|BD4 9JB||||||||||||||||||||||||||||

10|en-us||||||||||||||||||||||||||||47.673099|-122.11871

11|en-ca||||||||||||||||||||||||||||53.48021728|-113.4030925

12|en-gb||||||||||||||||||||||||||||53.77848387|-1.719561517

Successful Output
The following is an example list of locations that were geocoded successfully.
1|en-US||16630 Redmond Way|WA|USA|||Redmond|98052|||16630 Redmond Way|WA|United
States||16630 Redmond Way, Redmond, WA 98052-4434|Redmond|98052-4434||47.673302|-
122.118576|47.673099|-122.11871|High|16630 Redmond Way, Redmond, WA 98052-
4434|Address|Success|||

2|en-US||16552 NE 74th St|WA||||Redmond|||High|16552 NE 74th St|WA|United States||16552
NE 74th St, Redmond, WA 98052-7804|Redmond|98052-7804||||47.670211|-122.119581|High|16552
NE 74th St, Redmond, WA 98052-7804|Address|Success|||

3|en-US|Seattle Space Needle|||||||||||Washington|United States||Space Needle,
WA|Seattle|||47.620495|-122.34931|||High|Space Needle, WA|LandmarkBuilding|Success|||

5|en-US||W Jefferson Blvd|CA||||Los Angeles|90007|||W Jefferson Blvd|CA|United States||W
Jefferson Blvd, Los Angeles, CA 90007|Los Angeles|90007||||34.0236140484618|-
118.28398661223|High|W Jefferson Blvd, Los Angeles, CA 90007|RoadBlock|Success|||

6|en-US|||CA||||Los angeles|||||California|United States||Los Angeles, CA|Los
Angeles|||34.0532901138067|-118.245009407401|||High|Los Angeles,
CA|PopulatedPlace|Success|||

7|en-ca|Montreal Canada|||||||||||Quebec|Canada||Montreal,
QC|Montreal|||45.5122858285904|-73.5543867945671|||High|Montreal,
QC|PopulatedPlace|Success|||

8|en-CA||444 Kirkpatrick Cres NW|AB|Canada|||Edmonton||||444 Kirkpatrick Crescent
NW|AB|Canada||444 Kirkpatrick Crescent NW, Edmonton, AB
T6L|Edmonton|T6L||||53.4802172766598|-113.403092450204|High|444 Kirkpatrick Crescent NW,
Edmonton, AB T6L|Address|Success|||

                                                                                          82
9|en-gb|BD4 9JB||||||||||||United Kingdom||BD4 9JB, United Kingdom||BD4
9JB||53.7784838676453|-1.71956151723862|||High|BD4 9JB, United
Kingdom|Postcode1|Success|||

10||||||||||||16630 Redmond Way|WA|United States||16630 Redmond Way, Redmond, WA 98052-
4434|Redmond|98052-4434||47.673302|-122.118576|||High|16630 Redmond Way, Redmond, WA
98052-4434|Address|Success||47.673099|-122.11871

11||||||||||||457 Kirkpatrick Crescent NW|Alberta|Canada||457 Kirkpatrick Crescent NW,
Edmonton Alberta, Canada|Edmonton|T6L||||53.4802068024874|-113.403086364269|Medium|457
Kirkpatrick Crescent NW, Edmonton Alberta, Canada|Address|Success||53.48021728|-
113.4030925

12||||||||||||Fern Street|England|United Kingdom||Fern Street, Bradford BD4 9, United
Kingdom|Bradford|BD4 9||||53.7784677743912|-1.71975195407867|Medium|Fern Street, Bradford
BD4 9, United Kingdom|Address|Success||53.77848387|-1.719561517

Error Output
The following is an example list of locations that were not geocoded successfully.
4|en-US||||||||||||||||||||||||||BadRequest|Either Query or Address must be specified.||

Tab Example


    In the following examples, a tab character is represented by an arrow: ->.
Input
1->en-US->->16630 Redmond Way->WA->USA->->->Redmond->98052->->->->->->->->->->->->->->->-
>->->->->->->->->

2->en-US->->16552 NE 74th St->WA->->->->Redmond->->->High->->->->->->->->->->->->->->->-
>->->->->->->

3->en-US->Seattle Space Needle->->->->->->->->->->->->->->->->->->->->->->->->->->->->

4->en-US->->->->->->->->->->->->->->->->->->->->->->->->->->->->->

5->en-US->->W Jefferson Blvd->CA->->->->Los Angeles->90007->->->->->->->->->->->->->->->-
>->->->->->->->->

6->en-US->->->CA->->->->Los angeles->->->->->->->->->->->->->->->->->->->->->->->->->

7->en-ca->Montreal Canada->->->->->->->->->->->->->->->->->->->->->->->->->->->->

8->en-CA->->444 Kirkpatrick Cres NW->AB->Canada->->->Edmonton->->->->->->->->->->->->->-
>->->->->->->->->->->

9->en-gb->BD4 9JB->->->->->->->->->->->->->->->->->->->->->->->->->->->->

10->en-us->->->->->->->->->->->->->->->->->->->->->->->->->->->->47.673099->-122.11871

11->en-ca->->->->->->->->->->->->->->->->->->->->->->->->->->->->53.48021728->-
113.4030925

                                                                                          83
12->en-gb->->->->->->->->->->->->->->->->->->->->->->->->->->->->53.77848387->-
1.719561517

Successful Output
The following is an example list of locations that were geocoded successfully.
1->en-US->->16630 Redmond Way->WA->USA->->->Redmond->98052->->->16630 Redmond Way->WA-
>United States->->16630 Redmond Way, Redmond, WA 98052-4434->Redmond->98052-4434->-
>47.673302->-122.118576->47.673099->-122.11871->High->16630 Redmond Way, Redmond, WA
98052-4434->Address->Success->->->

2->en-US->->16552 NE 74th St->WA->->->->Redmond->->->High->16552 NE 74th St->WA->United
States->->16552 NE 74th St, Redmond, WA 98052-7804->Redmond->98052-7804->->->->47.670211-
>-122.119581->High->16552 NE 74th St, Redmond, WA 98052-7804->Address->Success->->->

3->en-US->Seattle Space Needle->->->->->->->->->->->Washington->United States->->Space
Needle, WA->Seattle->->->47.620495->-122.34931->->->High->Space Needle, WA-
>LandmarkBuilding->Success->->->

5->en-US->->W Jefferson Blvd->CA->->->->Los Angeles->90007->->->W Jefferson Blvd->CA-
>United States->->W Jefferson Blvd, Los Angeles, CA 90007->Los Angeles->90007->->->-
>34.0236140484618->-118.28398661223->High->W Jefferson Blvd, Los Angeles, CA 90007-
>RoadBlock->Success->->->

6->en-US->->->CA->->->->Los angeles->->->->->California->United States->->Los Angeles,
CA->Los Angeles->->->34.0532901138067->-118.245009407401->->->High->Los Angeles, CA-
>PopulatedPlace->Success->->->

7->en-ca->Montreal Canada->->->->->->->->->->->Quebec->Canada->->Montreal, QC->Montreal-
>->->45.5122858285904->-73.5543867945671->->->High->Montreal, QC->PopulatedPlace-
>Success->->->

8->en-CA->->444 Kirkpatrick Cres NW->AB->Canada->->->Edmonton->->->->444 Kirkpatrick
Crescent NW->AB->Canada->->444 Kirkpatrick Crescent NW, Edmonton, AB T6L->Edmonton->T6L-
>->->->53.4802172766598->-113.403092450204->High->444 Kirkpatrick Crescent NW, Edmonton,
AB T6L->Address->Success->->->

9->en-gb->BD4 9JB->->->->->->->->->->->->United Kingdom->->BD4 9JB, United Kingdom->->BD4
9JB->->53.7784838676453->-1.71956151723862->->->High->BD4 9JB, United Kingdom->Postcode1-
>Success->->->

10->->->->->->->->->->->->16630 Redmond Way->WA->United States->->16630 Redmond Way,
Redmond, WA 98052-4434->Redmond->98052-4434->->47.673302->-122.118576->->->High->16630
Redmond Way, Redmond, WA 98052-4434->Address->Success->->47.673099->-122.11871

11->->->->->->->->->->->->457 Kirkpatrick Crescent NW->Alberta->Canada->->457 Kirkpatrick
Crescent NW, Edmonton Alberta, Canada->Edmonton->T6L->->->->53.4802068024874->-
113.403086364269->Medium->457 Kirkpatrick Crescent NW, Edmonton Alberta, Canada->Address-
>Success->->53.48021728->-113.4030925


                                                                                          84
12->->->->->->->->->->->->Fern Street->England->United Kingdom->->Fern Street, Bradford
BD4 9, United Kingdom->Bradford->BD4 9->->->->53.7784677743912->-1.71975195407867-
>Medium->Fern Street, Bradford BD4 9, United Kingdom->Address->Success->->53.77848387->-
1.719561517



Error Output
The following is an example list of locations that were not geocoded successfully.
4->en-US->->->->->->->->->->->->->->->->->->->->->->->->->->BadRequest->Either Query or
Address must be specified.->->->->->->->->->->->->->->->->->->->->->BadRequest->The
Address.FormattedAddress property must not be specified as it is an output-only
property.->->


CSV (comma-separated-value) Example


Input
1,en-US,,16630 Redmond Way,WA,USA,,,Redmond,98052,,,,,,,,,,,,,,,,,,,,,,

2,en-US,,16552 NE 74th St,WA,,,,Redmond,,,High,,,,,,,,,,,,,,,,,,,,,,

3,en-US,Seattle Space Needle,,,,,,,,,,,,,,,,,,,,,,,,,,,,

4,en-US,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

5,en-US,,W Jefferson Blvd,CA,,,,Los Angeles,90007,,,,,,,,,,,,,,,,,,,,,,,,

6,en-US,,,CA,,,,Los angeles,,,,,,,,,,,,,,,,,,,,,,,,,

7,en-ca,Montreal Canada,,,,,,,,,,,,,,,,,,,,,,,,,,,,

8,en-CA,,444 Kirkpatrick Cres NW,AB,Canada,,,Edmonton,,,,,,,,,,,,,,,,,,,,,,,,

9,en-gb,BD4 9JB,,,,,,,,,,,,,,,,,,,,,,,,,,,,

10,en-us,,,,,,,,,,,,,,,,,,,,,,,,,,,,47.673099,-122.11871

11,en-ca,,,,,,,,,,,,,,,,,,,,,,,,,,,,53.48021728,-113.4030925

12,en-gb,,,,,,,,,,,,,,,,,,,,,,,,,,,,53.77848387,-1.719561517

Successful Output
The following is an example list of locations that were geocoded successfully.
1,en-US,,16630 Redmond Way,WA,USA,,,Redmond,98052,,,16630 Redmond Way,WA,United
States,,"16630 Redmond Way, Redmond, WA 98052-4434",Redmond,98052-4434,,47.673302,-
122.118576,47.673099,-122.11871,High,"16630 Redmond Way, Redmond, WA 98052-
4434",Address,Success,,,

2,en-US,,16552 NE 74th St,WA,,,,Redmond,,,High,16552 NE 74th St,WA,United States,,"16552
NE 74th St, Redmond, WA 98052-7804",Redmond,98052-7804,,,,47.670211,-
122.119581,High,"16552 NE 74th St, Redmond, WA 98052-7804",Address,Success,,,



                                                                                          85
3,en-US,Seattle Space Needle,,,,,,,,,,,Washington,United States,,"Space Needle,
WA",Seattle,,,47.620495,-122.34931,,,High,"Space Needle, WA",LandmarkBuilding,Success,,,

5,en-US,,W Jefferson Blvd,CA,,,,Los Angeles,90007,,,W Jefferson Blvd,CA,United States,,"W
Jefferson Blvd, Los Angeles, CA 90007",Los Angeles,90007,,,,34.0236140484618,-
118.28398661223,High,"W Jefferson Blvd, Los Angeles, CA 90007",RoadBlock,Success,,,

6,en-US,,,CA,,,,Los angeles,,,,,California,United States,,"Los Angeles, CA",Los
Angeles,,,34.0532901138067,-118.245009407401,,,High,"Los Angeles,
CA",PopulatedPlace,Success,,,

7,en-ca,Montreal Canada,,,,,,,,,,,Quebec,Canada,,"Montreal,
QC",Montreal,,,45.5122858285904,-73.5543867945671,,,High,"Montreal,
QC",PopulatedPlace,Success,,,

8,en-CA,,444 Kirkpatrick Cres NW,AB,Canada,,,Edmonton,,,,444 Kirkpatrick Crescent
NW,AB,Canada,,"444 Kirkpatrick Crescent NW, Edmonton, AB
T6L",Edmonton,T6L,,,,53.4802172766598,-113.403092450204,High,"444 Kirkpatrick Crescent
NW, Edmonton, AB T6L",Address,Success,,,

9,en-gb,BD4 9JB,,,,,,,,,,,,United Kingdom,,"BD4 9JB, United Kingdom",,BD4
9JB,,53.7784838676453,-1.71956151723862,,,High,"BD4 9JB, United
Kingdom",Postcode1,Success,,,

10,,,,,,,,,,,,16630 Redmond Way,WA,United States,,"16630 Redmond Way, Redmond, WA 98052-
4434",Redmond,98052-4434,,47.673302,-122.118576,,,High,"16630 Redmond Way, Redmond, WA
98052-4434",Address,Success,,47.673099,-122.11871

11,,,,,,,,,,,,457 Kirkpatrick Crescent NW,Alberta,Canada,,"457 Kirkpatrick Crescent NW,
Edmonton Alberta, Canada",Edmonton,T6L,,,,53.4802068024874,-113.403086364269,Medium,"457
Kirkpatrick Crescent NW, Edmonton Alberta, Canada",Address,Success,,53.48021728,-
113.4030925

12,,,,,,,,,,,,Fern Street,England,United Kingdom,,"Fern Street, Bradford BD4 9, United
Kingdom",Bradford,BD4 9,,,,53.7784677743912,-1.71975195407867,Medium,"Fern Street,
Bradford BD4 9, United Kingdom",Address,Success,,53.77848387,-1.719561517

Error Output
The following is an example list of locations that were not geocoded successfully.
4,en-US,,,,,,,,,,,,,,,,,,,,,,,,,,BadRequest,Either Query or Address must be specified.,,


Entity Types
Entity type identifies a location. The following table lists the available entity types.


EntityType                                            Description

Address                                               A physical address of a location.


                                                                                           86
EntityType               Description

AdminDivision1           A first-order, initial political subdivision of a
                         [Sovereign], such as a state, a province, a
                         department, a region, or a prefecture.

AdminDivision2           A second-order political subdivision of a
                         [CountryRegion], a division of an
                         [AdminDivision1] or a [Dependent].

AdminDivision3           A third-order political subdivision of a
                         [CountryRegion], a division of an
                         [AdminDivision2].

AdministrativeBuilding   A building that contains governmental offices or
                         facilities.

AdministrativeDivision   An administrative division of a [CountryRegion],
                         undifferentiated as to administrative level.

AgriculturalStructure    A [Structure] used for agricultural purposes.

Airport                  A place where aircraft regularly land and take
                         off, with runways, navigational aids, and
                         facilities for handling passengers and/or cargo.

AirportRunway            An improved surface suitable for landing
                         airplanes.

AmusementPark            A facility that contains rides and other
                         attractions, such as a theme park.

AncientSite              A place where archeological remains, old
                         structures, or cultural artifacts are located.

Aquarium                 A place where marine life is displayed to the
                         public.

Archipelago              A logical grouping of [Island]s.

Autorail                 A [Railway] that carries automobiles.

Basin                    A low-lying area mostly or wholly surrounded
                         by higher ground.

Battlefield              A site of a land battle of historical importance.

Bay                      An area of water partially enclosed by an
                         indentation of shoreline.

Beach                    A [Coast] with a surface of sand, pebbles, or


                                                                             87
EntityType          Description
                    small rocks.

BorderPost          A post or station at an international boundary
                    for regulating the movement of people and
                    goods.

Bridge              A structure erected across an obstacle, such as
                    a stream or road, that is used by vehicles and
                    pedestrians.

BusinessCategory    A category that identifies a kind of business.

BusinessCenter      A place where a number of businesses are
                    located.

BusinessName        A name that identifies a business.

BusinessStructure   A [Structure] used for commercial purposes.

BusStation          A place where buses pick up and discharge
                    passengers.

Camp                A site occupied by tents, huts, or other shelters
                    for temporary use.

Canal               An artificially constructed watercourse.

Cave                An underground passageway or chamber, or a
                    cavity on the side of a cliff.

CelestialFeature    A spherical body in space.

Cemetery            A burial place or a burial ground.

Census1             One of the set of the most detailed, lowest-level
                    [CensusDistrict]s.

Census2             One of the set of second-order
                    [CensusDistrict]s composed by aggregating
                    [Census1]s.

CensusDistrict      A district defined by a national census bureau
                    and used for statistical data collection.

Channel             A body of water between two landmasses.

Church              A building for public Christian worship.

CityHall            A building that contains the administrative
                    offices of a municipal government.


                                                                     88
EntityType         Description

Cliff              A high, steep-to-perpendicular slope that
                   overlooks a lower area or a water body.

ClimateRegion      An area of homogenous climactic conditions,
                   as defined by modified Koeppen classes.

Coast              An area of land adjacent to a [WaterFeature].

CommunityCenter    A facility for community recreation and
                   meetings.

Continent          A very large landmass, surrounded by water
                   and larger than an [Island], that forms one of
                   the primary divisions of land on a
                   [CelestialFeature].

ConventionCenter   A large meeting hall for conventions and other
                   meetings, and shows.

CountryRegion      A primary [PoliticalUnit].

Courthouse         A building in which courts of law are held.

Crater             A generally circular, saucer-shaped, or bowl-
                   shaped depression caused by volcanic or
                   meteorite explosive action.

CulturalRegion     An area of land with strong local identity, but no
                   political status.

Current            A large area of ocean where surface water
                   flows in a certain constant general direction.

Dam                A barrier constructed across a stream to
                   impound water.

Delta              An area where a [River] divides into many
                   separate water channels as it enters a [Sea] or
                   a [Lake].

Dependent          A [PoliticalUnit] that is politically controlled by a
                   [Sovereign], but separate geographically, and
                   to some degree politically, such as a territory, a
                   colony, or a dependency.

Desert             A large area with low rainfall and little or no
                   vegetation.

DisputedArea       An area in political dispute that is not

                                                                     89
EntityType                     Description
                               considered part of any [CountryRegion].

DrainageBasin                  A land region where all surface water drains
                               into one specific [WaterFeature].

Dune                           A wave form, a ridge, or a star-shaped feature
                               composed of sand.

EarthquakeEpicenter            A place where the destructive force of a
                               specific earthquake is centered.

Ecoregion                      A region with a homogeneous ecosystem, flora,
                               and/or fauna.

EducationalStructure           A place for providing instruction.

ElevationZone                  An area where the surface elevation of all land
                               is within a defined range.

Factory                        A building or set of buildings where goods are
                               manufactured, processed, or fabricated.

FerryRoute                     A route used by a boat, or by other floating
                               conveyances regularly used to transport people
                               and vehicles across a [WaterFeature].

FerryTerminal                  A structure and associated facilities where a
                               ferry boat docks and takes on passengers,
                               automobiles, and/or cargo.

FishHatchery                   A place for hatching fish eggs or raising fish.

Forest                         A large area of trees.

FormerAdministrativeDivision   An [AdministrativeDivision] that no longer
                               exists.

FormerPoliticalUnit            A [PoliticalUnit] that no longer exists.

FormerSovereign                A [Sovereign] that no longer exists.

Fort                           A defensive structure or earthwork.

Garden                         An enclosure for displaying selected plant life.

GeodeticFeature                An invisible point, line, or area on the surface of
                               a [CelestialFeature] that is used for geographic
                               reference.

GeoEntity                      A single thing that has spatial extent and
                               location.

                                                                                 90
EntityType                 Description

GeographicPole             One of the two points of intersection of the
                           surface of a [CelestialFeature] and its axis of
                           rotation.

Geyser                     A [HotSpring] that intermittently shoots water
                           into the air.

Glacier                    A mass of ice, usually at high latitudes or high
                           elevations, with sufficient thickness to flow
                           away from the source area.

GolfCourse                 A recreational field where golf is played.

GovernmentStructure        A [Structure] typically owned and operated by a
                           governmental entity.

Heliport                   A place where helicopters land and take off.

Hemisphere                 A half of the surface of a [Celestial Feature],
                           usually specified as northern, southern,
                           eastern, or western.

HigherEducationFacility    A place where students receive advanced or
                           specialized education, such as a college or a
                           university.

HistoricalSite             A place of historical importance.

Hospital                   A building in which the sick or injured,
                           especially those confined to bed, are medically
                           treated.

HotSpring                  A place where hot water emerges from the
                           ground.

Ice                        A large area covered with frozen water.

IndigenousPeoplesReserve   An area of land set aside for aboriginal, tribal,
                           or native populations.

IndustrialStructure        A [Structure] used for industrial or extractive
                           purposes.

InformationCenter          A place where tourists and citizens can obtain
                           information.

InternationalDateline      The line running between geographic poles
                           designated as the point where a calendar day
                           begins.

                                                                             91
EntityType                  Description

InternationalOrganization   An area of land composed of the member
                            [PoliticalUnit]s of an official governmental
                            organization composed of two or more
                            [Sovereign]s.

Island                      An area of land completely surrounded by
                            water and smaller than a [Continent].

Isthmus                     A narrow strip of land connecting two larger
                            landmasses and bordered by water on two
                            sides.

Junction                    A place where two or more roads join.

Lake                        An inland water body, usually fresh water.

LandArea                    A relatively small area of land exhibiting a
                            common characteristic that distinguishes it from
                            the surrounding land.

Landform                    A natural geographic feature on dry land.

LandmarkBuilding            A [Structure] that is a well-known point of
                            reference.

LatitudeLine                An imaginary line of constant latitude that
                            circles a [CelestialFeature], in which every point
                            on the line is equidistant from a geographic
                            pole.

Library                     A place where books and other media are
                            stored and loaned out to the public or others.

Lighthouse                  A tall structure with a major navigation light.

LinguisticRegion            An area of land where most of the population
                            speaks the same language or speaks
                            languages in the same linguistic family.

LongitudeLine               An imaginary line of constant longitude on a
                            [CelestialFeature] that runs from one
                            geographic pole to the other.

MagneticPole                A point on the surface of a [CelestialFeature]
                            that is the origin for lines of magnetic force.

Marina                      A harbor facility for small boats.

Market                      A place where goods are bought and sold.

                                                                              92
EntityType              Description

MedicalStructure        A [Structure] in which the sick or injured are
                        medically treated.

MetroStation            A place where urban rapid transit trains pick up
                        and drop off passengers, often underground or
                        elevated.

MilitaryBase            A place used by an armed service for storing
                        arms and supplies, for accommodating and
                        training troops, and as a base from which
                        operations can be initiated.

Mine                    A place where mineral ores are extracted from
                        the ground by excavating surface pits and
                        subterranean passages.

Mission                 A place characterized by dwellings, school,
                        church, hospital, and other facilities operated
                        by a religious group for the purpose of
                        providing charitable services and to propagate
                        religion.

Monument                A commemorative structure or statue.

Mosque                  A building for public Islamic worship.

Mountain                An elevated landform that rises, often steeply,
                        above surrounding land on most sides.

MountainRange           A group of connected [Mountain]s.

Museum                  A building where objects of permanent interest
                        in one or more of the arts and sciences are
                        preserved and exhibited.

NauticalStructure       A [Structure] used for nautical purposes.

NavigationalStructure   A [Structure] used for navigational purposes.

Neighborhood            A section of a [PopulatedPlace], usually
                        homogenous and/or well-known, but often with
                        indistinct boundaries.

Oasis                   An area in a [Desert] that contains water and
                        plant life.

ObservationPoint        A wildlife or scenic observation point.

Ocean                   A vast expanse of salt water, one of the major

                                                                         93
EntityType       Description
                 [Sea]s covering part of the earth.

OfficeBuilding   A building that contains offices.

Park             An area maintained as a place of scenic
                 beauty, or for recreation.

ParkAndRide      A parking lot reserved for mass transit
                 commuters.

Pass             A break in a [MountainRange] used for
                 transportation from one side of the mountain
                 range to the other.

Peninsula        An elongated area of land projecting into a
                 body of water and surrounded by water on
                 three sides.

Plain            An extensive area of comparatively level to
                 gently undulating land, lacking surface
                 irregularities.

Planet           A [CelestialFeature] that orbits a star.

Plate            A section of a planetary crust that is in motion
                 relative to other tectonic plates.

Plateau          An elevated plain with steep slopes on one or
                 more sides.

PlayingField     A tract of land used for playing team sports
                 and/or other athletic events.

Pole             A point on the surface of a [CelestialFeature]
                 that marks an important geographical or
                 astronomical location.

PoliceStation    A building in which police are stationed or
                 posted.

PoliticalUnit    An area of land with well-defined borders that is
                 subject to a specific political administration.

PopulatedPlace   A concentrated area of human settlement, such
                 as a city, a town, or a village.

Postcode         A district used by a postal service as an aid in
                 postal distribution and having a unique
                 identifying code.


                                                                  94
EntityType              Description

Postcode1               One of the set of lowest-level and most detailed
                        set of [PostCode]s in a [Sovereign].

Postcode2               One of the set of second-order (one level up
                        from the lowest level) [Postcode]s in a
                        [Sovereign], composed by aggregating
                        [Postcode1]s.

Postcode3               One of the set of third-order [Postcode]s in a
                        [Sovereign], composed by aggregating
                        [Postcode2]s.

Postcode4               One of the set of fourth-order [Postcode]s in a
                        [Sovereign], composed by aggregating
                        [Postcode3]s.

PostOffice              A public building in which mail is received,
                        sorted, and distributed.

PowerStation            A facility for generating electric power.

Prison                  A facility for confining persons convicted or
                        accused of crimes.

Promontory              A small, usually pointed [Peninsula] that often
                        marks the terminus of a landmass.

RaceTrack               A track where races are held.

Railway                 A permanent twin steel-rail track on which
                        trains move.

RailwayStation          A place comprised of ticket offices, platforms,
                        and other facilities for loading and unloading
                        train passengers and freight.

RecreationalStructure   A [Structure] used for watching or participating
                        in sports or other athletic activities.

Reef                    A partly submerged feature, usually of coral,
                        that projects upward near the water's surface
                        and can be a navigational hazard.

Region                  A large area of land where a specific
                        characteristic of the land or its people is
                        relatively homogenous.

ReligiousRegion         An area of land where the population holds


                                                                         95
EntityType               Description
                         relatively homogenous religious practices.

ReligiousStructure       A structure where organized, public religious
                         services are held.

ResearchStructure        A [Structure] used for scientific purposes.

Reserve                  A tract of public land set aside for restricted use
                         or reserved for future use.

ResidentialStructure     A house, a hut, an apartment building, or
                         another structure where people reside.

RestArea                 A designated area, usually along a major
                         highway, where motorists can stop to relax.

River                    A stream of running water.

Road                     An open way with an improved surface for
                         efficient transportation of vehicles.

RoadBlock                A road.

RoadIntersection         A junction where two or more roads meet or
                         cross at the same grade.

Ruin                     A destroyed or decayed structure that is no
                         longer functional.

Satellite                A [CelestialFeature] that orbits a [Planet].

School                   A place where people, usually children, receive
                         a basic education.

ScientificResearchBase   A scientific facility used as a base from which
                         research is carried out or monitored.

Sea                      A large area of salt water.

SeaplaneLandingArea      A place on a water body where floatplanes land
                         and take off.

ShipWreck                A site of the remains of a wrecked vessel.

ShoppingCenter           A collection of linked retail establishments.

Shrine                   A structure or place that memorializes a person
                         or religious concept.

Site                     A place most notable because of an event that
                         occurred in that location.


                                                                           96
EntityType                Description

SkiArea                   A place developed for recreational Alpine or
                          Nordic skiing.

Sovereign                 An independent nation-state, the highest level
                          of political authority in that location.

SpotElevation             A point on a [CelestialFeature]'s surface with a
                          known elevation.

Spring                    A place where water emerges from the ground.

Stadium                   A structure with an enclosure for athletic games
                          with tiers of seats for spectators.

StatisticalDistrict       An area of land defined as a district to be used
                          for statistical collection or service provision.

Structure                 A building, a facility, or a group of buildings
                          and/or facilities used for a certain common
                          purpose.

TectonicBoundary          A line that forms the border between two
                          [Plate]s.

TectonicFeature           A [Landform] related to [Plate]s and their
                          movement.

Temple                    An edifice dedicated to religious worship.

TimeZone                  A large area within which the same time
                          standard is used.

TouristStructure          A [Structure] typically used by tourists.

Trail                     A path, a track, or a route used by pedestrians,
                          animals, or off-road vehicles.

TransportationStructure   A [Structure] used for transportation purposes.

Tunnel                    A subterranean passageway for transportation.

UnderwaterFeature         A feature on the floor of a [WaterFeature].

UrbanRegion               An area of land with high population density
                          and extensive urban development.

Valley                    A low area surrounded by higher ground on two
                          or more sides.

Volcano                   A [Mountain] formed by volcanic action and


                                                                            97
EntityType                                         Description
                                                   composed of volcanic rock.

Wall                                               An upright structure that encloses, divides, or
                                                   protects an area.

Waterfall                                          A vertical or very steep section of a [River].

WaterFeature                                       A geographic feature that has water on its
                                                   surface.

Well                                               A cylindrical hole, pit, or tunnel drilled or dug
                                                   down to a depth from which water, oil, or gas
                                                   can be pumped or brought to the surface.

Wetland                                            An area of high soil moisture, partially or
                                                   intermittently covered with shallow water.

Zoo                                                A zoological garden or park where wild animals
                                                   are kept for exhibition.



Data Source Management API
Use the Data Source Management API to create, update, download, and delete data sources,
and to get information about data sources. A data source stores entity data for a specified user-
defined entity type.


      To use the Data Source Management API, you must have access to Bing Spatial Data
      Services. If you would like to request access to Bing Spatial Data Services, email
      MAPLIC@microsoft.com with your Bing Maps Account ID and (for publicly-accessible
      sites) top level domains. You must email this request from the email account associated
      with your Bing Maps Account in the Bing Maps Account Center
      (http://www.bingmapsportal.com).
      As an enterprise user, you can also use the Bing Maps Account Center to geocode, edit
      and upload entity data to a new or existing data source. You can also download and
      delete a data source. For more information, see Creating and Managing Data Sources.
To create a data source: Use the Load Data Source Dataflow to create a data source for an
entity type. The properties of the entity type are defined in a data schema that you upload along
with sets of entity data. To create a data source, you must have a Bing Maps Account. The key
parameter that defines the data source master key and the queryKey parameter (when it is
specified) must be set to Bing Maps Keys from this account.
If you are an enterprise customer, you can also use the Bing Maps Account Center
(https://www.bingmapsportal.com) to geocode and upload data to a new or existing data source.
For more information, see Geocode and Publish Entity Data to a Data Source.

                                                                                                       98
To update a data source: After the data source is created, you can add or edit entities by using
the Load Data Source Dataflow and setting the loadOperation parameter to incremental.
To query a data source: After the data source is created, use the Query API and the data
source query key to query the data source.
To get information about data sources: Use the Get Data Source Information URLs to get
information about a data source or to query for all the data sources that belong to a Bing Maps
Account. You can use these URLs to get entity type and entity property information as well as get
the base URL to use to query a data source.
To download a data source:: Use the Data Source Download Dataflow to download entity data
for a published data source.
To delete a data source: Use the Delete a Data Source URL to delete a data source.


In this Section

Load Data Source Dataflow                         Describes how to create a data source and
                                                  upload entity data.

Get Data Source Information                       Describes how to get information about one or
                                                  more data sources.

Data Source Download Dataflow                     Describes how to download entity data for a
                                                  published data source.

Delete a Data Source                              Describes how to delete a data source.



Load Data Source Dataflow
The Load Data Source Dataflow API is a component of the Bing Spatial Data Services. You can
use the Load Data Source Dataflow API to create a data source that contains entity data for a
user-specified entity type. For example, a data source could contain location and hours of
operation information for a set of restaurants. With the Load Data Source Dataflow API you can:
   Create a data source.
   Update an entity and add new entities to a data source
   Overwrite an existing data source.


     To use the Load Data Source Dataflow, you must have access to Bing Spatial Data
     Services. If you would like to request access to Bing Spatial Data Services, email
     MAPLIC@microsoft.com with your Bing Maps Account ID and (for publicly-accessible
     sites) top level domains. You must email this request from the email account associated
     with your Bing Maps Account in the Bing Maps Account Center
     (http://www.bingmapsportal.com).


                                                                                                99
    If you are an enterprise customer, you can use the Bing Maps Account Center to
    geocode, edit and upload entity data to a new or existing data source. You can also
    download and delete a data source. For more information, see Creating and Managing
    Data Sources.
The Load Data Source Dataflow API creates and updates data sources by creating load data
source jobs. The Create a Load Data Source Job and Input Entity Data URL is used to create the
load data source job and requires a data schema and a set of entity data. The data schema and
entity data can be provided in XML format or as values separated by commas, tabs or pipe (|)
values. For more information about the data schema and input data, see Load Data Source Data
Schema and Sample Input.
After you have created a job, you can use the Get Status of a Load Data Source Job URL to get
job status. A job can have one of three statuses: “Pending”, “Completed” or “Aborted”. A job has a
“Pending” status when it is created and keeps that status until the job is “Completed” or Aborted”.
When a job completes, the response returns a unique base URL that you can use to query the
data source with the Query API.
You can delete a data source by using the Delete a Data Source API.


    The size of the data you upload with a Load Data Source Dataflow job must be no more
    than 300 MB. If the data is compressed, the size of the uncompressed data must be no
    more than 300 MB. The data you upload must use UTF-8 encoding.
    There are limits on the number of dataflow and data source jobs that you can create. For
    more information, see Dataflow and Data Source Job Requirements.
    A Bing Maps Account can have up to 25 published data sources.
    There may be a delay between the time that a Load Data Source job completes and the
    time you can query the data source. This delay can occur while the data source is
    performing some additional processing.

In this Section


Create a Load Data Source Job and Input           Describes how to create a data source and
Entity Data                                       upload entity data by using a load data source
                                                  job. You can also use this API to edit a data
                                                  source.

Get Status of a Load Data Source Job              Describes how to request status for a load data
                                                  source job.

Load Data Source Dataflow Response                Describes the responses returned when you
Description                                       create and get status for a load data source
                                                  job.


                                                                                               100
Load Data Source Data Schema and Sample            Describes how to define a data schema and
Input                                              input data for an entity type. Examples are
                                                   provided for XML format and for input data that
                                                   is provided by using sets of values separated
                                                   by pipe (|), comma, or tab characters.

Helpful Tips for Entity Data                       Provides helpful tips to guide you when you
                                                   create a data schema and entity data to upload
                                                   to a data source.

Load Data Source Dataflow Sample Code (C#)         Provides C# code that shows how to upload
                                                   entity data to a data source by using the Load
                                                   Data Source Dataflow API.

Load Data Source Dataflow Sample Code (VB)         Provides VB code that shows how to upload
                                                   entity data to a data source by using the Load
                                                   Data Source Dataflow API.


Create a Load Data Source Job and Input Entity Data
Use the following URL to create and update a data source. This URL creates a load data source
dataflow job.


     As an enterprise user, you can also use the Bing Maps Account Center to geocode, edit
     and upload entity data to a new or existing data source. You can also download and
     delete a data source. For more information, see Creating and Managing Data Sources.
Supported HTTP Methods
POST
URL template


     This template supports both HTTP and HTTPS protocols. URLs in the response use
     HTTPS protocol.
Create a load data source job to create or update a data source.
This URL creates a load data source job to create or update a data source. You must provide a
data schema and entity data.
   To create a data source or replace the data source with a new data schema and entity data,
     set the loadOperation parameter to complete.
   To update existing entities or add new entities to the data source, set the loadOperation
     parameter to incremental and use the existing data schema defined for that data source.
You can upload up to 300 MB of data for each job. If your data is compressed, the size of the
uncompressed data must be no more than 300 MB. The data you upload must use UTF-8
encoding.

                                                                                                 101
The response to this HTTP request returns a URL that you can use to check the status of the
load data source job.
The master key and the query key must be different Bing Maps Keys from the same Bing Maps
Account.
There are limits on the number of dataflow and data source jobs that you can create. For more
information, see Dataflow and Data Source Job Requirements.
http://spatial.virtualearth.net/REST/v1/Dataflows/LoadDataSource?dataSourceName=dataSourc
eName&loadOperation=loadOperation&dataLocation=dataLocation&input=input&output=output&key
=masterKey&queryKey=queryKey



Template Parameters


    Parameter names and values are not case-sensitive except for the key and queryKey
    parameter values.


Parameter    Ali   Description     Values
             as

dataSourc          Required        A user-defined string that contains a name for the data source.
eName              The name of     A data source name can have up to 50 characters and can
                   the data        contain alphanumeric characters and any of the following:
                   source.
                                   ~`!$^_={}
                                   Example: dataSourceName=FourthCoffeeSample

dataLocati         Optional.       A Windows Azure™ Blob Service location that contains the data
on                 Specifies the   to process. The Blob Service uses the following URL formats:
                   location of     http://account-name.blob.core.windows.net/myDataFile
                   the data that
                                   https://account-name.blob.core.windows.net/myDataFile
                   you want to
                   load into the   For more information, see Addressing Blob Service Requests.
                   data source.    Before you make your request to start the dataflow job, make
                   The data        sure that the Blob Service URL is available publicly or shared
                   must contain    with a signature key. If the URL is shared with a signature key, it
                   a data          must be encoded. For more information, see Managing Access
                   schema          to Containers and Blobs.
                   along with      The following content types are supported for data that is
                   the data        retrieved:
                   sets. The          application/xml
                   location
                                      text/xml
                   must be
                                      text/plain
                   hosted by

                                                                                                  102
Parameter   Ali   Description   Values
            as
                  the              application/octet-stream
                  Windows®F     If you are specifying an Azure blob that is accessed by using a
                  Azure™        signature key, you must encode the URL.
                  Blob
                                Example:
                  Service.      dataLocation=http://myAzureAccount.blob.core.windows.net/my
                                EntityData
                     You        Example for an Azure blob with a signature key:
                     must       dataLocation=http%3a%2f%2fmyAzureAccount.blob.core.windo
                     set        ws.net%2fmyEntityData%3fse%3d2012-08-
                     the        27T22%253A46%253A57Z%26sr%3db%26si%3d
                     data       readonly%26sig%3dabcdef10389481
                     Loca
                     tion
                     para
                     met
                     er to
                     the
                     locat
                     ion
                     of
                     the
                     data
                     or
                     inclu
                     de
                     the
                     data
                     to
                     proc
                     ess
                     in
                     the
                     HTT
                     P
                     requ
                     est.
                     If
                     you
                     do
                     both

                                                                                             103
Parameter   Ali   Description     Values
            as
                      , the
                      URL
                      retur
                      ns
                      an
                      error
                      .

input             Required.       One of the following values:
                  The format          xml
                  of the data         csv
                  schema and
                                      tab
                  input data.
                                      pipe
                                  For more information about the data schema and input data
                                  formats including examples, see Load Data Source Data
                                  Schema and Sample Input.
                                  Example:input=csv

loadOpera         Required        One of the following values:
tion              The type of         complete: Replaces all data in the data source with the new
                  operation to          data.
                  perform with        incremental: Update entities and add new entities to a data
                  the data.             source.
                                  Example: loadOperation=complete

output      o     Optional.       One of the following values:
                  The output      json [default]
                  format for
                                  xml
                  the
                  response.       Example: output=xml

key               Required.       A Bing Maps Key obtained from the Bing Maps Account Center.
                  The Bing        For information about how to get a Bing Maps Key, see Getting
                  Maps Key to     a Bing Maps Key.
                  use to create   Example: key=abc123def456ghi789abc123def456ghi789
                  or access
                  the data
                  source. If
                  you are
                  creating a
                  new data

                                                                                                 104
Parameter   Ali   Description    Values
            as
                  source, this
                  Bing Maps
                  Key
                  becomes the
                  master key
                  for the data
                  source. If
                  you are
                  updating a
                  data source,
                  you must set
                  the key
                  parameter to
                  the data
                  source
                  master key.


                     The
                     mast
                     er
                     key
                     and
                     the
                     quer
                     y
                     key
                     must
                     be
                     diffe
                     rent
                     Bing
                     Map
                     s
                     Key
                     s
                     from
                     the
                     sam
                     e
                     Bing

                                          105
Parameter   Ali   Description    Values
            as
                     Map
                     s
                     Acc
                     ount
                     .

queryKey          Optional. A    A Bing Maps Key obtained from the Bing Maps Account Center.
                  Bing Maps      For information about how to get a Bing Maps Key, see Getting
                  Key that is    a Bing Maps Key.
                  used to        All queries on the data source can use this key. You can also
                  query the      use the master key to query the data source. The master key is
                  data source.   the Bing Maps Key that you used for the key parameter when
                                 you create the data source.

                     The         If you do not specify a query key, then you can query the data
                     mast        source with any Bing Maps Key that is associated with the same
                     er          Bing Maps Account as the data source master key.
                     key
                     and
                                    It is best practice to use a Bing Maps Key that is
                     the
                                    different than the master key to query the data source
                     quer
                                    because the master key is also used to update and
                     y
                                    delete the data source. When you use the master key
                     key
                                    for queries, you increase the chance for the master key
                     must
                                    to be compromised by an unauthorized user.
                     be
                                 Example:
                     diffe
                     rent        queryKey=312456def132ghi789abc6473def456ghi321
                     Bing
                     Map
                     s
                     Key
                     s
                     from
                     the
                     sam
                     e
                     Bing
                     Map
                     s
                     Acc
                     ount


                                                                                              106
Parameter     Ali   Description    Values
              as
                       .


Input
When you create the HTTP request to upload data and create a load data source job, you must
post the input data in the body of the request or set the dataLocation parameter to a URL where
your data can be retrieved. You must also set the content type in the request to one of the
following input format values.
Input data must use UTF-8 encoding. For input data examples, see Load Data Source Data
Schema and Sample Input.
This URL supports the following input formats.
   XML (application/xml)
   XML (text/xml)
   Comma-delimited values (text/plain)
   Tab-delimited values (text/plain)
   Pipe-delimited values (text/plain)
   Binary (application/octet-stream)
Response
The response to this URL contains a link that you can use to get the status of the load data
source job.
This URL supports the following response formats.
   JSON (application/json)
   XML (application/xml)
For detailed information about the response, see Load Data Source Dataflow Response
Description.
Examples
EXAMPLE: Create a load data source job to create a new data source that includes the
input data in the HTTP request.
This example creates a new data source and provides a data schema with entity data to load into
the data source. For more information about the data schema and input data, see Load Data
Source Data Schema and Sample Input. Because the dataLocation parameter is not specified in
this example, the input data must be included in the HTTP request. The specified query key must
be used to perform any query operations against this data source. The query key is a Bing Maps
Key that belongs to the same Bing Maps Account as the Bing Maps Key used for the key
parameter.
URL and XML response
http://spatial.virtualearth.net/REST/v1/Dataflows/LoadDataSource?loadOperation=complete&i
nput=xml&o=xml&key=masterKey&query=queryKey

                                                                                               107
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

         xmlns:xsd="http://www.w3.org/2001/XMLSchema"

         xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">

 <Copyright>© 2011 Microsoft and its suppliers. This API and any results cannot be used
or accessed without Microsoft’s express written permission.</Copyright>



<BrandLogoUri>http://spatial.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>

 <StatusCode>201</StatusCode>

 <StatusDescription>Created</StatusDescription>

 <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>

 <TraceId>2bf0339473434af7b34336790b001f7</TraceId>

 <ResourceSets>

   <ResourceSet>

     <EstimatedTotal>1</EstimatedTotal>

     <Resources>

       <DataflowJob>

         <Id>f8293dc72ac04942b7cb003c9608c547</Id>

         <Link
role="self">https://spatial.virtualearth.net/REST/v1/dataflows/LoadDataSource/f8293dc72ac
04942b7cb003c9608c547</Link>

         <Status>Pending</Status>

         <CreatedDate>2010-11-12T20:03:56.3157889-08:00</CreatedDate>

         <CompletedDate xsi:nil="true" />

         <TotalEntityCount>0</TotalEntityCount>

         <ProcessedEntityCount>0</ProcessedEntityCount>

         <FailedEntityCount>0</FailedEntityCount>

       </DataflowJob>

     </Resources>

   </ResourceSet>

 </ResourceSets>

</Response>



URL and JSON response




                                                                                      108
The response returns a URL that you can use to get status of the dataflow job that was created.
The URL is provided as the value of a "url" element under links with the attribute "role" set to
"self".

http://spatial.virtualearth.net/REST/”v1/Dataflows/LoadDataSource?loadOperation=complete&
input=xml&key=masterKey&queryKey=queryKey

{

    "authenticationResultCode":"ValidCredentials",

    "brandLogoUri":"http:\/\/spatial.virtualearth.net\/Branding\/logo_powered_by.png",

    "copyright":"© 2011 Microsoft and its suppliers. This API and any results cannot be
used or accessed without Microsoft’s express written permission.",

    "resourceSets":[

         {

             "estimatedTotal":1,

             "resources":[

                 {

                     "__type":"DataflowJob:http:\/\/schemas.microsoft.com\/search\/local\/ws\/r
est\/v1",

                     "id":"f8293dc72ac04942b7cb003c9608c547",

                     "links":[

                          {

                              "role":"self",

                              "url":"https:\/\/spatial.virtualearth.net\/REST\/v1\/dataflows\/Load
DataSource\/f8293dc72ac04942b7cb003c9608c547"

                          }

                     ],

                     "createdDate":"Fri, 12 Nov 2010 20:03:56 GMT",

                     "description":"FourthCoffeeSample Data Source",

                     "failedEntityCount":0,

                     "processedEntityCount":0,

                     "status":"Pending",

                     "totalEntityCount":0

                 }

             ]

         }

    ],


                                                                                               109
     "statusCode":201,

     "statusDescription":"Created",

     "traceId":"3fa754b674cc431d8a72d86a5aea27be"

}

EXAMPLE: Create a load data source job to update specified entities and add new entities
to data source.
http://spatial.virtualearth.net/REST/v1/Dataflows/LoadDataSource?loadOperation=incrementa
l&input=xml&o=xml&key=masterKey



EXAMPLE: Create a load data source job to create a new data source and use the
dataLocation parameter to specify the location of the input data.

http://spatial.virtualearth.net/REST/v1/Dataflows/LoadDataSource?loadOperation=complete&d
ataLocation=http://myAzureAccount.blob.core.windows.net/myEntityData&input=x

ml&o=xml&key=masterKey&queryKey=queryKey

HTTP Status Codes
In addition to HTTP status codes, error information is provided in the response to this request.
For more information, see the Load Data Source Dataflow Response Description.


     For more details about these HTTP status codes, see Status Codes and Errors.
When the request is successful, the following HTTP status code is returned.
   201
When the request is not successful, the response returns one of the following errors.
   400
   403
         A 403 HTTP status code can occur when you try to create a data source for an account
           that already has the maximum of 25 published data sources.
   500
   503

Get Status of a Load Data Source Job
Use the following URL to get the status of a load data source job.
Supported HTTP Methods
GET
URL template


     This template supports both HTTP and HTTPS protocols. URLs in the response use
     HTTPS protocol.

                                                                                                   110
Get status information for a load data source job.
When you request status information for a load data source job, you must specify the master key
for the data source. You request job status by using the URL returned in the response when you
Create a Load Data Source Job and Input Entity Data. The URL is specified in a link field of the
response and has a role attribute set to self. To use this status URL, you must add the key
parameter and set it to the data source master key. You can optionally add the output parameter
to specify the how the response is returned. The URL template below shows the format of this
status URL.
When the load data source job is complete, the response to this status URL contains another link
field with the role attribute set to datasource. This link field contains a unique URL that you can
use to query the data source. For more information, see Load Data Source Dataflow Response
Description.
http://spatial.virtualearth.net/REST/v1/Dataflows/LoadDatasource/jobID?output=output&key=
masterKey

Template Parameters


      Parameter names and values are not case-sensitive except for the key parameter value.


Parameter            Alias          Description          Values

jobID                               Required. The ID     When you request a dataflow job, the job
                                    of the job.          ID is returned in the ID field of the
                                                         response. For more information, see
                                                         Load Data Source Dataflow Response
                                                         Description.
                                                         Example:
                                                         e14b1d9bd65c4b9d99d267bbb8102ccf

key                                 Required. The        The Bing Maps Key that was specified
                                    master key for the   as the master key for the data source.
                                    data source.         For more information, see Create a Load
                                                         Data Source Job and Input Entity Data.

output               o              Optional. The        One of the following values:
                                    output format for    json [default]
                                    the response.
                                                         xml
                                                         Example: o=xml


Response
This URL supports the following response formats.
    JSON: application/json


                                                                                               111
    XML: application/xml
For information about the response, see Load Data Source Dataflow Response Description.
Examples
EXAMPLE: Request job status for a load data source job.
This example requests status information for the load data source job with an ID of
f8293dc72ac04942b7cb003c9608c547 that was created by specifying the master key
b1c323ea23d99d267d99d267bbb814. This URL without the key and output parameters is
returned in the response when you use the URL to Create a Load Data Source Job and Input
Entity Data.
Responses returned while the job is in process
While the job is in process, the Status in the response is set to Pending.
When the job completes, the Status field in the response is set to Completed and a URL that is
unique to the data source is returned. This unique URL is contained as a link field that has a role
attribute set to self and a name attribute set to service.
URL with XML Response
http://spatial.virtualearth.net/REST/v1/Dataflows/LoadDatasource/f8293dc72ac04942b7cb003c
9608c547?o=xml&key=b1c323ea23d99d267d99d267bbb814

XML Response when the job is in process
In this response, the Status field is set to Pending because the load data source job is in process.
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

                 xmlns:xsd="http://www.w3.org/2001/XMLSchema"

                 xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">

     <Copyright>© 2011 Microsoft and its suppliers. This API and any results cannot be used
or accessed without Microsoft’s express written permission.</Copyright>



<BrandLogoUri>http://spatial.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>

     <StatusCode>200</StatusCode>

     <StatusDescription>OK</StatusDescription>

     <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>

     <TraceId>9401a5764214a3b87a4c982d2d98a64<TraceId>

     <ResourceSets>

      <ResourceSet>

        <EstimatedTotal>1</EstimatedTotal>

        <Resources>

          <DataflowJob>

            <Id>f8293dc72ac04942b7cb003c9608c547</Id>


                                                                                                 112
           <Link
role="self">https://spatial.virtualearth.net/REST/v1/dataflows/LoadDataSource/f8293dc72ac
04942b7cb003c9608c547</Link>

           <Status>Pending</Status>

           <CreatedDate>2010-11-13T12:58:39.3157889-08:00</CreatedDate>

           <CompletedDate xsi:nil="true" />

           <TotalEntityCount>0</TotalEntityCount>

           <ProcessedEntityCount>0</ProcessedEntityCount>

           <FailedEntityCount>0</FailedEntityCount>

         </DataflowJob>

      </Resources>

    </ResourceSet>

  </ResourceSets>

</Response>



XML Response returned when the job has completed.
In this response, the Status field is set to Completed and a new link field that has the role
attribute set to datasource and the name attribute set to service is also returned.

<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

                 xmlns:xsd="http://www.w3.org/2001/XMLSchema"

                 xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">

  <Copyright>© 2011 Microsoft and its suppliers. This API and any results cannot be used
or accessed without Microsoft’s express written permission.</Copyright>



<BrandLogoUri>http://spatial.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>

  <StatusCode>200</StatusCode>

  <StatusDescription>OK</StatusDescription>

  <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>

  <TraceId>9401a5764214a3b87a4c982d2d98a64<TraceId>

  <ResourceSets>

    <ResourceSet>

      <EstimatedTotal>1</EstimatedTotal>

      <Resources>

         <DataflowJob>

           <Id>f8293dc72ac04942b7cb003c9608c547</Id>

                                                                                                113
            <Link
role="self">https://spatial.virtualearth.net/REST/v1/dataflows/LoadDataSource/f8293dc72ac
04942b7cb003c9608c547</Link>

            <Link role="datasource"
name="service">https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d
4f23/FourthCoffeeSample</Link>

            <Status>Completed</Status>

            <CreatedDate>2010-11-13T12:58:39.3157889-08:00</CreatedDate>

            <CompletedDate>2010-11-13T12:59:45.4724897-08:00</CompletedDate>

            <TotalEntityCount>0</TotalEntityCount>

            <ProcessedEntityCount>0</ProcessedEntityCount>

            <FailedEntityCount>0</FailedEntityCount>

           </DataflowJob>

       </Resources>

     </ResourceSet>

    </ResourceSets>

</Response>



URL with JSON Responses
http://spatial.virtualearth.net/REST/v1/Dataflows/LoadDatasource/f8293dc72ac04942b7cb003c
9608c547?key=b1c323ea23d99d267d99d267bbb814

JSON Response returned when the job is in process.
In this response, the status field is set to Pending because the load data source job is in process.
{

    "authenticationResultCode":"ValidCredentials",

    "brandLogoUri":"http:\/\/spatial.virtualearth.net\/Branding\/logo_powered_by.png",

    "copyright":"© 2011 Microsoft and its suppliers. This API and any results cannot be
used or accessed without Microsoft’s express written permission.",

    "resourceSets":[

       {

           "estimatedTotal":1,

           "resources":[

              {

                  "__type":"DataflowJob:http:\/\/schemas.microsoft.com\/search\/local\/ws\/r
est\/v1",


                                                                                                 114
                     "id":"f8293dc72ac04942b7cb003c9608c547",

                     "links":[

                          {

                              "role":"self",

                              "url":"https:\/\/spatial.virtualearth.net\/REST\/v1\/dataflows\/Load
DataSource\/f8293dc72ac04942b7cb003c9608c547"

                          }

                     ],

                     "createdDate":"Mon, 13 Nov 2010 20:58:39 GMT",

                     "failedEntityCount":0,

                     "processedEntityCount":0,

                     "status":"Pending",

                     "totalEntityCount":0

                 }

             ]

         }

    ],

    "statusCode":200,

    "statusDescription":"OK",

    "traceId":"9401a5764214a3b87a4c982d2d98a64"

}

JSON Response returned when the job has completed.
In this response, the Status field is set to Completed and a new links value that has the role
attribute set to "datasource" and the name attribute set to "service" is also returned.

{

    "authenticationResultCode":"ValidCredentials",

    "brandLogoUri":"http:\/\/spatial.virtualearth.net\/Branding\/logo_powered_by.png",

    "copyright":"© 2011 Microsoft and its suppliers. This API and any results cannot be
used or accessed without Microsoft’s express written permission.",

    "resourceSets":[

         {

             "estimatedTotal":1,

             "resources":[

                 {



                                                                                                 115
                     "__type":"DataflowJob:http:\/\/schemas.microsoft.com\/search\/local\/ws\/r
est\/v1",

                     "id":"f8293dc72ac04942b7cb003c9608c547",

                     "links":[

                          {

                              "role":"self",

                              "url":"https:\/\/spatial.virtualearth.net\/REST\/v1\/dataflows\/Load
DataSource\/f8293dc72ac04942b7cb003c9608c547"

                          }

                          {

                              "name":"service",

                              "role":"datasource",

                              "url":"https:\/\/spatial.virtualearth.net\/REST\/v1\/data\/20181f26d
9e94c81acdf9496133d4f23\/FourthCoffeeSample"

                          }

                     ],

                     "completedDate":"Mon, 13 Nov 2010 20:59:45 GMT",

                     "createdDate":"Mon, 13 Nov 2010 20:58:39 GMT",

                     "failedEntityCount":0,

                     "processedEntityCount":0,

                     "status":"Completed",

                     "totalEntityCount":0

                 }

             ]

         }

    ],

    "statusCode":200,

    "statusDescription":"OK",

    "traceId":"9401a5764214a3b87a4c982d2d98a64"

}

HTTP Status Codes


    For more details about these HTTP status codes, see Status Codes and Errors.
When the request is successful, the following HTTP status code is returned.

                                                                                               116
   200
When the request is not successful, the response returns one of the following HTTP status codes.
   400
   401
   500
   503

Load Data Source Dataflow Response Description
The following tables describe the response syntax for a LoadDataSource Dataflow request in a
set of hierarchical tables. Examples in JSON and XML formats are also provided.
Response
The following fields are the top-level fields in the LoadDataSource Dataflow response. Additional
tables describe the fields in each of the collections.


JSON                         XML                           Type                   Description

copyright                    Copyright                     string                 A copyright
                                                                                  notice.

brandLogoUri                 BrandLogoUri                  string                 A URL that
                                                                                  references a
                                                                                  brand image to
                                                                                  support
                                                                                  contractual
                                                                                  branding
                                                                                  requirements.

statusCode                   StatusCode                    integer                The HTTP
                                                                                  Status code for
                                                                                  the request.

statusDescription            StatusDescription             string                 A description of
                                                                                  the HTTP
                                                                                  status code.

authenticationResultCode     AuthenticationResultCode      One of the following   A status code
                                                           values:                that offers
                                                           ValidCredentials       additional
                                                                                  information
                                                           InvalidCredentials
                                                                                  about
                                                           CredentialsExpired
                                                                                  authentication
                                                           NotAuthorized          success or
                                                           NoCredentials          failure.
                                                           None


                                                                                                117
JSON                        XML                           Type                Description

traceId                     TraceId                       string              A unique
                                                                              identifier for the
                                                                              request.

resourceSets                ResourceSets                  collection          A collection of
                                                                              ResourceSet
                                                                              objects. A
                                                                              ResourceSet  is
                                                                              a container of
                                                                              Resources
                                                                              returned by the
                                                                              request. For
                                                                              more
                                                                              information,
                                                                              see the
                                                                              ResourceSet
                                                                              section below.

errorDetails                ErrorDetails                  string[]            A collection of
                                                                              error
                                                                              descriptions.
                                                                              For example,
                                                                              ErrorDetails
                                                                              can identify
                                                                              parameter
                                                                              values that are
                                                                              not valid or are
                                                                              missing. An
                                                                              error log URL is
                                                                              also provided
                                                                              as part of links
                                                                              or Link fields.


ResourceSet
The ResourceSet container provides the following information.


JSON                     XML                       Type                Description

estimatedTotal           EstimatedTotal            long                An estimate of the total
                                                                       number of resources in
                                                                       the ResourceSet.

resources                Resources                 collection          A collection of one or

                                                                                            118
JSON                     XML                       Type                   Description
                                                                          more DataflowJob
                                                                          resources. Information
                                                                          about the DataflowJob
                                                                          resource is found in
                                                                          the DataflowJob
                                                                          section.


DataflowJob
The DataflowJob resource container provides the following information.


JSON                      XML                        Type                Description

id                        Id                         string              A unique string that
                                                                         identifies the dataflow
                                                                         job. There are no
                                                                         requirements for the
                                                                         string format.

links                     Link                       URL                 URLs that is defined by
                                                                         its role and name
                                                                         attributes.
                                                                         “role”:”self”:  Use to
                                                                         check the status of your
                                                                         job. This URL is
                                                                         provided in the response
                                                                         when you create a load
                                                                         data source job.
                                                                         “role”:”self”   and
                                                                         “name”:“datasource”:
                                                                         Use to query and update
                                                                         a data source. This URL
                                                                         appears in the response
                                                                         to a job status request
                                                                         when the load data
                                                                         source job completes.
                                                                         “role”:”output”  and
                                                                         “name”:”failed”: Use to
                                                                         access the error log for
                                                                         the job. This URL
                                                                         appears in the response
                                                                         only when the job status


                                                                                               119
JSON               XML                Type               Description
                                                         is set to Aborted.

description        Description        string             A user-defined
                                                         description of the
                                                         dataflow job. If a
                                                         description is not
                                                         specified when the
                                                         workflow is created, this
                                                         field is not included or
                                                         the value is null.

status             Status             One of the         The status of the
                                      following          dataflow job.
                                      values:
                                      Pending: The
                                      dataflow job is
                                      processing.
                                      Completed:  The
                                      dataflow job has
                                      completed. A
                                      status of
                                      completed does
                                      not indicate
                                      success.
                                      Aborted:   The
                                      workflow
                                      stopped
                                      because of an
                                      error.

createdDate        CreatedDate        DateTime           The date and time that
                                                         the dataflow job was
                                                         created.

completedDate      CompletedDate      DateTime           The date and time that
                                                         the dataflow job is
                                                         completed. If the Status
                                                         field is set to Pending,
                                                         the CompletedDate field
                                                         is not shown or is
                                                         empty.

totalEntityCount   TotalEntityCount   integer            The total number of
                                                         entities that were
                                                                               120
JSON                       XML                       Type           Description
                                                                    uploaded.

processedEntityCount       ProcessedEntityCount      integer        The number of entities
                                                                    that were processed.
                                                                    This number included
                                                                    entities that were
                                                                    processed successfully
                                                                    and those that failed. If
                                                                    the field is set to 0, the
                                                                    number of processed
                                                                    entries is not known.

failedEntityCount          FailedEntityCount         integer        The number of entities
                                                                    that did not process
                                                                    successfully because of
                                                                    an error.

errorMessage               ErrorMessage              string         Additional error
                                                                    information that is
                                                                    provided when the
                                                                    Status is set to Aborted.
                                                                    A link to an error log is
                                                                    also provided in the
                                                                    links or Link field.


DataflowJob Response Examples
The following examples show DataflowJob resource content in JSON and XML formats.
JSON Example
{

    "authenticationResultCode":"ValidCredentials",

    "brandLogoUri":"http:\/\/spatial.virtualearth.net\/Branding\/logo_powered_by.png",

    "copyright":"© 2010 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.",

    "resourceSets":[

       {

           "estimatedTotal":1,

           "resources":[

             {



                                                                                           121
"__type":"DataflowJob:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",

                     "id":"5bf10c37df011183b1879fbb0556e67e",

                     "links":[

                          {

                               "role":"self",



"url":"https:\/\/spatial.virtualearth.net\/REST\/v1\/dataflows\/LoadDataSource\/5bf10c37d
f011183b1879fbb0556e67e"

                          },

                          {

                               "role":"datasource",

                               "name":"service",

                               "url":"https:\/\/
https://spatial.virtualearth.net/REST\/v1\/data\/20181f26d9e94c81acdf9496133d4f23\/Fourth
CoffeeSample"

                          },



                     ],

                     "completedDate":"Mon, 10 May 2010 20:23:49 GMT",

                     "createdDate":"Mon, 10 May 2010 20:22:35 GMT",

                     "description":"Xml",

                     "failedEntityCount":0,

                     "processedEntityCount":12,

                     "status":"Completed",

                     "totalEntityCount":12

                 }

             ]

         }

    ],

    "statusCode":200,

    "statusDescription":"OK",

    "traceId":"e8bfe25fdc4f4bc5824cda4e568e1c19"

}

XML Example
                                                                                      122
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">

 <Copyright>© 2010 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.</Copyright>



<BrandLogoUri>http://spatial.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>

 <StatusCode>200</StatusCode>

 <StatusDescription>OK</StatusDescription>

 <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>

 <TraceId>f65bd9af90e241b3a7d52316314eb352</TraceId>

 <ResourceSets>

   <ResourceSet>

     <EstimatedTotal>1</EstimatedTotal>

     <Resources>

       <DataflowJob>

         <Id>5bf10c37df011183b1879fbb0556e67e</Id>

         <Link
role="self">https://spatial.virtualearth.net/REST/v1/dataflows/Geocode/5bf10c37df011183b1
879fbb0556e67e</Link>

         <Link role="datasource"
name=”service”>https://spatial.virtualearth.com/REST/v1/data/20181f26d9e94c81acdf9496133d
4f23/FourthCoffeeSample</Link>

         <Description>Xml</Description>

         <Status>Completed</Status>

         <CreatedDate>2010-05-10T13:22:35.0553408-07:00</CreatedDate>

         <CompletedDate>2010-05-10T13:23:49.1959658-07:00</CompletedDate>

         <TotalEntityCount>12</TotalEntityCount>

         <ProcessedEntityCount>12</ProcessedEntityCount>

         <FailedEntityCount>0</FailedEntityCount>

       </DataflowJob>

     </Resources>

   </ResourceSet>

 </ResourceSets>


                                                                                         123
</Response>


Load Data Source Data Schema and Sample Input
You must provide a data schema and a set of input data to create a data source when you use
the Create a Load Data Source Job and Input Entity Data URL. The data schema describes the
entity type for the data source. The set of input data must validate against the schema. The data
schema and input data are provided together when you create a LoadDataSource job to create or
update a data source. You can provide a data schema and input data in XML format or as text
with values separated by comma, tab or pipe(|) characters. If the input data is compressed, the
size of the input data must be less than 300 MB.
The input data format for an incremental update to a data source is the same as the format for
creating a data source. The incremental update input data must include the data schema
currently in use by the data source and the entity data to overwrite existing entries or to create
new ones. If the entity ID of a set of entity data matches an entity ID in the data source, the entity
data is replaced by the new data. If the entity ID does not exist, a new entity is created.
DataSchema
The data schema defines the name and attributes of the entity type to use for the new data
source. If you are using XML to format your input data, you must provide an XSLT data schema.
If you providing your input as values separated by comma, tab or pipe (|) characters, you must
provide a text data schema. Example schemas and input are provided in the Example Schema
and Entity Data section below.
You must specify an entity ID and include latitude and longitude properties in your schema. The
following sections describe how to specify the entity ID.
If you are using XML format, you can use System.Data.Dataset to generate the data schema,
primary key information and the input data.
The Bing Spatial Data Services only supports UTF-8 encoded input data.
For some helpful tips about creating the data schema and entity data, see Helpful Tips for Entity
Data.
Entity ID
A data source requires an entity ID that is unique for every entity in the data source. Your data
schema must specify one of the entity properties to be this entity ID. The following examples
show how to specify a property named ShopID as the entity ID in your data schema. The data type
of the entity ID property must be a string and all entity ID values must have a maximum length of
50 characters.
Defining an Entity ID in an XML Schema
When you use XML to format your data, add the following entity ID declaration to the XSLT
schema.
<xs:unique name="Constraint1" msdata:PrimaryKey="true">

  <xs:selector xpath=".//DataSourceName" />

  <xs:field xpath="EntityIDStringProperty" />


                                                                                                   124
</xs:unique>



The following XSLT example specifies the ShopID property as the entity ID for the
FourthCoffeeShops data source.
<xs:unique name="Constraint1" msdata:PrimaryKey="true">

  <xs:selector xpath=".//FourthCoffeeShops" />

  <xs:field xpath="ShopID" />

</xs:unique>

Defining an Entity ID in a Text Data Schema
When you use a text format for your data, use the following property declaration for the entity ID
property in the data schema.
PropertyName(Edm.String,primaryKey)
The following example specifies the ShopID property as the entity ID.
ShopID(Edm.String,primaryKey)

Version String
If you are using a text format for your input data, you must insert the following text data schema
version information at the beginning of the data schema. Currently, the only text data schema
version is 1.0.
Bing Spatial Data Services, 1.0, FourthCoffeeShops

Position Properties
Your data schema is also required to have latitude and longitude properties and each entity must
have valid values for these properties. The elevation property is optional. The following table
defines the input data type and the corresponding OData data type for each position property.


Attribute                Description                Input Data Type        OData Data Type

Latitude                 Required. The latitude     double                 Edm.Double
                         of the entity location.

Longitude                Required. The              double                 Edm.Double
                         longitude of the entity
                         location.

Elevation                The elevation of the       double                 Edm.Double
                         entity location.



Supported Data Types for Entity Properties
The following table shows the supported data types for the data schema. These data types map
to a set of OData types that are used by the datasource.

                                                                                                125
You must use the XML data types in an XML data schema. If you use one of the delimited
formats for your data and data schema (values separated by commas, tabs or pipe (|)
characters), you must use the OData types in the data schema. Descriptions of OData types are
found in the OData Protocol Overview.
There are a maximum number of properties that you can define for each data type. The latitude
and longitude properties do not count towards this maximum.


XML Data Type                    OData Type                         Maximum Number of Properties
                                                                    for the Data Type Collection

string                           Edm.String                         100
                                                                    The maximum string length is
                                                                    2560 characters.

long                             Edm.Int64                          20

boolean                          Edm.Boolean                        200

double                           Edm.Double                         20

dateTime                         Edm.DateTime                       10


Property Name Requirements
Property names must meet the following requirements:
   The property name can have up to 50 characters.
   The property name must contain alphanumeric characters and underscores (_) only.
   The first character of the property name must be a letter or an underscore.
   The property name cannot start with a two underscores (__).
   The string "Entity" is reserved and cannot be used as a property name.
   Property names are case-insensitive.
Example Schema and Entity Data
The following examples show how to define a data schema and entity data that conforms to that
data schema. The Create a Load Data Source Job and Input Entity Data URL requires that the
schema and the input data be provided together in the load data source request. XML and text
file examples are provided. The data schema and input data must use UTF-8 encoding.
XML data schema and input data


     The XML root node (FourthCoffeeSampleData in this example) must have a different
     name than the <xs:element> tag that sets the msdata:IsDataSet attribute
     (FourthCoffeeSample in this example).
In addition to other characters, such as a comma and hyphen (-), you can also use the pipe (|)
character in XML entity values.

                                                                                                   126
<?xml version="1.0" encoding="UTF-8"?>

<FourthCoffeeSampleData>

 <xs:schema id="FourthCoffeeSample" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">

     <xs:element name="FourthCoffeeSample" msdata:IsDataSet="true"
msdata:UseCurrentLocale="true">

      <xs:complexType>

        <xs:choice minOccurs="0" maxOccurs="unbounded">

          <xs:element name="FourthCoffeeShops">

            <xs:complexType>

              <xs:sequence>

                <xs:element name="AddressLine" type="xs:string" minOccurs="0" />

                <xs:element name="Locality" type="xs:string" minOccurs="0" />

                <xs:element name="AdminDistrict" type="xs:string" minOccurs="0" />

                <xs:element name="CountryRegion" type="xs:string" minOccurs="0" />

                <xs:element name="PostalCode" type="xs:string" minOccurs="0" />

                <xs:element name="Phone" type="xs:string" minOccurs="0" />

                <xs:element name="Manager" type="xs:string" minOccurs="0" />

                <xs:element name="StoreOpen" type="xs:string" minOccurs="0" />

                <xs:element name="StoreType" type="xs:string" minOccurs="0" />

                <xs:element name="Name" type="xs:string" minOccurs="0" />

                <xs:element name="DisplayName" type="xs:string" minOccurs="0" />

                <xs:element name="EntityID" type="xs:string" />

                <xs:element name="Longitude" type="xs:double" minOccurs="0" />

                <xs:element name="Latitude" type="xs:double" minOccurs="0" />

                <xs:element name="IsWiFiHotSpot" type="xs:boolean" minOccurs="0" />

                <xs:element name="IsWheelchairAccessible" type="xs:boolean" minOccurs="0"
/>

                <xs:element name="AcceptsOnlineOrders" type="xs:boolean" minOccurs="0" />

                <xs:element name="AcceptsCoffeeCards" type="xs:boolean" minOccurs="0" />

                <xs:element name="Open" type="xs:long" minOccurs="0" />

                <xs:element name="Close" type="xs:long" minOccurs="0" />

                <xs:element name="CreatedDate" msdata:DateTimeMode="Utc"
type="xs:dateTime" minOccurs="0" />



                                                                                      127
                <xs:element name="LastUpdatedDate" msdata:DateTimeMode="Utc"
type="xs:dateTime" minOccurs="0" />

             </xs:sequence>

           </xs:complexType>

         </xs:element>

       </xs:choice>

     </xs:complexType>

     <xs:unique name="Constraint1" msdata:PrimaryKey="true">

       <xs:selector xpath=".//FourthCoffeeShops" />

       <xs:field xpath="EntityID" />

     </xs:unique>

   </xs:element>

 </xs:schema>

 <FourthCoffeeShops>

   <AddressLine>Løven</AddressLine>

   <Locality>Aalborg</Locality>

   <AdminDistrict>Nordjyllands Amt</AdminDistrict>

   <CountryRegion>Danmark</CountryRegion>

   <PostalCode>9200</PostalCode>

   <Phone>303-555-0188</Phone>

   <Manager>Alan Steiner | Pannarat Pattanapitakkul</Manager>

   <StoreOpen>Y</StoreOpen>

   <StoreType>Drive-Thru</StoreType>

   <Name>Fourth Coffee Store #22067</Name>

   <DisplayName>Fourth Coffee Store #22067, Aalborg, Nordjyllands Amt,
Danmark</DisplayName>

   <EntityID>-22067</EntityID>

   <Longitude>9.87443416667</Longitude>

   <Latitude>57.00376611111</Latitude>

   <IsWiFiHotSpot>false</IsWiFiHotSpot>

   <IsWheelchairAccessible>false</IsWheelchairAccessible>

   <AcceptsOnlineOrders>false</AcceptsOnlineOrders>

   <AcceptsCoffeeCards>true</AcceptsCoffeeCards>

   <Open>700</Open>


                                                                               128
   <Close>1800</Close>

   <CreatedDate>2010-11-11T01:19:36.4350494Z</CreatedDate>

   <LastUpdatedDate>2010-11-16T01:19:36.4350494Z</LastUpdatedDate>

 </FourthCoffeeShops>

 <FourthCoffeeShops>

   <AddressLine>1 Microsoft Way</AddressLine>

   <Locality>Redmond</Locality>

   <AdminDistrict>WA</AdminDistrict>

   <CountryRegion>United States</CountryRegion>

   <PostalCode>8600</PostalCode>

   <Phone>425-555-0111</Phone>

   <Manager>Phil Spencer</Manager>

   <StoreOpen>Y</StoreOpen>

   <StoreType>Coffee Shop</StoreType>

   <Name>Fourth Coffee Store #22066</Name>

   <DisplayName>Fourth Coffee Store #22066, Redmond, WA United States</DisplayName>

   <EntityID>-22066</EntityID>

   <Longitude>-122.1293731033802</Longitude>

   <Latitude>47.640568390488625</Latitude>

   <IsWiFiHotSpot>true</IsWiFiHotSpot>

   <IsWheelchairAccessible>true</IsWheelchairAccessible>

   <AcceptsOnlineOrders>true</AcceptsOnlineOrders>

   <AcceptsCoffeeCards>true</AcceptsCoffeeCards>

   <Open>1000</Open>

   <Close>2000</Close>

   <CreatedDate>2010-11-11T01:19:36.4350494Z</CreatedDate>

   <LastUpdatedDate>2010-11-16T01:19:36.4350494Z</LastUpdatedDate>

 </FourthCoffeeShops>

</FourthCoffeeSampleData>



Text data schema and input separated by commas (CSV)
Bing Spatial Data Services, 1.0, FourthCoffeeShops

Phone(Edm.String),EntityID(Edm.String,primaryKey),Longitude(Edm.Double),Latitude(Edm.Doub
le),CountryRegion(Edm.String),Open(Edm.Int64),Close(Edm.Int64)


                                                                                      129
303-555-0188,-22067,9.87443416667,57.00376611111,Danmark,700,1800

425-555-0111,-22066,9.54552166667,56.16946722222,Danmark,1000,2000

Text data schema and input separated by tabs
In the following example, a tab character is represented by an arrow: ->.
Bing Spatial Data Services, 1.0, FourthCoffeeShops

Phone(Edm.String)->EntityID(Edm.String,primaryKey)->Longitude(Edm.Double)-
>Latitude(Edm.Double)->CountryRegion(Edm.String)->Open(Edm.Int64)->Close(Edm.Int64)

303-555-0188->-22067->9.87443416667->57.00376611111->Danmark->700->1800

425-555-0111->-22066->9.54552166667->56.16946722222->Danmark->1000->2000

Text data schema and input separated by pipe characters (|)
Bing Spatial Data Services, 1.0, FourthCoffeeShops

Phone(Edm.String)|EntityID(Edm.String,primaryKey)|Longitude(Edm.Double)|Latitude(Edm.Doub
le)|CountryRegion(Edm.String)|Open(Edm.Int64)|Close(Edm.Int64)

303-555-0188|-22067|9.87443416667|57.00376611111|Danmark|700|1800

425-555-0111|-22066|9.54552166667|56.16946722222|Danmark|1000|2000

Helpful Tips for Entity Data
Here are some tips to help you when you create entity data to use with the Bing Spatial Data
Services.
   Consider using pipe(|)-delimited or XML entity data files. Entity data often contains
     commas (Example: Seattle, WA). Therefore, using the pipe (|) character as a separator in
     entity data files is often a good choice. Similarly, XML files support the use of commas (,),
     hyphens (-), and pipe characters (|) as part of entity data values.
   Make sure you do not exceed the maximum number of properties allowed for a give
     data type. For information about the limits on the number of properties for each data type,
     see Load Data Source Data Schema and Sample Input. If you find that you need more than
     the maximum number of string (Edm.String) properties, consider the following options.
        Remove unnecessary or redundant properties.
        Convert a property with 'yes' and 'no' string values to a Boolean property with true and
          false values.
        Combine two or more string properties into a single string property by using a secondary
          delimiter, such as a dash (-).For example, if your entity data included an opening and
          closing time and you do not need to query on these values separately, you could
          combine them into a single string, such as '8:00 – 5:00'. If you needed to separate these
          values for a web application, use client-side parsing.
          If you are using XML to format your entity data, you can also use the pipe (|) character as
          a delimiter.
        Consider converting numeric information such as phone numbers to an integer property.
          Note that a leading 0 in a number will not be stored in this scenario. However, you can


                                                                                                     130
             accommodate for this if all the numbers are the same length. Also, if a number is not
             provided, the default value of zero (0) is stored.
       Make sure you specify a primary key in your data schema and that each set of entity data has
         a unique primary key value.
       Do not use 'Entity' as a property name. 'Entity' is a reserved word and cannot be used as
         a property name.
       Make sure latitude and longitude properties are included in the data schema. The
         latitude and longitude properties do not count towards the maximum number of properties
         with a data type of double (Edm.Double).
       Do not store HTML with entity data. HTML tags cannot be stored as entity data. If an entity
         value is used in the HTML of a web application, you can store the value in the data source,
         and then generate the HTML by using client-side processing. For example, you can store the
         URL for an image as entity data and then build the HTML image using client-side code.
       When possible, reduce the resolution of latitude and longitude values to six decimal
         places or less. This reduces the size of a data source query and reduces the response size.
         The response download time can be noticeable with mobile applications.

Load Data Source Dataflow Sample Code (C#)
The following C# code shows how to upload entity data to a data source by using the Load Data
Source Dataflow. The code is provided in two parts. The first code sample creates a Load Data
Source Dataflow job and monitors the job status. The second code sample provides general
classes that support these operations.
Classes that upload spatial data and check the status of a Load Data Source Dataflow job


using System;

using System.IO;

using System.Net;

using System.Text;

using System.Threading;

using BingMapsCsExamples.Properties;

namespace BingMapsCsExamples.Examples.Phase2

{

     class SpatialDataUploading: ExamplesBase

     {



         /// <summary>

         /// Upload spatial data to Bing Spatial Data Services

         /// and wait for job completion (or timeout).

         /// </summary>

                                                                                                     131
   public void UploadSpatialDataAndWaitForCompletion()

   {

       Console.WriteLine("Uploading spatial data...");

       string statusUrl = UploadSpatialData();

       Console.WriteLine("Spatial DataflowJob status URL: " + statusUrl);

       Console.WriteLine("Waiting for job completion...");

       string location = QueryDataflowJobStatus(statusUrl, 180);

       Console.WriteLine("Spatial Data location: " + statusUrl);

   }



   /// <summary>

   /// Bing Maps REST examples of uploading data to Spatial Data Services (SDS).

   /// </summary>

   /// <returns>The URL of the DataflowJob, with master key,

   /// that can be used to query status.</returns>

   public string UploadSpatialData()

   {

       //
http://spatial.virtualearth.net/REST/v1/Dataflows/LoadDataSource?dataSourceName=MyShopsSa
mple&loadOperation=complete&input=xml&output=xml&key=masterKey



       // Custom name of spatial data source created during upload.

       string dataSourceName = "MyShopsSample";

       // Path to the spatial data input file to be uploaded.

       string dataFilePath = @".\Data\SpatialDataUploadExampleData1.xml";

       // The master key used for uploading to Spatial Data Services.

       // This key should differ from your query key.

       string bingMapsMasterKey = Settings.Default.BingMapsMasterKey;

       // Create the spatial data upload URL.

       StringBuilder queryStringBuilder = new StringBuilder();

       queryStringBuilder.Append("dataSourceName=");

       queryStringBuilder.Append(Uri.EscapeUriString(dataSourceName));

       queryStringBuilder.Append("&loadOperation=complete");

       // Use xml input and output for the spatial data.


                                                                                      132
     // You could use any of: xml, csv, tab, or pipe.

     queryStringBuilder.Append("&input=xml");

     queryStringBuilder.Append("&output=xml");

     queryStringBuilder.Append("&key=");

     queryStringBuilder.Append(Uri.EscapeUriString(bingMapsMasterKey));

     UriBuilder uriBuilder = new UriBuilder("http://spatial.virtualearth.net");

     uriBuilder.Path = "/REST/v1/Dataflows/LoadDataSource";

     uriBuilder.Query = queryStringBuilder.ToString();

     // Create the request object. HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(uriBuilder.Uri);

     // The HTTP method must be 'POST'.

     request.Method = "POST";

     request.ContentType = "application/xml";

     // Write the request body with the

     // spatial data XML file contents (schema and data).

     using(FileStream dataStream = File.OpenRead(dataFilePath))

     {

         using(Stream requestStream = request.GetRequestStream())

         {

             byte[] buffer = new byte[16384];

             int bytesRead = dataStream.Read(buffer, 0, buffer.Length);

             while (bytesRead > 0)

             {

                 requestStream.Write(buffer, 0, bytesRead);

                 bytesRead = dataStream.Read(buffer, 0, buffer.Length);

             }

         }

     }

     string dataflowJobUrl = null;



     // Submit the HTTP request and check if the

     // job was created successfully.

     using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())

     {


                                                                                  133
        // // If the job was created successfully, the status code should be

        // 201 (Created) and the 'Location' header should contain a URL

        // that defines the location of the new dataflow job. You use this

        // URL with the Bing Maps Key to query the status of your job.

        //

        if (response.StatusCode != HttpStatusCode.Created)

         throw new Exception("An HTTP error status code was " +

             "encountered when creating the geocode job.");

        dataflowJobUrl = response.GetResponseHeader("Location");

        if (String.IsNullOrEmpty(dataflowJobUrl))

         throw new Exception("The 'Location' header is " +

             "missing from the HTTP response " + "when creating a geocode job.");

    }

    string jobStatusQueryUrl = string.Format("{0}?key={1}", dataflowJobUrl,

        Uri.EscapeUriString(bingMapsMasterKey));

    Console.WriteLine("Upload job location = " + dataflowJobUrl);



    return jobStatusQueryUrl;

}



/// <summary>

/// Bing Maps REST example of querying a

/// Spatial Data Services DataflowJob status.

/// Blocks the calling thread until the DataflowJob

/// completes or until a timeout is reached.

/// </summary>

/// <param name="jobStatusQueryUrl">The URL used to query

/// the upload job status.

/// Must contain your Bing Maps Key

/// as a query parameter.</param>

/// <returns>The URL of the uploaded data flow.</returns>

/// <exception cref="Exception">On upload

/// error or timeout.</exception>

public string QueryDataflowJobStatus(string jobStatusQueryUrl, int

                                                                                    134
    timeoutInSeconds)

{

    // int timeoutInSeconds = 120;

    string dataSourceUrl = null;

    const int secondsBetweenPolls = 5;

    int maxCount = timeoutInSeconds / secondsBetweenPolls;

    if (maxCount < 1)

    {

        maxCount = 1;

    }

    for (int checkCounter = 0; checkCounter < maxCount; ++checkCounter)

    {

        Console.WriteLine("Querying job status: " + jobStatusQueryUrl);

        // Check the job status by making a

        // request to the job status URL.

        BingMapsRestV1.Response jsonResponse = GetJsonResponse

            (jobStatusQueryUrl);

        BingMapsRestV1.DataflowJob job =

            jsonResponse.ResourceSets[0].Resources[0] as

            BingMapsRestV1.DataflowJob;

        if (job.Status == "Completed")

        {

            foreach (BingMapsRestV1.Link link in job.Links)

            {

                if (link.Role == "dataSource")

                {



                    // There can be multiple data source

                    // links but for this example,

                    // we just use the first link.

                    dataSourceUrl = link.Url;

                    break;

                }

            }

                                                                          135
                    break;

                }

                else if (job.Status == "Aborted")

                {

                    throw new Exception("The spatial data upload " +

                     "failed with status: " + job.Status + " Job location: " +

                     jobStatusQueryUrl + " Error message: " + job.ErrorMessge);

                }

                // Job status is "Pending" or otherwise incomplete.

                // Wait to poll the job status again.

                Thread.Sleep(secondsBetweenPolls * 1000);

            }

            if (string.IsNullOrEmpty(dataSourceUrl))

            {

                throw new Exception("Timed out or otherwise failed to " +

                    "find the dataSource link in the data flow job. " + " Job location: "

                    + jobStatusQueryUrl);

            }

            return dataSourceUrl;

        }

    }

}

Support Classes


using System;

using System.IO;

using System.Net;

using System.Runtime.Serialization.Json;

using System.Xml;

using BingMapsCsExamples.Helpers;

using BingMapsCsExamples.Properties;

namespace BingMapsCsExamples.Examples

{




                                                                                            136
/// <summary> /// Base class containing functionality common across the examples,

/// such as JSON and XML response processing.

/// </summary> public abstract class ExamplesBase



{

    #region Static members

    /// <summary>

    /// Your Bing Maps Key. You can either replace the value

    /// here or you can add a Settings value to your project.

    /// </summary> protected static string BingMapsKey = Settings.Default.BingMapsKey;

    /// <summary> /// Send the request to the Bing Maps REST API

    /// and deserialize the JSON response.

    /// </summary>

    public static BingMapsRestV1.Response GetJsonResponse(string requestUrl)

    {

        System.Diagnostics.Trace.WriteLine("Request URL (JSON): " + requestUrl);

        HttpWebRequest request = WebRequest.Create(requestUrl)as HttpWebRequest;

        using(HttpWebResponse response = request.GetResponse()as HttpWebResponse)

        {

            if (response.StatusCode != HttpStatusCode.OK)

             throw new Exception(String.Format("Server error (HTTP {0}: {1}).",

               response.StatusCode, response.StatusDescription));

            DataContractJsonSerializer jsonSerializer = new

             DataContractJsonSerializer(typeof(BingMapsRestV1.Response));

            object objResponse = jsonSerializer.ReadObject

             (response.GetResponseStream());

            BingMapsRestV1.Response jsonResponse = objResponse as

             BingMapsRestV1.Response;

            return jsonResponse;

        }

    }



    /// <summary>

    /// Send the request to the Bing Maps REST API and deserialize the XML response.

                                                                                         137
        /// </summary>

        public static XmlDocument GetXmlResponse(string requestUrl)

        {

            System.Diagnostics.Trace.WriteLine("Request URL (XML): " + requestUrl);

            HttpWebRequest request = WebRequest.Create(requestUrl)as HttpWebRequest;

            using(HttpWebResponse response = request.GetResponse()as HttpWebResponse)

            {

                if (response.StatusCode != HttpStatusCode.OK)

                 throw new Exception(String.Format("Server error (HTTP {0}: {1}).",

                   response.StatusCode, response.StatusDescription));

                XmlDocument xmlDoc = new XmlDocument();

                xmlDoc.Load(response.GetResponseStream());

                TraceXmlDocument(xmlDoc);

                return xmlDoc;

            }

        }



        /// <summary>

        /// Write an XML document to Diagnostics.Trace.

        /// </summary>

        private static void TraceXmlDocument(XmlDocument xmlDoc)

        {

            StringWriter sw = new StringWriter();

            XmlTextWriter xw = new XmlTextWriter(sw);

            xmlDoc.WriteTo(xw);

            System.Diagnostics.Trace.WriteLine(sw.ToString());

        }



        #endregion

    }



}




                                                                                        138
Load Data Source Dataflow Sample Code (VB)
The following Visual Basic code shows how to upload entity data to a data source by using the
Load Data Source Dataflow. The code is provided in two parts. The first code sample creates a
Load Data Source Dataflow job and monitors the job status. The second code sample provides
general classes that support these operations.
Classes that upload spatial data and check the status of a Load Data Source Dataflow job


Imports System

Imports System.Collections.Generic

Imports System.Linq

Imports System.Text

Imports BingMapsMigrationCsExamples.Properties

Imports System.IO

Imports System.Net

64

Imports System.Xml

Imports System.Threading

Imports System.Runtime.Serialization

Imports System.Runtime.Serialization.Json

Imports BingMapsMigrationCsExamples



Class SpatialDataUploading

     Inherits ExamplesBase

     #Region

     Imports System.Xml

     Imports System.Threading

     Imports System.Runtime.Serialization

     Imports System.Runtime.Serialization.Json

     Imports BingMapsMigrationCsExamples



     Class SpatialDataUploading

        Inherits ExamplesBase

        #Region "Spatial Data Upload"

        ''' <summary>

        ''' Bing Maps REST examples of uploading data to Spatial Data Services (SDS).

                                                                                            139
        ''' </summary>

        ''' <returns>The URL of the DataflowJob, with master key,

        ''' that can be used to query status.</returns>



        Public Function UploadSpatialData() As String

           '
http://spatial.virtualearth.net/REST/v1/Dataflows/LoadDataSource?dataSourceName=MyShopsSa
mple&loadOperation=complete&input=xml&output=xml&key=masterKey

           ' Custom name of spatial data source created during upload.

           Dim dataSourceName As String = "MyShopsSample"

           ' Path to the spatial data input file to be uploaded.

           Dim dataFilePath As String = ".\Data\SpatialDataUploadExampleData1.xml"

           ' The master key used for uploading to Spatial Data Services.

           ' This key should differ from your query key.

           Dim bingMapsMasterKey As String = "TODO Replace with your Bing Maps Master
Key."

           ' Create the spatial data upload URL.

           Dim queryStringBuilder As New StringBuilder()

           queryStringBuilder.Append("dataSourceName=")

           queryStringBuilder.Append(Uri.EscapeUriString(dataSourceName))

           queryStringBuilder.Append("&loadOperation=complete")

           ' Use xml input and output for the spatial data.

           queryStringBuilder.Append("&input=xml")

           queryStringBuilder.Append("&output=xml")

           queryStringBuilder.Append("&key=")

           queryStringBuilder.Append(Uri.EscapeUriString(bingMapsMasterKey))

           Dim uriBuilder As New UriBuilder("http://spatial.virtualearth.net")

           uriBuilder.Path = "/REST/v1/Dataflows/LoadDataSource"

           uriBuilder.Query = queryStringBuilder.ToString()

           Dim dataflowJobUrl As String = Nothing

           Using dataStream As FileStream = File.OpenRead(dataFilePath)

           Dim request As HttpWebRequest = DirectCast(WebRequest.Create(uriBuilder.Uri),
HttpWebRequest)

           '



                                                                                        140
           ' The HTTP method must be 'POST'.

           '

           request.Method = "POST"

           request.ContentType = "application/xml"

           Using requestStream As Stream = request.GetRequestStream()

           Dim buffer As Byte() = New Byte(16383) {}

           Dim bytesRead As Integer = dataStream.Read(buffer, 0, buffer.Length)

           While bytesRead > 0

               requestStream.Write(buffer, 0, bytesRead)

               bytesRead = dataStream.Read(buffer, 0, buffer.Length)

           End While

           End Using

           ' Submit the HTTP request and check if the

           ' job was created successfully.

           Using response As HttpWebResponse = DirectCast(request.GetResponse(),
HttpWebResponse)

           '

           ' If the job was created successfully, the status code should be

           ' 201 (Created) and the 'Location' header should contain a URL

           ' that defines the location of the new dataflow job. You use this

           ' URL with the Bing Maps Key to query the status of your job.

           '

           If response.StatusCode <> HttpStatusCode.Created Then

               Throw New Exception("An HTTP error status code was " + "encountered when
creating the geocode job.")

           End If

           dataflowJobUrl = response.GetResponseHeader("Location")

           If [String].IsNullOrEmpty(dataflowJobUrl) Then

               Throw New Exception("The 'Location' header is " + "missing from the HTTP
response " + "when creating a geocode job.")

           End If

           End Using

           End Using

           Console.WriteLine("Upload job location = " + dataflowJobUrl)


                                                                                     141
            Dim jobStatusQueryUrl As String = String.Format("{0}?key={1}",
dataflowJobUrl, Uri.EscapeUriString(bingMapsMasterKey))

            Return jobStatusQueryUrl

       End Function



       ''' <summary>

       ''' Bing Maps REST example of querying a

       ''' Spatial Data Services DataflowJob status.

       ''' Blocks the calling thread until the DataflowJob

       ''' completes or until a timeout is reached.

       ''' </summary>

       ''' <param name="jobStatusQueryUrl">The URL used to query

       66

       ''' the upload job status.

       ''' Must contain your Bing Maps Key

       ''' as a query parameter.</param>

       ''' <returns>The URL of the uploaded data flow.</returns>

       ''' <exception cref="Exception">On upload

       ''' error or timeout.</exception>



       Public Function QueryDataflowJobStatus(ByVal jobStatusQueryUrl As String, ByVal
timeoutInSeconds As Integer) As String

            Dim dataSourceUrl As String = Nothing

            Const secondsBetweenPolls As Integer = 5

            Dim maxCount As Integer = timeoutInSeconds / secondsBetweenPolls

            If maxCount < 1 Then

               maxCount = 1

            End If

            For checkCounter As Integer = 0 To maxCount - 1

               Console.WriteLine("Querying job status: " + jobStatusQueryUrl)

               ' Check the job status by making a

               ' request to the job status URL.

               Dim jsonResponse As BingMapsRestV1.Response =
GetJsonResponse(jobStatusQueryUrl)


                                                                                     142
                 Dim job As BingMapsRestV1.DataflowJob =
TryCast(jsonResponse.ResourceSets(0).Resources(0), BingMapsRestV1.DataflowJob)

                 If job.Status = "Completed" Then

                      For Each link As BingMapsRestV1.Link In job.Links

                             If link.Role = "dataSource" Then

                                 ' There can be multiple data source

                                 ' links but for this example,

                                 ' we just use the first link.

                                 dataSourceUrl = link.Url

                                 Exit For

                             End If

                      Next

                      Exit For

                 ElseIf job.Status = "Aborted" Then

                      Throw New Exception("The spatial data upload " + "failed with status:
" + job.Status + " Job location: " + jobStatusQueryUrl + " Error message: " +
job.ErrorMessge)

                 End If

                 ' Job status is "Pending" or otherwise incomplete.

                 ' Wait to poll the job status again.

                 Thread.Sleep(secondsBetweenPolls * 1000)

           Next

           If String.IsNullOrEmpty(dataSourceUrl) Then

                 Throw New Exception("Timed out or otherwise failed to " + "find the
dataSource link in the data flow job. " + " Job location: " + jobStatusQueryUrl)

                 67

           End If

           Return dataSourceUrl

       End Function



       #End Region

   End Class

Support Classes


Imports System

                                                                                        143
Imports System.Collections.Generic

Imports System.Windows.Media.Imaging

Imports System.Text

Imports System.Net

Imports System.Xml

Imports System.Runtime.Serialization.Json

Imports BingMapsMigrationCsExamples.BingMapsRestV1

Imports BingMapsMigrationCsExamples.Properties

Imports BingMapsMigrationCsExamples.Helpers

Imports BingMapsMigrationCsExamples



''' <summary>

''' Base class containing the functionality common for all examples.

''' </summary>

Public MustInherit Class ExamplesBase

   #Region "Constants"

       Private Shared BingMapsKey As String = "TODO Replace with your BingMapsKey"

   #End Region



   #Region "Static members"

   ''' <summary>

   ''' Send the request to the Bing Maps REST API

   ''' and deserialize the JSON response.

   ''' </summary>

   Public Shared Function GetJsonResponse(ByVal requestUrl As String) As
BingMapsRestV1.Response

       Dim request As HttpWebRequest = TryCast(WebRequest.Create(requestUrl),
HttpWebRequest)

       Using response As HttpWebResponse = TryCast(request.GetResponse(),
HttpWebResponse)

       If response.StatusCode <> HttpStatusCode.OK Then

           Throw New Exception([String].Format("Server error (HTTP {0}: {1}).",
response.StatusCode, response.StatusDescription))

       End If



                                                                                     144
       Dim jsonSerializer As New
DataContractJsonSerializer(GetType(BingMapsRestV1.Response))

       Dim objResponse As Object =
jsonSerializer.ReadObject(response.GetResponseStream())

       Dim jsonResponse As BingMapsRestV1.Response = TryCast(objResponse,
BingMapsRestV1.Response)

       Return jsonResponse

       End Using

   End Function



   ''' <summary>

   ''' Send the request to the Bing Maps REST API and deserialize the XML response.

   ''' </summary>

   Public Shared Function GetXmlResponse(ByVal requestUrl As String) As XmlDocument

       Dim request As HttpWebRequest = TryCast(WebRequest.Create(requestUrl),
HttpWebRequest)

       Using response As HttpWebResponse = TryCast(request.GetResponse(),
HttpWebResponse)

       If response.StatusCode <> HttpStatusCode.OK Then

            Throw New Exception([String].Format("Server error (HTTP {0}: {1}).",
response.StatusCode, response.StatusDescription))

       End If

       Dim xmlDoc As New XmlDocument()

       xmlDoc.Load(response.GetResponseStream())

       Return xmlDoc

       End Using

   End Function



   #End Region



   #Region "Instance members"

       Protected imageLoader As New MapImageLoader()

   #End Region

End Class



                                                                                      145
Get Data Source Information
Use the following URLs to get information about one or more data sources.

Supported HTTP Methods
GET

URL templates
Get information about all data sources that belong to a Bing Maps Account.
The response returned by this URL is an AtomPub service document that contains the date and
time that the each data source was last updated and the names of the data sources. When the
$format query option is set to atom, which is the default value, the base URLs to use to query the
data sources are also provided. For more information about the response and AtomPub service
documents, see the Response and Example sections following the table of parameters.
The key parameter in this URL is set to any Bing Maps Key that belongs to the Bing Maps
Account.
http://spatial.virtualearth.net/REST/v1/data?$format=formatQueryOption&key=anyAccountKey



Get information about a specific data source.
The response returned by this URL is an AtomPub service document that contains the date and
time that the data source was last updated and the name of the data source. When the $format
query option is set to atom, which is the default value, the base URL to use to query the data
source is also provided.
The base part of the following URL with accessID and dataSourceName is returned when you
create the data source. It is also returned when you request information for all data sources that
belong to a Bing Maps Account. This base URL is unique for each data source and is used to get
information about the datasource, such as entity types and properties. It is also used to query the
data source. For more information about the response and AtomPub service documents, see the
Response and Example sections following the table of parameters.
The key parameter in this URL can be set to the data source master key or any Bing Maps Key
that belongs to the same Bing Maps Account.
http://spatial.virtualearth.net/REST/v1/data/accessID/dataSourceName?$format=formatQueryO
ption&key=anyAccountKey

Get the metadata for all data sources that belong to a Bing Maps Account.
The response returned by this URL is an OData Service Metadata Document, which describes
the entity types and properties for all of the data sources that belong to a Bing Maps Account. For
more information about the response and OData Service Metadata Documents, see the
Response and Example sections following the table of parameters.
The key parameter in this URL is set to any Bing Maps Key that belongs to the Bing Maps
Account.
http://spatial.virtualearth.net/REST/v1/data/$metadata?key=anyAccountKey


                                                                                               146
Get the metadata for a single data source.
The response returned by this URL is an OData Service Metadata Document, which describes
the entity types and properties for the data source. For more information about the response and
OData Service Metadata Documents, see the Response and Example sections following the
table of parameters.
The key parameter in this URL can be set to the data source master key or any Bing Maps Key
that belongs to the same Bing Maps Account.
http://spatial.virtualearth.net/REST/v1/data/accessID/dataSourceName/$metadata?key=anyAcc
ountKey

Template Parameters


      Parameter names and values are not case-sensitive except for the key parameter value.


Parameter                    Description           Values

accessId                     Required. A unique A string containing and ID that is part of the
                             ID for the data    URL structure that identifies the data source.
                             source.            Example:
                                                a92dcfac8a0894bc4921ad5c74022623.

dataSourceName               Required The          A string that identifies the data source. The
                             name of the data      name is part of the URL structure that identifies
                             source that you       the data source.
                             want to search.       Example: FourthCoffeeSample

entityTypeName               Required The          A string that specifies the entity type for the
                             entity type to        data source.
                             search for in the     Example: FourthCoffeeShops
                             data source.

formatQueryOption            Optional. Specifies   One of the following values:
                             the format of the        atom [default]
                             response. The            json
                             supported formats
                                                   Example: $format=json
                             are Atom and
                             JSON.

key                          Required. A Bing      One of the Bing Maps Keys that is belongs to
                             Maps Key that         the Bing Maps Account that manages the data
                             belongs to the Bing   source(s).
                             Maps Account that     If you are requesting information about a single
                             manages the data      data source, you can also use the data source
                             source(s).            master key.

                                                                                                     147
Parameter                       Description        Values
                                                   Example:
                                                   key=abc123def456ghi789abc123def456ghi789


Response
These URLs supports the following response formats. You can specify the format to return by
setting the $format query option. For more information, see Query Options.
    Atom (application/atomsvc + xml) [default]
    JSON (application/json)
      Note: You cannot request JSON format for your response when you request data source
      metadata.
The response to the URLs that get information about one or more data sources that belong to a
Bing Maps Account is an Atom Publishing Protocol (AtomPub) service document. The AtomPub
service document contains the data source information that you requested. The Atom Publishing
Protocol (AtomPub) is a protocol that applications can use to publish and edit web resources. The
AtomPub service document for this response uses the style defined in the Atom Publishing
Protocol:Data Services URI and Payload Extensions specification. For specific information about
the JSON response format, see the OData JSON Service Document section of this document.
The Atom Publishing Protocol:Data Services URI and Payload Extensions specification defines
an extension of the Atom Publishing Protocol for REST services.
The response to the URL that gets metadata for a data source is an OData Service Metadata
Document. This document describes the entity types and properties for that data source by using
the Entity Data Model and the Conceptual Schema Data Language (CSDL). For more
information, see Service Metadata Document section of the Open Data Protocol.

Examples
EXAMPLE: Get information on all data sources the belong to a Bing Maps Account.
The following example shows how to request information about all data sources that belong to a
Bing Maps Account. The key parameter must be set to a Bing Maps Key that belongs to the Bing
Maps Account.
URL with Atom Response
http://spatial.virtualearth.net/REST/v1/data?key=anyAccountKey

The following response provides two unique URLs that represent two data sources that belong to
a Bing Maps Account. You can use these URLs to query the data sources.
<app:service xmlns:app="http://www.w3.org/2007/app"

                     xmlns:atom="http://www.w3.org/2005/Atom"

                     xmlns:bsi="http://schemas.microsoft.com/bing/spatial/2010/11/odata">

     <bsi:copyright>© 2011 Microsoft and its suppliers.     This API and any results cannot be
used or accessed without Microsoft’s express written permission.</bsi:copyright>

                                                                                              148
    <app:workspace bsi:updated="2008-04-10T06:30:00-07:00">

     <atom:title>FourthCoffeeSample</atom:title>

     <app:collection
app:href="https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/
FourthCoffeeSample/FourthCoffeeStores">

       <atom:title>FourthCoffeeStores</atom:title>

     </app:collection>

    </app:workspace>

    <app:workspace bsi:updated="2008-04-10T06:30:00-07:00">

     <atom:title>Transit</atom:title>

     <app:collection
app:href="https://spatial.virtualearth.net/REST/v1/data/123abc456deffed654cbc32131213411/
Transit/Stops">

       <atom:title>Stops</atom:title>

     </app:collection>

    </app:workspace>

</app:service>



URL with JSON Response
http://spatial.virtualearth.net/REST/v1/data?$format=json&key=anyAccountKey

{

    "d":{

       "Copyright":"© 2011 Microsoft and its suppliers.       This API and any results cannot b
e used or accessed without Microsoft’s express written permission.",

       "DataSources":[

            {

                 "Name":"FourthCoffeeSample",

                 "Updated":"Thu, 10 Apr 2008 13:30:00 GMT",

                 "EntitySets":[

                     "FourthCoffeeShops"

                 ]

            },

            {

                 "Name":"Transit",

                 "Updated":"Thu, 10 Apr 2008 13:30:00 GMT",

                                                                                            149
                "EntitySets":[

                    "Stops"

                ]

            }

        ]

    }

}




EXAMPLE: Get general information about a specific data source.
The following example shows how to request information for a specific data source. The key
parameter must be set to the master key of the data source or any Bing Maps Key that belongs to
the Bing Maps Account that contains the data source.
URL with Atom Response
The following response provides a URL that you can use to query data source.
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample?key=anyAccountKey

<app:service xmlns:app="http://www.w3.org/2007/app"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:bsi="http://schemas.microsoft.com/bing/spatial/2010/11/odata">

    <bsi:copyright>© 2011 Microsoft and its suppliers.   This API and any results cannot be
used or accessed without Microsoft’s express written permission.</bsi:copyright><

    <app:workspace>

     <atom:title>FourthCoffeeSample</atom:title>

     <app:collection
app:href="https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/
FourthCoffeeSample/FourthCoffeeShops" bsi:updated="2008-04-10T06:30:00-07:00">

        <atom:title>FourthCoffeeShops</atom:title>

     </app:collection>

    </app:workspace>

</app:service>



URL with JSON response
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample?$format=json&key=anyAccountKey


                                                                                           150
{

    "d":{

        "Copyright":"© 2011 Microsoft and its suppliers.     This API and any results cannot b
e used or accessed without Microsoft’s express written permission.",

        "Name":"FourthCoffeeSample",

        "Updated":"Thu, 10 Apr 2008 13:30:00 GMT",

        "EntitySets":[

            "FourthCoffeeShops"

        ]

    }

}




EXAMPLE: Get metadata for a specific data source.
The following example shows how to request metadata for a specific data source. Metadata
includes the entity types for the data source and their corresponding properties. The key
parameter must be set to the data source master key or to any Bing Maps Key that belongs to the
Bing Maps Account that contains the data source.
URL with Atom Response
Atom is the only supported response type when you request metadata.
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/$metadata?key=anyAccountKey

<edmx:Edmx xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx"
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" Version="1.0">

    <edmx:DataServices DataServiceVersion="1.0">

     <Schema Namespace="FourthCoffeeSampleDataSource"
xmlns="http://schemas.microsoft.com/ado/2008/09/edm">

        <EntityType Name="FourthCoffeeShops">

            <Key>

             <PropertyRef Name="EntityID" />

            </Key>

            <Property Name="EntityID" Type="Edm.String" Nullable="false" MaxLength="2560"
Unicode="true" FixedLength="false" />

            <Property Name="Latitude" Type="Edm.Double"/>

            <Property Name="Longitude" Type="Edm.Double"/>


                                                                                            151
       <Property Name="AddressLine" Type="Edm.String" Nullable="true" MaxLength="2560"
Unicode="true" FixedLength="false" />

       <Property Name="PrimaryCity" Type="Edm.String" Nullable="true" MaxLength="2560"
Unicode="true" FixedLength="false" />

       <Property Name="Subdivision" Type="Edm.String" Nullable="true" MaxLength="2560"
Unicode="true" FixedLength="false" />

       <Property Name="PostalCode" Type="Edm.String" Nullable="true" MaxLength="2560"
Unicode="true" FixedLength="false" />

       <Property Name="Phone" Type="Edm.String" Nullable="true" MaxLength="2560"
Unicode="true" FixedLength="false" />

       <Property Name="SecondaryCity" Type="Edm.String" Nullable="true" MaxLength="2560"
Unicode="true" FixedLength="false" />

       <Property Name="CountryRegion" Type="Edm.String" Nullable="true" MaxLength="2560"
Unicode="true" FixedLength="false" />

       <Property Name="Name" Type="Edm.String" Nullable="true" MaxLength="2560"
Unicode="true" FixedLength="false" />

       <Property Name="DisplayName" Type="Edm.String" Nullable="true" MaxLength="2560"
Unicode="true" FixedLength="false" />

       <Property Name="Manager" Type="Edm.String" Nullable="true" MaxLength="2560"
Unicode="true" FixedLength="false" />

       <Property Name="StoreOpen" Type="Edm.String" Nullable="true" MaxLength="2560"
Unicode="true" FixedLength="false" />

       <Property Name="StoreType" Type="Edm.String" Nullable="true" MaxLength="2560"
Unicode="true" FixedLength="false" />

       <Property Name="SeatingCapacity" Type="Edm.Int64" Nullable="true" />

       <Property Name="Open" Type="Edm.Int64" Nullable="true" />

       <Property Name="Close" Type="Edm.Int64" Nullable="true" />

       <Property Name="IsWiFiHotSpot" Type="Edm.Boolean" Nullable="true" />

       <Property Name="IsWheelchairAccessible" Type="Edm.Boolean" Nullable="true" />

       <Property Name="AcceptsOnlineOrders" Type="Edm.Boolean" Nullable="true" />

       <Property Name="AcceptsCoffeeCards" Type="Edm.Boolean" Nullable="true" />

       <Property Name="CreatedDate" Type="Edm.DateTime" Nullable="true" />

       <Property Name="LastUpdatedDate" Type="Edm.DateTime" Nullable="true" />

     </EntityType>

   </Schema>



                                                                                        152
      <Schema Namespace="FourthCoffeeSample"
xmlns="http://schemas.microsoft.com/ado/2008/09/edm">

        <EntityContainer Name="FourthCoffeeSampleContext"
m:IsDefaultEntityContainer="true">

            <EntitySet Name="FourthCoffeeShops"
EntityType="FourthCoffeeSampleDataSource.FourthCoffeeShops" />

        </EntityContainer>

      </Schema>

     </edmx:DataServices>

</edmx:Edmx>




HTTP Status Codes


      For more details about these HTTP status codes, see Status Codes and Errors.
When the request is successful, the following HTTP status code is returned.
    201
When the request is not successful, the response returns one of the following errors.
    400
    401
    500
    503


Data Source Download Dataflow
The Data Source Download Dataflow API is a component of the Bing Spatial Data Services. You
can use the Data Source Download Dataflow API to download entity data from a published data
source.


      To use the Data Source Download Dataflow, you must have access to Bing Spatial Data
      Services. If you would like to request access to Bing Spatial Data Services, email
      MAPLIC@microsoft.com with your Bing Maps Account ID and (for publicly-accessible
      sites) top level domains. You must email this request from the email account associated
      with your Bing Maps Account in the Bing Maps Account Center
      (http://www.bingmapsportal.com).
You can download a data source in three steps.
    Create a Download Job: Create a download job to download a published data source.
    Get Status of a Download Data Source Job: Monitor the job status to determine when the
      download is complete.

                                                                                                153
   Get Downloaded Data: Use the URL provided in the download status response to access the
     entity data that was downloaded from the data source.

In this Section


Create a Download Job                            Describes how to create a job to download
                                                 entity data from a data source.

Get Status of a Download Data Source Job         Describes how to request status for a download
                                                 data source job.

Get Downloaded Data                              Describes how to access the downloaded data.

Download Data Source Walkthrough                 Provides a step-by-step overview of how to use
                                                 the Download Data Source Dataflow.

Download Data Source Dataflow Response           Describes the data that comes back in the
Description                                      response.


Create a Download Job
Use the following URL to download entity data from a published data source.
Supported HTTP Methods
GET
URL template


     This template supports both HTTP and HTTPS protocols. URLs in the response use
     HTTPS protocol.
Download data source entity data.
This URL creates a DataSourceDownload job that downloads entity data for a data source.
http://spatial.virtualearth.net/REST/v1/Dataflows/DataSourceDownload/accessId/dataSourceN
ame?output=output&key=DataSourceMasterKey

After you create a download job, use the status URL provided in the response to check status.
For more information about the status URL, see the Examples section and Get Status of a
Download Data Source Job.
For a step-by-step description of how use the DataSourceDownload Dataflow to download entity
data, see Download Data Source Walkthrough.
Template Parameters


     Parameter names and values are not case sensitive except for the key parameter value.




                                                                                                154
Parameter             Alias     Description     Values

accessId                        Required. A     A string containing and ID that is part of the
                                unique ID for   URL structure that identifies the data source.
                                the data        You can retrieve the accessId and
                                source.         dataSourceName values when you get
                                                information about all datasources. For more
                                                information, see Get Data Source Information.
                                                Example:
                                                a92dcfac8a0894bc4921ad5c74022623.

dataSourceName                  Required The    A string that identifies the data source. The
                                name of the     name is part of the URL structure that
                                data source     identifies the data source.
                                that you want   You can retrieve the accessId and
                                to search.      dataSourceName values when you get
                                                information about all datasources. For more
                                                information, see Get Data Source Information.
                                                Example: MyDataSourceName

output                o         Optional. The   One of the following values:
                                output format      json [default]
                                for the            xml
                                response.
                                                Example: o=xml

key                             Required.       The Bing Maps Key that was specified as the
                                The master      master key when the data source was created.
                                key for the     Example:
                                data source.    key=abc123def456ghi789abc123def456ghi789


Response
This URL supports the following response formats.
    JSON: application/json
    XML: application/xml
For information about the response, see Download Data Source Dataflow Response Description.
Examples
EXAMPLE: Create a job to download entity data from a data source.
The following request example shows how to request a data source download job. The key
parameter must be set to the data source master key.
The response specifies a status URL that you can use to monitor the download job status. This
status URL is highlighted in the response examples below. See Get Status of a Download Data
Source Job to learn how to use the status URL to determine when the download job is complete.
                                                                                                155
http://spatial.virtualearth.net/REST/v1/data/DataSourceDownload/12ccc26d9e9412345f9492221
2345/ADataSourceName?o=xml&key=DataSourceMasterKey

XML Response
This URL will return a response similar to the following example.
<?xml version="1.0" encoding="utf-8"?>

<Response xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="https://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">

  <Copyright>Copyright © 2011 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.</Copyright>



<BrandLogoUri>http://spatial.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>

  <StatusCode>201</StatusCode>

  <StatusDescription>Created</StatusDescription>

  <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>

  <TraceId>0ddc1a3bd3dc46e28c92bb01942b0812</TraceId>

  <ResourceSets>

    <ResourceSet>

      <EstimatedTotal>1</EstimatedTotal>

      <Resources>

        <DataflowJob>

          <Id>8ccf2a5b428d423c92759150dcddc338</Id>

          <Link
role="self">https://spatial.virtualearth.net/REST/v1/dataflows/DataSourceDownload/8ccf2a5
b428d423c92759150dcddc338</Link>

          <Status>Pending</Status>

          <CreatedDate>2011-11-17T12:38:16.8179772-08:00</CreatedDate>

          <CompletedDate xsi:nil="true" />

          <TotalEntityCount>0</TotalEntityCount>

          <ProcessedEntityCount>0</ProcessedEntityCount>

          <FailedEntityCount>0</FailedEntityCount>

        </DataflowJob>

      </Resources>

                                                                                      156
     </ResourceSet>

    </ResourceSets>

</Response>



JSON Response
If o=xml was not specified in the response, a JSON response similar to the following example is
returned.
{

    "authenticationResultCode":"ValidCredentials",

    "brandLogoUri":"http:\/\/spatial.virtualearth.net\/Branding\/logo_powered_by.png",

    "copyright":"Copyright © 2011 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.",

    "resourceSets":[

       {

           "estimatedTotal":1,

           "resources":[

              {



"__type":"DataflowJob:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",

                  "id":"8ccf2a5b428d423c92759150dcddc338",

                  "links":[

                       {

                           "role":"self",



"url":"https:\/\/spatial.virtualearth.net\/REST\/v1\/dataflows\/DataSourceDownload\/8ccf2
a5b428d423c92759150dcddc338"

                       }

                  ],

                  "createdDate":"Thu, 17 Nov 2011 20:38:31 GMT",

                  "failedEntityCount":0,

                  "processedEntityCount":0,

                  "status":"Pending",

                  "totalEntityCount":0


                                                                                             157
                   }

               ]

          }

     ],

     "statusCode":201,

     "statusDescription":"Created",

     "traceId":"9bc6dede6e79468ba1cc3728aa7f1cb4"

}

HTTP Status Codes


     For more details about these HTTP status codes, see Status Codes and Errors.
When the request is successful, the following HTTP status code is returned.
   202
When the request is not successful, the response returns one of the following errors.
   400
   401
     This error code can occur in any of the following conditions:
            The key parameter is not specified.
            The specified key value is not a valid Bing Maps Key.
            The specified key is not the master key for the data source.
   404
            This error code can occur when the data source does not exist.
   500
   503

Get Status of a Download Data Source Job
Use the following URL to get the status of a download data source job.
Supported HTTP Methods
GET
URL template


     This template supports both HTTP and HTTPS protocols. URLs in the response use
     HTTPS protocol.
Get status information for a data source download job.
 A status URL in the following format without the output parameter and master key is provided in
the response to the URL request that you made to Create a Download Job. The status URL is


                                                                                             158
specified in a link field with an attribute of self. This URL with the data source master key
provides the status of the job.
http://spatial.virtualearth.net/REST/v1/Dataflows/DataSourceDownload/jobID?output=output&
key=DataSourceMasterKey

When the download job status is set to Completed, a download URL is included in the response.
For information about accessing downloaded entity data, see the Examples section below and
Get Downloaded Data.
For a step-by-step description of how use the Download Data Source Dataflow, see Download
Data Source Walkthrough.
Template Parameters


      Parameter names and values are not case-sensitive except for the key parameter value.


Parameter          Alias        Description         Values

jobID                           Required. The       When you request a dataflow job, the job ID is
                                ID of the job.      returned in the ID field of the response.
                                                    Example:
                                                    e14b1d9bd65c4b9d99d267bbb8102ccf

key                             Required. The       A Bing Maps Key that is the data source
                                data source         master key.
                                master key.         Example:
                                                    key=abc123def456ghi789abc123def456ghi789

output             o            Optional. The       One of the following values:
                                output format for   json [default]
                                the response.
                                                    xml
                                                    Example: o=xml


Response
This URL supports the following response formats.
    JSON: application/json
    XML: application/xml
For information about the response, see Download Data Source Dataflow Response Description.
Examples
This example requests status information in XML format for a download job with the specified job
ID. When the job status is complete, a download URL is included in the response that you can
use to download data. See Get Downloaded Data for more information. The example responses
are for a completed job and the download URL is highlighted.


                                                                                                159
http://spatial.virtualearth.net/REST/v1/Dataflows/DataSourceDownload/8ccf2a5b428d423c9275
9150dcddc338?o=xml&key=DataSourceMasterKey

XML Response
This URL will return a response similar to the following example.
<?xml version="1.0" encoding="utf-8"?>

<Response xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="https://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">

  <Copyright>Copyright © 2011 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.</Copyright>



<BrandLogoUri>http://spatial.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>

  <StatusCode>201</StatusCode>

  <StatusDescription>Created</StatusDescription>

  <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>

  <TraceId>0ddc1a3bd3dc46e28c92bb01942b0812</TraceId>

  <ResourceSets>

    <ResourceSet>

      <EstimatedTotal>1</EstimatedTotal>

      <Resources>

        <DataflowJob>

          <Id>8ccf2a5b428d423c92759150dcddc338</Id>

          <Link
role="self">https://spatial.virtualearth.net/REST/v1/dataflows/DataSourceDownload/8ccf2a5
b428d423c92759150dcddc338</Link>

          <Status>Completed</Status>

          <Link role="output"
name="succeeded">https://spatial.virtualearth.net/REST/v1/dataflows/DataSourceDownload/8c
cf2a5b428d423c92759150dcddc338/output/succeeded</Link>

          <CreatedDate>2011-11-17T12:50:08.8179772-08:00</CreatedDate>

          <CompletedDate xsi:nil="true" />

          <TotalEntityCount>300</TotalEntityCount>

          <ProcessedEntityCount>300</ProcessedEntityCount>

          <FailedEntityCount>0</FailedEntityCount>

                                                                                      160
           </DataflowJob>

       </Resources>

     </ResourceSet>

    </ResourceSets>

</Response>



JSON Response
If o=xml was not specified in the response, a JSON response similar to the following example is
returned.
{

    "authenticationResultCode":"ValidCredentials",

    "brandLogoUri":"http:\/\/spatial.virtualearth.net\/Branding\/logo_powered_by.png",

    "copyright":"Copyright © 2011 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.",

    "resourceSets":[

       {

           "estimatedTotal":1,

           "resources":[

              {



"__type":"DataflowJob:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",

                  "id":"8ccf2a5b428d423c92759150dcddc338",

                  "links":[

                      {

                           "role":"self",



"url":"https:\/\/spatial.virtualearth.net\/REST\/v1\/dataflows\/DataSourceDownload\/8ccf2
a5b428d423c92759150dcddc338"

                      },

                      {

                           "role":"output",

                           "output":"succeeded",




                                                                                             161
"url":"https:\/\/spatial.virtualearth.net\/REST\/v1\/dataflows\/DataSourceDownload\/8ccf2
a5b428d423c92759150dcddc338M\/ouput\/succeeded"

                           }



                      ],

                      "createdDate":"Thu, 17 Nov 2011 20:38:31 GMT",

                      "failedEntityCount":0,

                      "processedEntityCount":300,

                      "status":"Completed",

                      "totalEntityCount":300

                  }

              ]

          }

     ],

     "statusCode":201,

     "statusDescription":"Created",

     "traceId":"9bc6dede6e79468ba1cc3728aa7f1cb4"

}

HTTP Status Codes


     For more details about these HTTP status codes, see Status Codes and Errors.
When the request is successful, the following HTTP status code is returned.
   200
When the request is not successful, the response returns one of the following HTTP status codes.
   400
   500
   503

Get Downloaded Data
A download URL is returned in the job status response when download job has completed. Use
this download URL to access the downloaded entity data.
Your job has completed when the Status field in the response is set to Completed. The download
URL is specified as an XML Link value, or as part of a JSON links collection. These links have a
role attribute set to output and the name attribute and set to succeeded.

XML

                                                                                             162
<Link role="output"
name="succeeded">https://spatial.virtualearth.net/REST/v1/dataflows/Download/8ccf2a5b428d
423c92759150dcddc338/output/succeeded</Link>



JSON
"links":[

       {

           "name":"succeeded",

           "role":"output",

           "url":"https:\/\/spatial.virtualearth.net\/REST\/v1\/dataflows\/DataSourceDownlo
ad\/8ccf2a5b428d423c92759150dcddc338\/output\/succeeded"

       }

]



To download the entity data, you must add the master key for the data source to the download
URL.
https://spatial.virtualearth.net/REST/v1/dataflows/DataSourceDownload/8ccf2a5b428d423c927
59150dcddc338/output/succeeded?key=DataSourceMasterKey

Example of Downloaded Entity Data
The following shows and example of downloaded entity data.
<?xml version="1.0" encoding="UTF-8" ?>

<MainRoot>

    <xs:schema xmlns="" xmlns:xs="https://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="MyDataSourceName">

     <xs:element name="MyDataSourceName" msdata:IsDataSet="true"
msdata:UseCurrentLocale="true">

       <xs:complexType>

           <xs:choice minOccurs="0" maxOccurs="unbounded">

            <xs:element name="MyDataSourceEntityType">

              <xs:complexType>

                <xs:sequence>

                  <xs:element name="EntityID" type="xs:string" minOccurs="0"/>

                  <xs:element name="Latitude" type="xs:double" minOccurs="0"/>

                  <xs:element name="Longitude" type="xs:double" minOccurs="0"/>

                  <xs:element name="AddressLine" type="xs:string" minOccurs="0"/>


                                                                                           163
                <xs:element name="Locality" type="xs:string" minOccurs="0"/>

                <xs:element name="AdminDistrict" type="xs:string" minOccurs="0"/>

                <xs:element name="CountryRegion" type="xs:string" minOccurs="0"/>

                <xs:element name="PostalCode" type="xs:string" minOccurs="0"/>

                <xs:element name="Confidence" type="xs:string" minOccurs="0"/>

                <xs:element name="Phone" type="xs:string" minOccurs="0"/>

                <xs:element name="Open" type="xs:long" minOccurs="0"/>

                <xs:element name="Close" type="xs:long" minOccurs="0"/>

                <xs:element name="IsWheelchairAccessible" type="xs:boolean" minOccurs="0"
/>

              </xs:sequence>

            </xs:complexType>

          </xs:element>

        </xs:choice>

      </xs:complexType>

      <xs:unique name="Constraint1" msdata:PrimaryKey="true">

        <xs:selector xpath=".//MyDataSourceEntityType"/>

        <xs:field xpath="EntityID"/>

      </xs:unique>

     </xs:element>

 </xs:schema>

 <MyDataSourceEntityType>

     <EntityID>1</EntityID>

     <Latitude>47.673302</Latitude>

     <Longitude>-122.118576</Longitude>

     <AddressLine>1 Microsoft Way</AddressLine>

     <Locality>Redmond</Locality>

     <AdminDistrict>WA</AdminDistrict>

     <CountryRegion>United States</CountryRegion>

     <PostalCode>98052</PostalCode>

     <Confidence>High</Confidence>

     <Phone>303-555-0188</Phone>

     <Open>700</Open>

     <Close>1800</Close>


                                                                                      164
    <IsWheelchairAccessible>true</IsWheelchairAccessible>

  </MyDataSourceEntityType>

</MainRoot>

For information about the Download Data Source data schema, see Download Data Source
Dataflow Response Description.
For a step-by-step description of how use the Download Data Source Dataflow, see Download
Data Source Walkthrough.

Download Data Source Walkthrough
Use the DataSourceDownload API to download entity data for a published data source.


    Both HTTP and HTTPS protocols are supported.


Create the Download Data Source Job
To start the download process, create a DataSourceDownload URL request using the following
format.
https://spatial.virtualearth.net/REST/v1/Dataflows/DataSourceDownload/accessId/DataSource
Name?output=xml&key=DataSourceMasterKey

When you make the download request, the response provides the ID and status of the download
job, and a status URL. The status URL is specified in the Link element with the role attribute set
to self and contains the job ID. The ID and status URL fields are highlighted in the following
response example.
Note that the job status is set to Pending. Job status values include Pending, Completed and
Aborted. The next section describes how to use the status URL to monitor job status and to get
the location of the downloaded entity data.
<Response xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">

  <Copyright>Copyright © 2011 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.</Copyright>



<BrandLogoUri>http://spatial.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>

  <StatusCode>201</StatusCode>

  <StatusDescription>Created</StatusDescription>



                                                                                               165
  <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>

  <TraceId>b1aae77f9b9145ffa87d97d7d405cffd</TraceId>

  <ResourceSets>

    <ResourceSet>

      <EstimatedTotal>1</EstimatedTotal>

      <Resources>

         <DownloadJob>

           <Id>e14b1d9bd65c4b9d99d267bbb8102ccf</Id>

           <Link
role="self">https://spatial.virtualearth.net/REST/v1/dataflows/DataSourceDownload/e14b1d9
bd65c4b9d99d267bbb8102ccf</Link>

           <Description></Description>

           <Status>Pending</Status>

           <CreatedDate>2011-11-09T15:15:51.8326153-08:00</CreatedDate>

           <CompletedDate xsi:nil="true" />

           <TotalEntityCount>0</TotalEntityCount>

           <ProcessedEntityCount>0</ProcessedEntityCount>

           <FailedEntityCount>0</FailedEntityCount>

         </DataflowJob>

      </Resources>

    </ResourceSet>

  </ResourceSets>

</Response>

Check Job Status
To monitor the status of your download job, use the status URL described in the previous section
with your data source master key.
https://spatial.virtualearth.net/REST/v1/dataflows/DataSourceDownload/e14b1d9bd65c4b9d99d
267bbb8102ccf?output=xml&key=DataSourceMasterKey



When the status is set to Completed, a download URL appears in the response. The download
URL is specified as a Link field with the role attribute set to output and the name attribute set to
succeeded.

The following response shows that the job is completed and specifies a download URL. These
fields are highlighted. The next section describes the download data and how to access it.



                                                                                                   166
<Response xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">

 <Copyright>Copyright © 2011 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.</Copyright>



<BrandLogoUri>http://spatial.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>

 <StatusCode>200</StatusCode>

 <StatusDescription>OK</StatusDescription>

 <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>

 <TraceId>2a4fcb1fd1274497ab8ed84955012264</TraceId>

 <ResourceSets>

   <ResourceSet>

     <EstimatedTotal>1</EstimatedTotal>

     <Resources>

       <DataflowJob>

         <Id>e14b1d9bd65c4b9d99d267bbb8102ccf</Id>

         <Link
role="self">https://spatial.virtualearth.net/REST/v1/dataflows/DataSourceDownload/e14b1d9
bd65c4b9d99d267bbb8102ccf</Link>

         <Link role="output"
name="succeeded">https://spatial.virtualearth.net/REST/v1/dataflows/DataSourceDownload/e1
4b1d9bd65c4b9d99d267bbb8102ccf/output/succeeded</Link>

         <Description></Description>

         <Status>Completed</Status>

         <CreatedDate>2011-11-08T16:35:00.2429749-08:00</CreatedDate>

         <CompletedDate>2011-11-08T16:44:00.9349209-08:00</CompletedDate>

         <TotalEntityCount>2</TotalEntityCount>

         <ProcessedEntityCount>2</ProcessedEntityCount>

         <FailedEntityCount>0</FailedEntityCount>

       </DataflowJob>

     </Resources>


                                                                                      167
    </ResourceSet>

  </ResourceSets>

</Response>

If your job status is Aborted, then the job ended due to an error and an ErrorMessage element
appears in the response and contains error information.
Get the downloaded data
To access the downloaded entity data, use the download URL described in the previous section
with the data source master key.
https://spatial.virtualearth.net/REST/v1/

dataflows/DataSourceDownload/e14b1d9bd65c4b9d99d267bbb8102ccf/output/succeeded?key=DataSo
urceMasterKey

The downloaded data includes the data schema and a set of entity data that matches that
schema in XML format. XML is the only option for downloaded entity data.
The following sample data is an example of downloaded entity data.
<?xml version="1.0" encoding="UTF-8" ?>

<MainRoot>

  <xs:schema xmlns="" xmlns:xs="https://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="MyDataSourceName">

    <xs:element name="MyDataSourceName" msdata:IsDataSet="true"
msdata:UseCurrentLocale="true">

      <xs:complexType>

        <xs:choice minOccurs="0" maxOccurs="unbounded">

          <xs:element name="MyDataSourceEntityType">

              <xs:complexType>

                <xs:sequence>

                 <xs:element name="EntityID" type="xs:string" minOccurs="0"/>

                 <xs:element name="Latitude" type="xs:double" minOccurs="0"/>

                 <xs:element name="Longitude" type="xs:double" minOccurs="0"/>

                 <xs:element name="AddressLine" type="xs:string" minOccurs="0"/>

                 <xs:element name="Locality" type="xs:string" minOccurs="0"/>

                 <xs:element name="AdminDistrict" type="xs:string" minOccurs="0"/>

                 <xs:element name="CountryRegion" type="xs:string" minOccurs="0"/>

                 <xs:element name="PostalCode" type="xs:string" minOccurs="0"/>

                 <xs:element name="Confidence" type="xs:string" minOccurs="0"/>

                 <xs:element name="Phone" type="xs:string" minOccurs="0"/>


                                                                                                168
                <xs:element name="Open" type="xs:long" minOccurs="0"/>

                <xs:element name="Close" type="xs:long" minOccurs="0"/>

                <xs:element name="IsWheelchairAccessible" type="xs:boolean" minOccurs="0"
/>

              </xs:sequence>

            </xs:complexType>

          </xs:element>

        </xs:choice>

      </xs:complexType>

      <xs:unique name="Constraint1" msdata:PrimaryKey="true">

        <xs:selector xpath=".//MyDataSourceEntityType"/>

        <xs:field xpath="EntityID"/>

      </xs:unique>

     </xs:element>

 </xs:schema>

 <MyDataSourceEntityType>

     <EntityID>1</EntityID>

     <Latitude>47.673302</Latitude>

     <Longitude>-122.118576</Longitude>

     <AddressLine>1 Microsoft Way</AddressLine>

     <Locality>Redmond</Locality>

     <AdminDistrict>WA</AdminDistrict>

     <CountryRegion>United States</CountryRegion>

     <PostalCode>98052</PostalCode>

     <Confidence>High</Confidence>

     <Phone>303-555-0188</Phone>

     <Open>700</Open>

     <Close>1800</Close>

     <IsWheelchairAccessible>true</IsWheelchairAccessible>

 </MyDataSourceEntityType>

 <MyDataSourceEntityType>

     <EntityID>2</EntityID>

     <Latitude>34.023614</Latitude>

     <Longitude>-118.28398</Longitude>


                                                                                      169
    <AddressLine>W Jefferson Blvd</AddressLine>

    <Locality>Los Angeles</Locality>

    <AdminDistrict>CA</AdminDistrict>

    <CountryRegion>United States</CountryRegion>

    <PostalCode>90007</PostalCode>

    <Confidence>Medium</Confidence>

    <Phone>303-555-0188</Phone>

    <Open>700</Open>

    <Close>1800</Close>

    <IsWheelchairAccessible>false</IsWheelchairAccessible>

  </MyDataSourceEntityType>

</MainRoot>

Download Data Source Dataflow Response Description
The following tables describe the response syntax for a Data Source Download Dataflow request
in a set of hierarchical tables.
Response
The following fields are the top-level fields in the Download Data Source Dataflow response.
Additional tables describe the fields in each of the collections.


JSON                         XML                          Type                   Description

copyright                    Copyright                    string                 A copyright
                                                                                 notice.

brandLogoUri                 BrandLogoUri                 string                 A URL that
                                                                                 references a
                                                                                 brand image to
                                                                                 support
                                                                                 contractual
                                                                                 branding
                                                                                 requirements.

statusCode                   StatusCode                   integer                The HTTP
                                                                                 Status code for
                                                                                 the request.

statusDescription            StatusDescription            string                 A description of
                                                                                 the HTTP
                                                                                 status code.

authenticationResultCode     AuthenticationResultCode     One of the following   A status code

                                                                                               170
JSON           XML            Type                 Description
                              values:              that offers
                              ValidCredentials     additional
                                                   information
                              InvalidCredentials
                                                   about
                              CredentialsExpired
                                                   authentication
                              NotAuthorized        success or
                              NoCredentials        failure.
                              None

traceId        TraceId        string               A unique
                                                   identifier for the
                                                   request.

resourceSets   ResourceSets   collection           A collection of
                                                   ResourceSet
                                                   objects. A
                                                   ResourceSet  is
                                                   a container of
                                                   Resources
                                                   returned by the
                                                   request. For
                                                   more
                                                   information,
                                                   see the
                                                   ResourceSet
                                                   section below.

errorDetails   ErrorDetails   string[]             A collection of
                                                   error
                                                   descriptions.
                                                   For example,
                                                   ErrorDetails
                                                   can identify
                                                   parameter
                                                   values that are
                                                   not valid or are
                                                   missing. An
                                                   error log URL is
                                                   also provided
                                                   as part of links
                                                   or Link fields.


ResourceSet

                                                                 171
The ResourceSet container provides the following information.


JSON                     XML                       Type                   Description

estimatedTotal           EstimatedTotal            long                   An estimate of the total
                                                                          number of resources in
                                                                          the ResourceSet.

resources                Resources                 collection             A collection of one or
                                                                          more DataflowJob
                                                                          resources. Information
                                                                          about the DataflowJob
                                                                          resource is found in
                                                                          the DataflowJob
                                                                          section.


DataflowJob
The DataflowJob resource container provides the following information.


JSON                       XML                        Type               Description

id                         Id                         string             A unique string that
                                                                         identifies the dataflow
                                                                         job. There are no
                                                                         requirements for the
                                                                         string format.

links                      Link                       URL                URLs that is defined by
                                                                         its role and name
                                                                         attributes.
                                                                         “role”:”self”:  Use to
                                                                         check the status of your
                                                                         job. This URL is
                                                                         provided in the
                                                                         response when you
                                                                         create a load data
                                                                         source job.
                                                                         “role”:”output”   and
                                                                         “name”:”succeeded”:
                                                                         Use to access the
                                                                         downloaded entity data.
                                                                         This URL appears in
                                                                         the response only when
                                                                         the job status is set to

                                                                                               172
JSON                   XML                    Type               Description
                                                                 Completed.
                                                                 “role”:”output”    and
                                                                 “name”:”failed”:    Use to
                                                                 access the error log for
                                                                 the job. This URL
                                                                 appears in the
                                                                 response only when the
                                                                 job status is set to
                                                                 Aborted.

status                 Status                 One of the        The status of the
                                              following values: dataflow job.
                                              Pending: The
                                              dataflow job is
                                              processing.
                                              Completed: The
                                              dataflow job has
                                              completed.
                                              Aborted: The
                                              workflow
                                              stopped
                                              because of an
                                              error.

createdDate            CreatedDate            DateTime           The date and time that
                                                                 the dataflow job was
                                                                 created.

completedDate          CompletedDate          DateTime           The date and time that
                                                                 the dataflow job is
                                                                 completed. If the Status
                                                                 field is set to Pending,
                                                                 the CompletedDate field
                                                                 is not shown or is
                                                                 empty.

totalEntityCount       TotalEntityCount       integer            The total number of
                                                                 entities that were
                                                                 uploaded.

processedEntityCount   ProcessedEntityCount   integer            The number of entities
                                                                 that were processed. If
                                                                 the field is set to 0, the


                                                                                        173
JSON                         XML                     Type           Description
                                                                    number of processed
                                                                    entries is not known.

failedEntityCount            FailedEntityCount       integer        The number of entities
                                                                    that did not process
                                                                    successfully because of
                                                                    an error.

errorMessage                 ErrorMessage            string         Additional error
                                                                    information that is
                                                                    provided when the
                                                                    Status is set to Aborted.
                                                                    A link to an error log is
                                                                    also provided in the
                                                                    links or Link field.


Data Source Download Response Examples
The following examples show DataflowJob resource content in JSON and XML formats.
JSON Example
{

    "authenticationResultCode":"ValidCredentials",

    "brandLogoUri":"http:\/\/spatial.virtualearth.net\/Branding\/logo_powered_by.png",

    "copyright":"Copyright © 2011 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.",

    "resourceSets":[

       {

           "estimatedTotal":1,

           "resources":[

             {



"__type":"DataflowJob:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",

                 "id":"8ccf2a5b428d423c92759150dcddc338",

                 "links":[

                    {

                        "role":"self",



                                                                                         174
"url":"https:\/\/spatial.virtualearth.net\/REST\/v1\/dataflows\/DataSourceDownload\/8ccf2
a5b428d423c92759150dcddc338"

                          },

                          {

                               "role":"output",

                               "output":"succeeded",



"url":"https:\/\/spatial.virtualearth.net\/REST\/v1\/dataflows\/DataSourceDownload\/8ccf2
a5b428d423c92759150dcddc338M\/ouput\/succeeded"

                          }



                     ],

                     "createdDate":"Thu, 17 Nov 2011 20:38:31 GMT",

                     "failedEntityCount":0,

                     "processedEntityCount":300,

                     "status":"Completed",

                     "totalEntityCount":300

                 }

             ]

         }

    ],

    "statusCode":201,

    "statusDescription":"Created",

    "traceId":"9bc6dede6e79468ba1cc3728aa7f1cb4"

}

XML Example
<?xml version="1.0" encoding="utf-8"?>

<Response xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="https://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">

    <Copyright>Copyright © 2011 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.</Copyright>


                                                                                        175
<BrandLogoUri>http://spatial.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>

  <StatusCode>201</StatusCode>

  <StatusDescription>Created</StatusDescription>

  <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>

  <TraceId>0ddc1a3bd3dc46e28c92bb01942b0812</TraceId>

  <ResourceSets>

    <ResourceSet>

      <EstimatedTotal>1</EstimatedTotal>

      <Resources>

        <DataflowJob>

          <Id>8ccf2a5b428d423c92759150dcddc338</Id>

          <Link
role="self">https://spatial.virtualearth.net/REST/v1/dataflows/DataSourceDownload/8ccf2a5
b428d423c92759150dcddc338</Link>

          <Status>Completed</Status>

          <Link role="output"
name="succeeded">https://spatial.virtualearth.net/REST/v1/dataflows/DataSourceDownload/8c
cf2a5b428d423c92759150dcddc338/output/succeeded</Link>

          <CreatedDate>2011-11-17T12:50:08.8179772-08:00</CreatedDate>

          <CompletedDate xsi:nil="true" />

          <TotalEntityCount>300</TotalEntityCount>

          <ProcessedEntityCount>300</ProcessedEntityCount>

          <FailedEntityCount>0</FailedEntityCount>

        </DataflowJob>

      </Resources>

    </ResourceSet>

  </ResourceSets>

</Response>




Delete a Data Source
Use the following URL to delete a data source. To delete a data source, a delete data source job
is created.



                                                                                             176
      There are limits on the number of data source jobs that you can request. For more
      information see Dataflow and Data Source Job Requirements.

Supported HTTP Methods
DELETE
URL Template
Delete a data source.
The key parameter in this URL must be set to the data source master key.
You can get the data source base component
(http://spatial.virtualearth.net/REST/v1/data/accessId/dataSourceName), by using the Get Data
Source Information API and requesting information about all the data sources associated with the
Bing Maps Account that manages the data source.
The URL uses the HTTP DELETE method so you cannot delete a datasource by typing the URL
directly in the address bar of a browser. See the Example section for more information.
http://spatial.virtualearth.net/REST/v1/data/accessId/dataSourceName?key=masterKey

Template Parameters


      Parameter names and values are not case sensitive except for the key parameter value.


Parameter                    Description           Values

accessId                     Required. A unique    A string containing and ID that is part of the
                             ID for the data       URL structure that identifies the data source.
                             source.               You can retrieve the accessId and
                                                   dataSourceName values when you get
                                                   information about all datasources. For more
                                                   information, see Get Data Source Information.
                                                   Example:
                                                   a92dcfac8a0894bc4921ad5c74022623.

dataSourceName               Required The name     A string that identifies the data source. The
                             of the data source    name is part of the URL structure that identifies
                             that you want to      the data source.
                             search.               You can retrieve the accessId and
                                                   dataSourceName values when you get
                                                   information about all datasources. For more
                                                   information, see Get Data Source Information.
                                                   Example: FourthCoffeeSample

key                          Required. The         The Bing Maps Key that was specified as the
                             master key for the    master key when the data source was created.

                                                                                                177
Parameter                     Description            Values
                              data source.           Example:
                                                     key=abc123def456ghi789abc123def456ghi789


Response
If the data source is successfully deleted, the HTTP 202 status code is returned. The response
does not contain any content.

Example
EXAMPLE: Delete a data source.
The following request deletes a data source. The key parameter must be set to the data source
master key. You cannot submit this URL directly from the Address bar in a browser because the
URL uses the HTTP DELETE method. You may want to use a tool such as Fiddler or cURL to
submit this URL request.
DELETE
http://spatial.virtualearth.net/REST/v1/data/12ccc26d9e9412345f94922212345/ADataSourceNam
e?key=masterKey HTTP/1.1


HTTP Status Codes


     For more details about these HTTP status codes, see Status Codes and Errors.
When the request is successful, the following HTTP status code is returned.
   202
When the request is not successful, the response returns one of the following errors.
   400
   401
     This error code can occur in any of the following conditions:
         The key parameter is not specified.
         The specified key value is not a valid Bing Maps Key.
         The specified key is not the master key for the data source.
   404
         This error code can occur when the data source does not exist.
   500
   503


Query API
The Query API is a component of the Bing Spatial Data Services. You can use the Query API to
query a data source for information about entities in that data source. For example, if the data

                                                                                              178
source contains restaurant entities, you can query for French restaurants nearby or you can get
information about a specific restaurant. A query response can contain a maximum number of 250
results.
Below are some ways you could use the Query API to search a data source that contains
information about a set of restaurants.
   Use Query by Area to search for all movie theaters within 20 kilometers.
   Use Query Near a Route to search for all restaurants along a route.
   Use Query by Property to search for all restaurants within 20 miles that have more than 20
     employees.
   Use Query by ID to search for the restaurant entity that has an entity ID of "410".
For information about creating and updating data sources, see the Load Data Source Dataflow.


In this Section

Query by Area                                       Describes how to query a data source for
                                                    entities that are in a specified geographical
                                                    area.

Query by Property                                   Describes how to query a data source for
                                                    entities that satisfy a set of property value
                                                    conditions.

Query Near a Route                                  Describes how to query a data source for
                                                    entities near a route.

Query by ID                                         Describes how to query a data source for one
                                                    or more entities by specifying entity IDs.

Query Options                                       Describes query options, such as the options to
                                                    filter and order results and to user wildcard
                                                    searches.

Query Response Description                          Describes the response returned for queries.

Query API Sample Code (C#)                          Provides sample C# code that uses the Query
                                                    API.

Query API Sample Code (VB)                          Provides sample Visual Basic code that uses
                                                    the Query API.



Query by Area
Use the following URLs to search a data source for entity types that are within a specified area.
You can use the Query Options such and $filter and $select to further specify the entity
information that would like to return. For example, you can search for all restaurants within 10

                                                                                                    179
kilometers that serve Italian food and request that only the restaurant name and location
information is returned.

Supported HTTP Methods
GET, HEAD

URL template


    This template supports both HTTP and HTTPS protocols. URLs in the response use
    HTTPS protocol.
    A query response can contain a maximum number of 250 results.
Get information about entities by searching an area defined by a point and a distance.
The distance specifies the maximum distance from the specified point to search. The maximum
distance is 400 kilometers.
You must specify the distance in kilometers between 0.16 and 400 kilometers. The distance unit
of miles is not supported.
You can return the distance from the point to each entity found in the search area by specifying
__Distance as one of the $select query option values. For more information see the queryOption
parameter description in the table below.
To search entities along a route, see Query Near a Route.
To search for entities by area and by property value, see Query by Property.
http://spatial.virtualearth.net/REST/v1/data/accessId/dataSourceName/entityTypeName?spati
alFilter=nearby(latitude,longitude,distance)&queryoption1&queryoption2&queryoptionN&jsonp
=jsonCallBackFunction&jsonso=jsonState&key=queryKey



Get information about nearby entities by searching an area defined by a bounding box.
A bounding box defines an area using latitude and longitude pairs.
http://spatial.virtualearth.net/REST/v1/data/accessId/dataSourceName/entityTypeName?spati
alFilter=bbox(southLatitude,westLongitude,northLatitude,eastLongitude)&queryOption1&query
Option2&queryOptionN&jsonp=jsonCallBackFunction&jsonso=jsonState&key=queryKey



Template Parameters


    Parameter names and values are not case-sensitive except for the queryKey parameter
    value.


Parameter                 Description           Values

accessId                  Required. A           A string containing an ID that is part of the URL

                                                                                               180
Parameter        Description              Values
                 unique ID for the        structure that identifies the data source.
                 data source.             Example: 20181f26d9e94c81acdf9496133d4f23

dataSourceName   Required The             A string that identifies the data source.
                 name of the data         Example: FourthCoffeeSample
                 source that you
                 want to search.

entityTypeName   Required The             The entity type of the data source.
                 entity type to           Example: FourthCoffeeShops
                 search for.

spatialFilter    Required The area        To define an area using a point and distance in
                 you want to search.      kilometers, use the following syntax:
                 You can specify          spatialFilter=nearby(latitude, longitude, distance)
                 this area in two
                                          where latitude and longitude represent a point on
                 ways:
                                          the Earth and the distance represents the
                    A latitude and      maximum distance to search from that point. You
                      longitude           must specify the distance in kilometers. The
                      representing a
                                          distance unit of miles is not supported.
                      point and a
                      distance in         Example: spatialFilter=nearby(47.6,-122.3,50.0)
                      kilometers to       To define an area using a bounding box, use the
                      search from         following syntax:
                      that point.
                                          spatialFilter=bbox(South Latitude, West
                    A set of latitude   Longitude, North Latitude, East Longitude)
                      and longitude
                                          where the latitude and longitude values define an
                      pairs that
                      create an area      area on the earth.
                      called a            Example: spatialFilter=bbox(47.5,-122.4,47.7,-
                      bounding box.       122.2)

queryOption      Optional. Specifies      A set of query options. Each query option is
                 query options, such      specified as a single URL parameter. Query
                 as format and            option examples include the ability to filter on
                 properties to            property values ($filter), specify the format of
                 display in the           response ($format) and order by a property value
                 response. For more       ($orderby). See Query Options for a complete
                 information about        list.
                 query options, see       The following example shows how to set both the
                 Query Options.           $format and the $orderby query options in the
                                          URL.
                                          &$format=json&$orderby=ZipCode



                                                                                          181
Parameter   Description            Values
                                   If you are using a spatial filter that searches a
                                   distance from a point, and you want to return the
                                   distance from the point to each entity returned in
                                   the response, you can add a custom value
                                   __Distance to the list of $select values as shown
                                   in the following example.
                                   Example:
                                   $select=AddressLine,City,PostalCode,__Distance
                                   When you specify __Distance as a $select value,
                                   the response returns a custom property element
                                   of type Edm:Double that is also named
                                   __Distance.

                                   You can specify up to three (3) properties for the
                                   $orderby option. You cannot use the latitude or
                                   longitude properties to sort results.
                                   If the $orderby option is not specified as part of
                                   the request, the results are sorted as follows:
                                      For searches using a point and distance: The
                                        results will be sorted by the distance of the
                                        entity from the specified point. If two results
                                        are at the same distance, they are sorted by
                                        the property that represents the entity ID.
                                        Results are returned in ascending order.
                                      For searches using a bounding box: The
                                        results will be sorted by the property that
                                        represents the entity ID in ascending order.
                                   You cannot use the latitude or longitude
                                   properties to filter results by using the $filter
                                   query option.

jsonp       Optional. Name of      A string that contains the name of the callback
            JSON callback          function.
            function that is       Example: jsonp=MyCallbackFunction
            called when the
            response to the
            request is received.
            The JSON object
            provided in the
            response is passed
            to the callback
            function.

                                                                                       182
Parameter                  Description            Values

jsonso                     Optional. The state Any valid JavaScript string.
                           object to pass to   Example: jsonso=abc3144sd
                           the JSON callback
                           function. You can
                           use a state object
                           to match a
                           response with a
                           specific call. This
                           value is provided
                           as the second
                           parameter to the
                           callback function
                           provided in the
                           JSONP parameter.

queryKey                   Required. The           The Bing Maps Keys that you can use for a data
                           Bing Maps Key to       source are specified when the data source is
                           use to access the      created. For example, there may be a single
                           data source.           query key you must use to query the data source
                                                  or you may be able to use any Bing Maps Key.
                                                  For more information about specifying query keys
                                                  when a data source is created, see Create a
                                                  Load Data Source Job and Input Entity Data.
                                                  Example:
                                                  key=abc123def456ghi789abc123def456ghi789


Response
The response to this URL contains the results of the query.
If the $orderby query option is not specified as part of the request, the results are sorted as
follows:
   For searches using a point and distance: The results will be sorted by the distance of the
     entity from the specified point. If two results are at the same distance, they are sorted by the
     property that is used as the entity ID. Results are returned in ascending order.
   For searches using a bounding box: The results will be sorted by the property that represents
     the entity ID in ascending order.
This URL supports the following response formats.
   Atom (application/atom + xml) [default]
   JSON (application/json)




                                                                                                   183
When the output format is set to Atom, the response contains a collection of Atom entries that are
part of an Atom feed. For more information about these Atom response formats, see OData
AtomPub Format and the Atom examples in the Examples section.
When the output format is JSON, the response format for both types of requests is a collection of
JSON Entries in a “results” container. For more information about the JSON response format, see
OData: JavaScript Object Notation (JSON) Format and the JSON examples in the Examples
section.

Examples
EXAMPLE: Query a data source by specifying a bounding box.
This example queries for coffee shops within an area defined by a bounding box (a pair of
latitudes and longitudes).The $select and $top query options request the entity ID, latitude and
longitude for the first three (3) entities that meet the search criteria.
URL with Atom Response
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops?spatialFilter=bbox(40.7801465817126,-
74.46958923339845,40.88535150706938,-
74.163070678710937)&$select=EntityID,Latitude,Longitude&$top=3&key=queryKey




<feed xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
xmlns="http://www.w3.org/2005/Atom">

  <title type="text" />

  <id>uuid:d359c52a-63a7-469d-bad9-7b54baada637;id=45</id>

  <rights type="text">© 2011 Microsoft and its suppliers. This API and any results cannot
be used or accessed without Microsoft’s express written permission.</rights>

  <updated>2011-01-11T01:55:58Z</updated>

  <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-7884')</id>

    <title type="text" />

    <updated>2011-01-11T01:55:58Z</updated>

    <content type="application/xml">

      <m:properties>

        <d:EntityID>-7884</d:EntityID>


                                                                                               184
          <d:Latitude m:type="Edm.Double">40.780329</d:Latitude>

          <d:Longitude m:type="Edm.Double">-74.237863</d:Longitude>

     </m:properties>

   </content>

 </entry>

 <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-7891')</id>

   <title type="text" />

   <updated>2011-01-11T01:55:58Z</updated>

   <content type="application/xml">

     <m:properties>

          <d:EntityID>-7891</d:EntityID>

          <d:Latitude m:type="Edm.Double">40.781604</d:Latitude>

          <d:Longitude m:type="Edm.Double">-74.181775</d:Longitude>

     </m:properties>

   </content>

 </entry>

 <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-7920')</id>

   <title type="text" />

   <updated>2011-01-11T01:55:58Z</updated>

   <content type="application/xml">

     <m:properties>

          <d:EntityID>-7920</d:EntityID>

          <d:Latitude m:type="Edm.Double">40.787240</d:Latitude>

          <d:Longitude m:type="Edm.Double">-74.391041</d:Longitude>

     </m:properties>

   </content>

 </entry>

</feed>



                                                                                      185
URL with JSON Response
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops?spatialFilter=bbox(40.7801465817126,-
74.46958923339845,40.88535150706938,-
74.163070678710937)&$select=EntityID,Latitude,Longitude&$top=3&$format=json&key=queryKey




{

    "d":{

      "__copyright":"\u00a9 2011 Microsoft and its suppliers.   This API and any results
cannot be used or accessed without Microsoft’s express written permission.",

      "results":[

            {

                 "__metadata":{



"uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fou
rthCoffeeSample/FourthCoffeeShops('-7884')"

                 },

                 "EntityID":"-7884",

                 "Latitude":40.780329,

                 "Longitude":-74.237863

            },

            {

                 "__metadata":{



"uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fou
rthCoffeeSample/FourthCoffeeShops('-7891')"

                 },

                 "EntityID":"-7891",

                 "Latitude":40.781604,

                 "Longitude":-74.181775

            },

            {

                 "__metadata":{

                                                                                       186
"uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fou
rthCoffeeSample/FourthCoffeeShops('-7920')"

                },

                "EntityID":"-7920",

                "Latitude":40.787240,

                "Longitude":-74.391041

            }

        ]

    }

}




EXAMPLE: Query a data source by specifying a point and distance to search from that
point.
This example queries for coffee shops within an area defined by a point (latitude and longitude)
and a distance from that point. The query returns the entity ID and the latitude and longitude of
the first three (3) entities that meet the search criteria.
URL with Atom Response
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops?spatialFilter=nearby(40.83274904439099,-
74.3163299560546935,5)&$select=EntityID,Latitude,Longitude,__Distance&$top=3&key=queryKey




<feed xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
xmlns="http://www.w3.org/2005/Atom">

    <title type="text" />

    <id>uuid:d359c52a-63a7-469d-bad9-7b54baada637;id=46</id>

    <rights type="text">© 2011 Microsoft and its suppliers. This API and any results cannot
be used or accessed without Microsoft’s express written permission.</rights>

    <updated>2011-01-11T02:03:34Z</updated>

    <entry>




                                                                                               187
<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-8051')</id>

   <title type="text" />

   <updated>2011-01-11T02:03:34Z</updated>

   <content type="application/xml">

     <m:properties>

       <d:EntityID>-8051</d:EntityID>

       <d:Latitude m:type="Edm.Double">40.820685</d:Latitude>

       <d:Longitude m:type="Edm.Double">-74.295683</d:Longitude>

       <d:__Distance m:type="Edm.Double">2.19734068236095</d:__Distance>

     </m:properties>

   </content>

 </entry>

 <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-8174')</id>

   <title type="text" />

   <updated>2011-01-11T02:03:34Z</updated>

   <content type="application/xml">

     <m:properties>

       <d:EntityID>-8174</d:EntityID>

       <d:Latitude m:type="Edm.Double">40.849513</d:Latitude>

       <d:Longitude m:type="Edm.Double">-74.292831</d:Longitude>

       <d:__Distance m:type="Edm.Double">2.72010344668636</d:__Distance>

     </m:properties>

   </content>

 </entry>

 <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-8181')</id>

   <title type="text" />

   <updated>2011-01-11T02:03:34Z</updated>

                                                                                      188
     <content type="application/xml">

       <m:properties>

          <d:EntityID>-8181</d:EntityID>

          <d:Latitude m:type="Edm.Double">40.851404</d:Latitude>

          <d:Longitude m:type="Edm.Double">-74.293720</d:Longitude>

          <d:__Distance m:type="Edm.Double">2.81746736218219</d:__Distance>

       </m:properties>

     </content>

    </entry>

</feed>



URL with JSON Response
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops?spatialFilter=nearby(40.83274904439099,-
74.3163299560546935,5)&$filter&$select=EntityID,Latitude,Longitude,__Distance&$top=3&$for
mat=json&key=queryKey




{

    "d":{

       "__copyright":"\u00a9 2011 Microsoft and its suppliers.     This API and any results
cannot be used or accessed without Microsoft’s express written permission.",

       "results":[

            {

                 "__metadata":{



"uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fou
rthCoffeeSample/FourthCoffeeShops('-8051')"

                 },

                 "EntityID":"-8051",

                 "Latitude":40.820685,

                 "Longitude":-74.295683,

                 "__Distance":2.19740735412509

            },


                                                                                          189
            {

                 "__metadata":{



"uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fou
rthCoffeeSample/FourthCoffeeShops('-8174')"

                 },

                 "EntityID":"-8174",

                 "Latitude":40.849513,

                 "Longitude":-74.292831.

                 "__Distance":2.72010344668636

            },

            {

                 "__metadata":{



"uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fou
rthCoffeeSample/FourthCoffeeShops('-8181')"

                 },

                 "EntityID":"-8181",

                 "Latitude":40.851404,

                 "Longitude":-74.293720,

                 "__Distance":2.81746736218219

            }

        ]

    }

}

EXAMPLE: Query a data source by specifying a point and distance to search and limit the
results returned based on additional property values.
This example queries for coffee shops within a given distance and uses the $filter property to
further limit the results to coffee shops with wifi. The query returns the entity ID and the latitude
and longitude of the first three (3) entities that meet the search criteria.
URL with Atom Response
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops?spatialFilter=nearby(40.83274904439099,-
74.3163299560546935,5)&$filter=IsWifiHotSpot%20eq%201&$select=DisplayName,Latitude,Longit
ude&$top=3&key=queryKey



                                                                                                    190
<feed xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
xmlns="http://www.w3.org/2005/Atom">

 <title type="text" />

 <id>uuid:9d7fa138-2948-4928-8e41-62a6c2daad08;id=1503</id>

 <rights type="text">© 2011 Microsoft and its suppliers. This API and any results cannot
be used or accessed without Microsoft’s express written permission.</rights>

 <updated>2011-02-03T01:36:41Z</updated>

 <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-8080')</id>

   <title type="text" />

   <updated>2011-02-03T01:36:41Z</updated>

   <content type="application/xml">

     <m:properties>

       <d:DisplayName>Fourth Coffee Store #8080, East Hanover, NJ, United
States</d:DisplayName>

       <d:Latitude m:type="Edm.Double">40.827191</d:Latitude>

       <d:Longitude m:type="Edm.Double">-74.358151</d:Longitude>

     </m:properties>

   </content>

 </entry>

 <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-8089')</id>

   <title type="text" />

   <updated>2011-02-03T01:36:41Z</updated>

   <content type="application/xml">

     <m:properties>

       <d:DisplayName>Fourth Coffee Store #8077, East Hanover, NJ, United
States</d:DisplayName>

                                                                                      191
          <d:Latitude m:type="Edm.Double">40.826413</d:Latitude>

          <d:Longitude m:type="Edm.Double">-74.360059</d:Longitude>

       </m:properties>

     </content>

    </entry>

    <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-8089')</id>

     <title type="text" />

     <updated>2011-02-03T01:36:41Z</updated>

     <content type="application/xml">

       <m:properties>

          <d:DisplayName>Fourth Coffee Store #8089, East Hanover, NJ, United
States</d:DisplayName>

          <d:Latitude m:type="Edm.Double" 40.828150</d:Latitude>

          <d:Longitude m:type="Edm.Double>-74.364028</d:Longitude>

       </m:properties>

     </content>

    </entry>

</feed>



URL with JSON Response
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops?spatialFilter=nearby(40.83274904439099,-
74.3163299560546935,5)&$filter=IsWifiHotSpot%20eq%201&$select=DisplayName,Latitude,Longit
ude&$top=3&format=json&key=queryKey




{

    "d":{

       "__copyright":"\u00a9
2011 Microsoft and its suppliers.    This API and any results cannot be used or accessed wi
thout Microsoft’s express written permission.",

       "results":[

                                                                                        192
             {

                  "__metadata":{

                       "uri":"https:\/\/spatial.virtualearth.net\/REST\/v1\/data\/20181f26d9e94c8
1acdf9496133d4f23\/FourthCoffeeSample\/FourthCoffeeShops('-8080')"

                  },

                  "DisplayName":"Fourth Coffee Store #8080, East Hanover, NJ, United States",

                  "Latitude":40.827191,

                  "Longitude:-74.358151           },

             {

                  "__metadata":{

                       "uri":"https:\/\/spatial.virtualearth.net\/REST\/v1\/data\/20181f26d9e94c8
1acdf9496133d4f23\/FourthCoffeeSample\/FourthCoffeeShops('-8077')"

                  },

                  "DisplayName":"Fourth Coffee Store #8077, East Hanover, NJ, United States",

                  "Latitude":40.826413,

                  "Longitude":-74.360059

             },

             {

                  "__metadata":{

                       "uri":"https:\/\/spatial.virtualearth.net\/REST\/v1\/data\/20181f26d9e94c8
1acdf9496133d4f23\/FourthCoffeeSample\/FourthCoffeeShops('-8089')"

                  },

                  "DisplayName":"Fourth Coffee Store #8089, East Hanover, NJ, United States",

                  "Latitude":40.828150,

                  "Longitude":-74.364028

             }

         ]

     }

}


HTTP Status Codes


     For more details about these HTTP status codes, see Status Codes and Errors.
When the request is successful, the following HTTP status code is returned.
   200

                                                                                              193
When the request is not successful, the response returns one of the following errors.
   400
   401
   500
   503

See Also
Query by ID
Query by Property


Query Near a Route
Use the following URL to search a data source for entities that are within one (1) mile or 1.6
kilometers of a route. You can use the Query Options such as $filter and $select to further specify
the entity information that would like to return. For example, you can search the Traffic Incident
Data Source for all traffic incidents along a route and request that only the severity, description
and location (latitude and longitude) be returned.


     The Query Near a Route feature is not supported for the NavteqNA and NavteqEU data
     sources.
For an example application of how to use Query Near a Route and Bing Maps AJAX Control,
Version 7.0 to show traffic incidents along a route on a map, see Searching for Traffic Incidents
Along a Route.

Supported HTTP Methods
GET, HEAD

URL template


     This template supports both HTTP and HTTPS protocols. URLs in the response use
     HTTPS protocol.
     A query response can contain a maximum number of 500 results.
Get entities that are within one (1) mile or 1.6 kilometers of a route.
Use the query options to specify the properties that you want to return and to provide other
options such as the number of results to return.
http://spatial.virtualearth.net/REST/v1/data/accessId/dataSourceName/entityTypeName?spati
alFilter=nearRoute(startRoute,endRoute)&avoid=avoid&optimize=optimize&distanceBeforeFirst
Turn=distanceBeforeFirstTurn&heading=heading&travelMode=travelMode&queryoption1&queryopti
on2&queryoptionN&jsonp=jsonCallBackFunction&jsonso=jsonState&key=queryKey




                                                                                               194
Template Parameters


    Parameter names and values are not case-sensitive except for the queryKey parameter
    value.
Query Parameters


Parameter                Description            Values

accessId                 Required. A            A string containing an ID that is part of the URL
                         unique ID for the      structure that identifies the data source.
                         data source.           Example: 20181f26d9e94c81acdf9496133d4f23

dataSourceName           Required. The          A string that identifies the data source.
                         name of the data       Example: FourthCoffeeSample
                         source that you
                         want to search.

entityTypeName           Required The           The entity type of the data source.
                         entity type to         Example: FourthCoffeeShops
                         search for.

spatialFilter            Required. The          To define a route and distance, use the following
                         start and end          syntax:
                         points of the route.   spatialFilter=nearRoute(latitude,longitude or
                         You can specify        address of route start, latitude,longitude or
                         the start and end      address of route end)
                         points of the route
                                                Example: spatialFilter=nearRoute('47.62341,-
                         in two ways.
                                                122.33441', '47.63143,-122.57243')
                            A latitude and
                              longitude.
                            An address.

queryOption              Optional.              A set of query options. Each query option is
                         Specifies query        specified as a single URL parameter. Query
                         options, such as       option examples include the ability to filter on
                         format and             property values ($filter), specify the format of
                         properties to          response ($format) and order by a property value
                         display in the         ($orderby). See Query Options for a complete
                         response. For          list.
                         more information       The following example shows how to set both the
                         about query            $format and the $orderby query options in the
                         options, see Query     URL.
                         Options.
                                                &$format=json&$orderby=ZipCode

                                                If you want to return the distance from the point to

                                                                                                195
Parameter   Description          Values
                                 each entity returned in the response, you can add
                                 a custom value __Distance to the list of $select
                                 values as shown in the following example.
                                 Example:
                                 $select=AddressLine,City,PostalCode,__Distance
                                 When you specify __Distance as a $select value,
                                 the response returns a custom property element
                                 of type Edm:Double that is also named
                                 __Distance.

                                 You can specify up to three (3) properties for the
                                 $orderby option. You cannot use the latitude or
                                 longitude properties to sort results.

jsonp       Optional. Name of    A string that contains the name of the callback
            JSON callback        function.
            function that is     Example: jsonp=MyCallbackFunction
            called when the
                                 For an example of how to use this parameter, see
            response to the
                                 Searching for Traffic Incidents Along a Route.
            request is
            received. The
            JSON object
            provided in the
            response is passed
            to the callback
            function.

jsonso      Optional. The         Any valid JavaScript string.
            state object to pass Example: jsonso=abc3144sd
            to the JSON
            callback function.
            You can use a
            state object to
            match a response
            with a specific call.
            This value is
            provided as the
            second parameter
            to the callback
            function provided
            in the JSONP
            parameter.


                                                                                196
Parameter          Description           Values

queryKey           Required. The          The Bing Maps Keys that you can use for a data
                   Bing Maps Key to      source are specified when the data source is
                   use to access the     created. For example, there may be a single
                   data source.          query key you must use to query the data source
                                         or you may be able to use any Bing Maps Key.
                                         For more information about specifying query keys
                                         when a data source is created, see Create a
                                         Load Data Source Job and Input Entity Data.
                                         Example:
                                         key=abc123def456ghi789abc123def456ghi789




Route Parameters


Parameter             Alias            Description         Values

avoid                                  Optional.           A comma-separated list of
                                       Specifies the       values that limit the use of
                                       road types to       highways and toll roads in the
                                       minimize or avoid   route. In the definitions below,
                                       when the route is   “highway” also refers to a
                                       created for the     “limited-access highway”.
                                       driving travel      If no values are specified,
                                       mode.               highways and tolls are allowed
                                                           in the route.
                                                              highways: Avoids the use of
                                                                highways in the route.
                                                              tolls: Avoids the use of toll
                                                                roads in the route.
                                                              minimizeHighways:
                                                                Minimizes (tries to avoid)
                                                                the use of highways in the
                                                                route.
                                                              minimizeTolls: Minimizes
                                                                (tries to avoid) the use of
                                                                toll roads in the route.


                                                                If you specify more than

                                                                                           197
Parameter                 Alias   Description           Values
                                                             one option for a road
                                                             type, then the most
                                                             restrictive option is
                                                             used. For example, if
                                                             you set the avoid
                                                             parameter to both
                                                             highways and
                                                             minimizeHighways, the
                                                             highways option is used
                                                             and all highways are
                                                             avoided.
                                                        Examples:
                                                        avoid=highways
                                                        avoid=highways,tolls

distanceBeforeFirstTurn   dbft    Optional.             An integer distance specified in
                                  Specifies the         meters. Use this parameter to
                                  distance before       make sure that the moving
                                  the first turn is     vehicle has enough distance to
                                  allowed in the        make the first turn.
                                  route. This option    Examples:
                                  only applies to
                                                        distanceBeforeFirstTurn=500
                                  the driving travel
                                                        dbft=500
                                  mode.

heading                   hd      Optional.             An integer value between 0 and
                                  Specifies the         359 that represents degrees
                                  initial heading for   from north where north is 0
                                  the route.            degrees and the heading is
                                                        specified clockwise from north.
                                                        For example, setting the
                                                        heading of 270 degrees creates
                                                        a route that initially heads west.
                                                        Example:
                                                        heading=90

optimize                  optmz   Optional.             One of the following values:
                                  Specifies what           distance: The route is
                                  parameters to              calculated to minimize the
                                  use to optimize            distance. Traffic information
                                  the route on the           is not used.
                                  map.                     time [default]: The route is

                                                                                       198
Parameter                      Alias            Description        Values
                                                                        calculated to minimize the
                                                                        time. Traffic information is
                                                                        not used.
                                                                      timeWithTraffic: The route is
                                                                        calculated to minimize the
                                                                        time and uses current traffic
                                                                        information.
                                                                   Example: optimize=time

travelMode                                      Optional. The      One of the following values:
                                                mode of travel for  Driving [default]
                                                the route.          Walking


Response
The response to this URL contains the results of the query.
Results are returned in ascending order. If the $orderby query option is not specified as part of
the request, the results are sorted as follows:
1. The results are sorted based on the distance from the start of the route.
2. The results are sorted by the distance from the closest route point.
3. The results are sorted based on entity ID.
This URL supports the following response formats.
   Atom (application/atom + xml) [default]
   JSON (application/json)
When the output format is set to Atom, the response contains a collection of Atom entries that are
part of an Atom feed. For more information about these Atom response formats, see OData
AtomPub Format and the Atom examples in the Examples section.
When the output format is JSON, the response format for both types of requests is a collection of
JSON Entries in a “results” container. For more information about the JSON response format, see
OData: JavaScript Object Notation (JSON) Format and the JSON examples in the Examples
section.

Examples
EXAMPLE: Query a data source for entities near a route.
The following example queries for coffee shops along a route between Webster, Texas and
Kemah, Texas. Coffee shops within one (1) mile of the route are returned in the response.
Because FourthCoffeeSample is a public data source, you can use any Bing Maps Key for the
query key.
URLs with ATOM Response
Specifying address values

                                                                                                  199
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops?spatialFilter=nearRoute('Webster,TX','Kemah,TX')&$select=Entity
ID,Latitude,Longitude,DisplayName,Phone&$top=3&key=queryKey




Specifying latitude and longitude values
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops?spatialFilter=nearRoute('29.5386,-95.1194','29.5431,-
95.01831')&$select=EntityID,Latitude,Longitude,DisplayName,Phone&$top=3&key=queryKey




<?xml version="1.0" encoding="utf-8"?>

<feed xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
xmlns="http://www.w3.org/2005/Atom">

  <title type="text"></title>

  <id>uuid:65a15ae6-c650-492a-9079-d942b919aa47;id=583534</id>

  <rights type="text">© 2012 Microsoft and its suppliers.   This API and any results
cannot be used or accessed without Microsoft's express written permission.</rights>

  <updated>2012-01-24T23:36:03Z</updated>

  <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-946')</id>

    <title type="text"></title>

    <updated>2012-01-24T23:36:03Z</updated>

    <content type="application/xml">

      <m:properties>

        <d:EntityID>-946</d:EntityID>

        <d:Latitude m:type="Edm.Double">29.533064</d:Latitude>

        <d:Longitude m:type="Edm.Double">-95.124686</d:Longitude>

        <d:DisplayName>Fourth Coffee Store #946, Webster, TX, United
States</d:DisplayName>

        <d:Phone>              1-800-XXX-XXXX    </d:Phone>



                                                                                       200
     </m:properties>

   </content>

 </entry>

 <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-951')</id>

   <title type="text"></title>

   <updated>2012-01-24T23:36:03Z</updated>

   <content type="application/xml">

     <m:properties>

       <d:EntityID>-951</d:EntityID>

       <d:Latitude m:type="Edm.Double">29.541998</d:Latitude>

       <d:Longitude m:type="Edm.Double">-95.016876</d:Longitude>

       <d:DisplayName>Fourth Coffee Store #951, Kemah, TX, United States</d:DisplayName>

       <d:Phone>            1-800-XXX-XXXX       </d:Phone>

     </m:properties>

   </content>

 </entry>

 <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-960')</id>

   <title type="text"></title>

   <updated>2012-01-24T23:36:03Z</updated>

   <content type="application/xml">

     <m:properties>

       <d:EntityID>-960</d:EntityID>

       <d:Latitude m:type="Edm.Double">29.566524</d:Latitude>

       <d:Longitude m:type="Edm.Double">-95.060661</d:Longitude>

       <d:DisplayName>Fourth Coffee Store #960, Seabrook, TX, United
States</d:DisplayName>

       <d:Phone>            1-800-XXX-XXXX       </d:Phone>

     </m:properties>

   </content>

                                                                                      201
    </entry>

</feed>




URLs with JSON Response
Specifying address values
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops?spatialFilter=nearRoute('Webster,TX','Kemah,TX')&$select=Entity
ID,Latitude,Longitude,DisplayName,Phone&$top=3&$format=json&key=queryKey




Specifying latitude and longitude values
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops?spatialFilter=nearRoute('29.5386,-95.1194','29.5431,-
95.01831')&$select=EntityID,Latitude,Longitude,DisplayName,Phone&$format=json&$top=3&key=
queryKey




{

    "d":{

       "__copyright":"\u00a9 2012 Microsoft and its suppliers.     This API and any results
cannot be used or accessed without Microsoft's express written permission.",

       "results":[

            {

                "__metadata":{



"uri":"https:\/\/spatial.virtualearth.net\/REST\/v1\/data\/20181f26d9e94c81acdf9496133d4f
23\/FourthCoffeeSample\/FourthCoffeeShops('-946')"

                },

                "EntityID":"-946",

                "Latitude":29.533064,

                "Longitude":-95.124686,

                "DisplayName":"Fourth Coffee Store #946, Webster, TX, United States",

                                                                                          202
                 "Phone":"            1-800-XXX-XXXX      "

            },

            {

                 "__metadata":{



"uri":"https:\/\/spatial.virtualearth.net\/REST\/v1\/data\/20181f26d9e94c81acdf9496133d4f
23\/FourthCoffeeSample\/FourthCoffeeShops('-951')"

                 },

                 "EntityID":"-951",

                 "Latitude":29.541998,

                 "Longitude":-95.016876,

                 "DisplayName":"Fourth Coffee Store #951, Kemah, TX, United States",

                 "Phone":"            1-800-XXX-XXXX      "

            },

            {

                 "__metadata":{



"uri":"https:\/\/spatial.virtualearth.net\/REST\/v1\/data\/20181f26d9e94c81acdf9496133d4f
23\/FourthCoffeeSample\/FourthCoffeeShops('-960')"

                 },

                 "EntityID":"-960",

                 "Latitude":29.566524,

                 "Longitude":-95.060661,

                 "DisplayName":"Fourth Coffee Store #960, Seabrook, TX, United States",

                 "Phone":"            1-800-XXX-XXXX      "

            }

        ]

    }

}




EXAMPLE: Query a data source for entities near a route.
The following example adds additional route parameters to the previous example that can affect
the route.


                                                                                            203
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops?&spatialFilter=nearRoute('Webster,TX','Kemah,TX')&$select=Entit
yID,Latitude,Longitude&avoid=tolls&optimize=time&travelMode=driving&output=xml&key=queryK
ey


HTTP Status Codes


     For more details about these HTTP status codes, see Status Codes and Errors.
When the request is successful, the following HTTP status code is returned.
   200
When the request is not successful, the response returns one of the following errors.
   400
   401
   500
   503

See Also
Query by Area
Query by ID
Query by Property


Query by Property
Use the following URL to search a data source for one or more entities by specifying property
values.

Supported HTTP Methods
GET, HEAD

URL template


     This template supports both HTTP and HTTPS protocols. URLs in the response use
     HTTPS protocol.
     A query response can contain a maximum number of 250 results.
Query for one or more entities by specifying property values and a distance to search.
http://spatial.virtualearth.net/REST/v1/data/accessId/dataSourceName

/entityTypeName?spatialFilter=nearby(latitude,longitude,distance)&$filter=filterString&qu
eryOption1&queryOption2&queryOptionN&jsonp=jsonCallBackFunction&jsonso=jsonState&key=quer
yKey




                                                                                                204
Query for one or more entities by specifying property values and a bounding box to
search.
http://spatial.virtualearth.net/REST/v1/data/accessId/dataSourceName

/entityTypeName?bbox(southLatitude,westLongitude,northLatitude,eastLongitude)&$filter=fil
terString&queryOption1&queryOption2&queryOptionN&jsonp=jsonCallBackFunction&jsonso=jsonSt
ate&key=queryKey

Template Parameters


    Parameter names and values are not case-sensitive except for the queryKey parameter
    value.


Parameter                Description              Values

accessId                 Required. A unique       A string containing and ID that is part of the
                         ID for the data          URL structure that identifies the data source.
                         source.                  Example:
                                                  20181f26d9e94c81acdf9496133d4f23

dataSourceName           Required The name        A string containing the data source name.
                         of the data source       Example: FourthCoffeeSample
                         that you want to
                         search.

entityTypeName           Required The entity      The entity type of the data source.
                         type to search for.      Example: FourthCoffeeStores

spatialFilter            Required The area        To define an area using a point and distance in
                         you want to search.      kilometers, use the following syntax:
                         You can specify this     spatialFilter=nearby(latitude, longitude,
                         area in two ways:        distance)
                            A latitude and      where latitude and longitude represent a point
                              longitude           on the Earth and the distance represents the
                              representing a
                                                  maximum distance to search from that route.
                              point and a
                                                  The distance must be between 0.15 and 40
                              distance in
                                                  kilometers. The distance unit of miles is not
                              kilometers to
                              search from that    supported.
                              point.              Example: spatialFilter=nearby(47.6,-
                            A set of latitude   122.3,50.0)
                              and longitude       To define an area using a bounding box, use
                              pairs that create   the following syntax:
                              an area called a
                                                  spatialFilter=bbox(South Latitude, West
                              bounding box.
                                                  Longitude, North Latitude, East Longitude)

                                                                                               205
Parameter      Description            Values
                                      where the latitude and longitude values define
                                      an area on the earth.
                                      Example: spatialFilter=bbox(47.5,-122.4,47.7,-
                                      122.2)

filterString   Required. The          A conditional expression that uses property
               search condition       values. An entity is returned when the
               based on property      expression is true for that entity‟s values. This
               values.                parameter is an OData query option. Currently,
                                      the Query API only supports logical operators.
                                      Example: $filter=CountryRegion Eq
                                      'Washington' and Employees Ge 10

queryOptions   Optional. Options      A set of query values. Each query value is
               for this query. For    specified as an individual URL parameter. The
               more information       following example shows how to set both the
               about query options,   $format and the $orderby query options in the
               see Query Options.     URL.
                                      &$format=json&$orderby=ZipCode

                                      Example:
                                      $select=HoursOfOperation,IsWiFiHotSpot
                                      If the $orderby option is not specified as part of
                                      the request, the results will be sorted by the
                                      property that represents the entity ID in
                                      ascending order. You can specify up to three
                                      (3) properties for the $orderby option. You
                                      cannot use the latitude or longitude properties
                                      to sort results.
                                      You cannot use the latitude or longitude
                                      properties to filter results by using the $filter
                                      query option.

jsonp          Optional. Name of       A string that contains the name of the callback
               JSON callback           function.
               function that is called Example: jsonp=MyCallbackFunction
               when the response
               to the request is
               received. The JSON
               object provided in
               the response is
               passed to the
               callback function.

                                                                                      206
Parameter                   Description             Values

jsonso                      Optional. The state     Any valid JavaScript string.
                            object to pass to the   Example: jsonso=abc3144sd
                            JSON callback
                            function. You can
                            use a state object to
                            match a response
                            with a specific call.
                            This value is
                            provided as the
                            second parameter to
                            the callback function
                            provided in the
                            JSONP parameter.

queryKey                    Required. The Bing       The Bing Maps Keys that you can use for a
                            Maps Key to use to      data source are specified when the data
                            access the data         source is created. For example, there may be
                            source.                 a single query key you must use to query the
                                                    data source or you may be able to use any
                                                    Bing Maps Key. For more information about
                                                    specifying query keys when a data source is
                                                    created, see Create a Load Data Source Job
                                                    and Input Entity Data.
                                                    Example:
                                                    key=abc123def456ghi789abc123def456ghi789


Response
This URL supports the following response formats.
If the $orderby query option is not specified when you query for multiple entity IDs, the results will
be sorted by the property that is used for the entity ID. Results are returned in ascending order.
   Atom (application/atom + xml) [default]
   JSON (application/json)
When the output format is set to Atom, the response contains a collection of Atom Entries is
returned as part of an Atom feed. For more information about these Atom response formats, see
OData AtomPub Format and the Atom examples in the Examples section.
When the output format is JSON, the response format for both types of requests is a collection of
JSON Entries in a “results” container. For more information about the JSON response format, see
OData: JavaScript Object Notation (JSON) Format and the JSON examples in the Examples
section.


                                                                                                  207
Examples
EXAMPLE: Get entities that meet specified filter conditions and order the results.
This example queries for coffee shops in the city of Clearwater and returns information about
whether they are WiFi hotspots. The entries are sorted in descending order so that shops that are
WiFi hotspots are listed first.
URL with Atom response


http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23

/FourthCoffeeSample/FourthCoffeeShops?spatialFilter=nearby(27.894007,-
82.670776,2)&$filter=StoreType%20Eq%20'Coffee
Shop'&$select=IsWiFiHotSpot&$orderby=IsWiFiHotSpot&key=queryKey




<feed xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
xmlns="http://www.w3.org/2005/Atom">

  <title type="text" />

  <id>uuid:876b2e49-e480-40b8-8282-9929ced06f7f;id=46</id>

  <rights type="text">© 2011 Microsoft and its suppliers. This API and any results cannot
be used or accessed without Microsoft’s express written permission.</rights>

  <updated>2010-11-09T22:53:36Z</updated>

  <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-715')</id>

    <title type="text" />

    <updated>2010-11-09T22:53:36Z</updated>

    <content type="application/xml">

      <m:properties>

        <d:IsWiFiHotSpot m:type="Edm.Boolean">1</d:IsWiFiHotSpot>

      </m:properties>

    </content>

  </entry>

  <entry>




                                                                                             208
<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-661')</id>

   <title type="text" />

   <updated>2010-11-09T22:53:36Z</updated>

   <content type="application/xml">

     <m:properties>

       <d:IsWiFiHotSpot m:type="Edm.Boolean">0</d:IsWiFiHotSpot>

     </m:properties>

   </content>

 </entry>

 <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-736')</id>

   <title type="text" />

   <updated>2010-11-09T22:53:36Z</updated>

   <content type="application/xml">

     <m:properties>

       <d:IsWiFiHotSpot m:type="Edm.Boolean">0</d:IsWiFiHotSpot>

     </m:properties>

   </content>

 </entry>

 <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-685')</id>

   <title type="text" />

   <updated>2010-11-09T22:53:36Z</updated>

   <content type="application/xml">

     <m:properties>

       <d:IsWiFiHotSpot m:type="Edm.Boolean">0</d:IsWiFiHotSpot>

     </m:properties>

   </content>

 </entry>

                                                                                      209
    <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-700')</id>

     <title type="text" />

     <updated>2010-11-09T22:53:36Z</updated>

     <content type="application/xml">

       <m:properties>

          <d:IsWiFiHotSpot m:type="Edm.Boolean">0</d:IsWiFiHotSpot>

       </m:properties>

     </content>

    </entry>

</feed>



URL with JSON response


http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf94961

33d4f23/FourthCoffeeSample/FourthCoffeeShops?spatialFilter=nearby(27.894007,-
82.670776,2)&$filter=StoreType%20Eq%20'Coffee
Shop'&$select=IsWiFiHotSpot&$orderby=IsWiFiHotSpot&$format=json&key=queryKey




{

    "d":{

       "__copyright":"\u00a9 2011 Microsoft and its suppliers.       This API and any results
cannot be used or accessed without Microsoft’s express written permission.",

       "results":[

            {

                 "__metadata":{

                      "uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9
496133d4f23/FourthCoffeeSample/FourthCoffeeShops('-715')"

                 },

                 "IsWiFiHotSpot":true

            },

            {


                                                                                             210
                 "__metadata":{

                      "uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9
496133d4f23/FourthCoffeeSample/FourthCoffeeShops('-661')"

                 },

                 "IsWiFiHotSpot":false

            },

            {

                 "__metadata":{

                      "uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9
496133d4f23/FourthCoffeeSample/FourthCoffeeShops('-736')"

                 },

                 "IsWiFiHotSpot":false

            },

            {

                 "__metadata":{

                      "uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9
496133d4f23/FourthCoffeeSample/FourthCoffeeShops('-685')"

                 },

                 "IsWiFiHotSpot":false

            },

            {

                 "__metadata":{

                      "uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9
496133d4f23/FourthCoffeeSample/FourthCoffeeShops('-700')"

                 },

                 "IsWiFiHotSpot":false

            }

        ]

    }

}

EXAMPLE: Get entities using a wildcard search.
This example queries for coffee shops that are near a location and that have a primary city value
that begins with 'Clear'. The results show the display name, location and whether the location is
accessible by a wheel chair.
URL with Atom response

                                                                                              211
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops?spatialFilter=nearby(27.894007,-
82.670776,10)&$filter=StartsWith(PrimaryCity,'Clear')%20eq%20true&$orderby=IsWheelchairAc
cessible&$select=DisplayName,IsWheelChairAccessible,Latitude,Longitude&key=queryKey

<?xml version="1.0" encoding="utf-8"?>

<feed xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
xmlns="http://www.w3.org/2005/Atom">

 <title type="text"></title>

 <id>uuid:721f67c8-3f6e-49d0-ba89-938fc4d83391;id=36</id>

 <rights type="text">© 2012 Microsoft and its suppliers.     This API and any results
cannot be used or accessed without Microsoft's express written permission.</rights>

 <updated>2012-01-27T09:56:12Z</updated>

 <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-661')</id>

   <title type="text"></title>

   <updated>2012-01-27T09:56:12Z</updated>

   <content type="application/xml">

     <m:properties>

       <d:DisplayName>Fourth Coffee Store #661, Clearwater, FL, United
States</d:DisplayName>

       <d:IsWheelchairAccessible m:type="Edm.Boolean">1</d:IsWheelchairAccessible>

       <d:Latitude m:type="Edm.Double">27.894007</d:Latitude>

       <d:Longitude m:type="Edm.Double">-82.670776</d:Longitude>

     </m:properties>

   </content>

 </entry>

 <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-660')</id>

   <title type="text"></title>

   <updated>2012-01-27T09:56:12Z</updated>

   <content type="application/xml">

                                                                                        212
     <m:properties>

       <d:DisplayName>Fourth Coffee Store #660, Clearwater, FL, United
States</d:DisplayName>

       <d:IsWheelchairAccessible m:type="Edm.Boolean">1</d:IsWheelchairAccessible>

       <d:Latitude m:type="Edm.Double">27.893759</d:Latitude>

       <d:Longitude m:type="Edm.Double">-82.667436</d:Longitude>

     </m:properties>

   </content>

 </entry>

 <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-666')</id>

   <title type="text"></title>

   <updated>2012-01-27T09:56:12Z</updated>

   <content type="application/xml">

     <m:properties>

       <d:DisplayName>Fourth Coffee Store #666, Clearwater, FL, United
States</d:DisplayName>

       <d:IsWheelchairAccessible m:type="Edm.Boolean">1</d:IsWheelchairAccessible>

       <d:Latitude m:type="Edm.Double">27.899343</d:Latitude>

       <d:Longitude m:type="Edm.Double">-82.715604</d:Longitude>

     </m:properties>

   </content>

 </entry>

 <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-669')</id>

   <title type="text"></title>

   <updated>2012-01-27T09:56:12Z</updated>

   <content type="application/xml">

     <m:properties>

       <d:DisplayName>Fourth Coffee Store #669, Clearwater, FL, United
States</d:DisplayName>


                                                                                      213
          <d:IsWheelchairAccessible m:type="Edm.Boolean">0</d:IsWheelchairAccessible>

          <d:Latitude m:type="Edm.Double">27.916173</d:Latitude>

          <d:Longitude m:type="Edm.Double">-82.733002</d:Longitude>

       </m:properties>

     </content>

    </entry>

    <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-710')</id>

     <title type="text"></title>

     <updated>2012-01-27T09:56:12Z</updated>

     <content type="application/xml">

       <m:properties>

          <d:DisplayName>Fourth Coffee Store #710, Clearwater, FL, United
States</d:DisplayName>

          <d:IsWheelchairAccessible m:type="Edm.Boolean">0</d:IsWheelchairAccessible>

          <d:Latitude m:type="Edm.Double">27.960745</d:Latitude>

          <d:Longitude m:type="Edm.Double">-82.719151</d:Longitude>

       </m:properties>

     </content>

    </entry>

</feed>




URL with JSON response
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops?spatialFilter=nearby(27.894007,-
82.670776,10)&$filter=StartsWith(PrimaryCity,'Clear')%20eq%20true&$orderby=IsWheelchairAc
cessible&$select=DisplayName,IsWheelChairAccessible,Latitude,Longitude&$format=json&key=q
ueryKey

{

    "d":{


                                                                                        214
     "__copyright":"\u00a9 2012 Microsoft and its suppliers.    This API and any results
cannot be used or accessed without Microsoft's express written permission.",

     "results":[

        {

             "__metadata":{



"uri":"https:\/\/spatial.virtualearth.net\/REST\/v1\/data\/20181f26d9e94c81acdf9496133d4f
23\/FourthCoffeeSample\/FourthCoffeeShops('-661')"

             },

             "DisplayName":"Fourth Coffee Store #661, Clearwater, FL, United States",

             "IsWheelchairAccessible":true,

             "Latitude":27.894007,

             "Longitude":-82.670776

        },

        {

             "__metadata":{



"uri":"https:\/\/spatial.virtualearth.net\/REST\/v1\/data\/20181f26d9e94c81acdf9496133d4f
23\/FourthCoffeeSample\/FourthCoffeeShops('-660')"

             },

             "DisplayName":"Fourth Coffee Store #660, Clearwater, FL, United States",

             "IsWheelchairAccessible":true,

             "Latitude":27.893759,

             "Longitude":-82.667436

        },

        {

             "__metadata":{



"uri":"https:\/\/spatial.virtualearth.net\/REST\/v1\/data\/20181f26d9e94c81acdf9496133d4f
23\/FourthCoffeeSample\/FourthCoffeeShops('-666')"

             },

             "DisplayName":"Fourth Coffee Store #666, Clearwater, FL, United States",

             "IsWheelchairAccessible":true,

             "Latitude":27.899343,

             "Longitude":-82.715604


                                                                                        215
             },

             {

                  "__metadata":{



"uri":"https:\/\/spatial.virtualearth.net\/REST\/v1\/data\/20181f26d9e94c81acdf9496133d4f
23\/FourthCoffeeSample\/FourthCoffeeShops('-669')"

                  },

                  "DisplayName":"Fourth Coffee Store #669, Clearwater, FL, United States",

                  "IsWheelchairAccessible":false,

                  "Latitude":27.916173,

                  "Longitude":-82.733002

             },

             {

                  "__metadata":{



"uri":"https:\/\/spatial.virtualearth.net\/REST\/v1\/data\/20181f26d9e94c81acdf9496133d4f
23\/FourthCoffeeSample\/FourthCoffeeShops('-710')"

                  },

                  "DisplayName":"Fourth Coffee Store #710, Clearwater, FL, United States",

                  "IsWheelchairAccessible":false,

                  "Latitude":27.960745,

                  "Longitude":-82.719151

             }

         ]

     }

}


HTTP Status Codes


     For more details about these HTTP status codes, see Status Codes and Errors.
When the request is successful, the following HTTP status code is returned.
   200
When the request is not successful, the response returns one of the following errors.
   400
   401
   500
                                                                                             216
   503

See Also
Query by Area
Query by ID


Query by ID
Use the following URL to search a data source for one or more entities by entity ID. The property
to use as the entity ID is specified in the data schema for the entity type. For more information,
see Load Data Source Data Schema and Sample Input.

Supported HTTP Methods
GET, HEAD

URL template


     This template supports both HTTP and HTTPS protocols. URLs in the response use
     HTTPS protocol.
     A query response can contain a maximum number of 250 results.
Query for a single entity by specifying the entity ID string.


http://spatial.virtualearth.net/REST/v1/data/accessId/dataSourceName/entityTypeName(entit
yId)?jsonp=jsonCallBackFunction&jsonso=jsonState&key=queryKey

Query for multiple entities by specifying a list of entity ID strings.
You can query for up to 50 entity ID strings with this URL.
http://spatial.virtualearth.net/REST/v1/data/accessId/dataSourceName/entityTypeName?$filt
er=entityId in
(entityId1,entityId2,entityIdN)&queryoption1&queryoption2&queryoptionN&jsonp=jsonCallBack
Function&jsonso=jsonState&key=queryKey

Template Parameters


     Parameter names and values are not case-sensitive except for the queryKey parameter
     value.


Parameter                         Description     Values

accessId                          Required. A     A string containing and ID that is part of
                                  unique ID for   the URL structure that identifies the data
                                  the data        source.
                                  source.         Example:
                                                                                               217
Parameter                         Description      Values
                                                   20181f26d9e94c81acdf9496133d4f23

dataSourceName                    Required         A string that identifies the data source.
                                  The name of      Example: FourthCoffeeSample
                                  the data
                                  source that
                                  you want to
                                  search.

entityTypeName                    Required         A string that identifies the entity type of the
                                  The entity       data source.
                                  type to          Example: FourthCoffeeShops
                                  search for.

entityTypeName(entityTypeID)      Required         The entity type of the data source and the
                                  when             entity ID string to search for in the data
                                  searching        source defined by using the following
                                  for a single     format:
                                  entity. The      EntityTypeName(EntityIdString)
                                  entity type
                                                   Example: FourthCoffeeShops('4232')
                                  name and the
                                  entity ID
                                  string.

$filter=entityId in (entityId1,   Required         A list of entity ID strings to search for in the
entityId2, entityIdN              when             data source. You can specify up to 50
                                  searching        entity ID strings.
                                  for multiple     Example: $filter=entityId in ('4024', '234',
                                  entities. A      '8982')
                                  comma-
                                  separated list
                                  of entity ID
                                  strings to
                                  search for in
                                  the
                                  datasource.

queryOptions                      Optional.        A set of query options. Each query option
                                  Options for      is specified as an individual URL
                                  this query.      parameter. The following example shows
                                  For more         how to set both the $format and the
                                  information      $orderby query options in the URL.
                                  about query      &$format=json&$orderby=ZipCode
                                  options, see
                                                   Example: $top=3

                                                                                                      218
Parameter   Description      Values
            Query            Example: $filter=ZipCode Eq '98052'
            Options.         If the $orderby option is not specified as
                             part of the request, the results will be
                             sorted by the property that represents the
                             entity ID. Results are returned in
                             ascending order. You can specify up to
                             three (3) properties for the $orderby option.
                             You cannot use the latitude or longitude
                             properties to sort results.
                             You cannot use the latitude or longitude
                             properties to filter results by using the
                             $filter query option.

jsonp       Optional.        A string that contains the name of the
            Name of          callback function.
            JSON             Example: jsonp=MyCallbackFunction
            callback
            function that
            is called
            when the
            response to
            the request is
            received. The
            JSON object
            provided in
            the response
            is passed to
            the callback
            function.

jsonso      Optional.      Any valid JavaScript string.
            The state      Example: jsonso=abc3144sd
            object to pass
            to the JSON
            callback
            function. You
            can use a
            state object
            to match a
            response with
            a specific
            call. This

                                                                             219
Parameter                          Description      Values
                                   value is
                                   provided as
                                   the second
                                   parameter to
                                   the callback
                                   function
                                   provided in
                                   the JSONP
                                   parameter.

queryKey                           Required.         The Bing Maps Keys that you can use for
                                   The Bing         a data source are specified when the data
                                   Maps Key to      source is created. For example, there may
                                   use to access    be a single query key you must use to
                                   the data         query the data source or you may be able
                                   source.          to use any Bing Maps Key. For more
                                                    information about specifying query keys
                                                    when a data source is created, see Create
                                                    a Load Data Source Job and Input Entity
                                                    Data.
                                                    Example:
                                                    key=20181f26d9e94c81acdf9496133d4f23


Response
This URL supports the following response formats.
If the $orderby query option is not specified when you query for multiple entity IDs, the results will
be sorted by the property that is used for the entity ID. Results are returned in ascending order.
   Atom (application/atom + xml) [default]
   JSON (application/json)
When the output format is set to Atom, the results are returned in the response as one or more
Atom Entries. When information about a single entity is requested using the
entityTypeName(entityID) format , a single Atom Entry is returned. When the $filter=entityId in
(entityId1, entityId2, entityIdN) format is used to get entity information, a collection of Atom Entries
is returned as part of an Atom feed. For more information about these Atom response formats,
see OData AtomPub Format and the Atom examples in the Examples section.
When the output format is JSON, the response format for both type of requests is a collection of
JSON Entries in a “results” container. For more information about the JSON response format, see
OData: JavaScript Object Notation (JSON) Format and the JSON examples in the Examples
section.



                                                                                                    220
Examples
EXAMPLE: Get entity information by specifying the entity ID.
This example returns all property information for the FourthCoffeeShops entity with an entity ID of
'-22067'.
URL with Atom Response
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops('-22067')?key=queryKey




<entry xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"
xmlns="http://www.w3.org/2005/Atom">



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-22067')</id>

  <title type="text" />

  <updated>2011-01-11T02:22:18Z</updated>

  <content type="application/xml">

    <m:properties>

      <d:EntityID>-22067</d:EntityID>

      <d:Latitude m:type="Edm.Double">57.003766</d:Latitude>

      <d:Longitude m:type="Edm.Double">9.874434</d:Longitude>

      <d:AddressLine>Løven</d:AddressLine>

      <d:PrimaryCity>Aalborg</d:PrimaryCity>

      <d:Subdivision>Nordjyllands Amt</d:Subdivision>

      <d:PostalCode>9200</d:PostalCode>

      <d:Phone>0800-XXXXX</d:Phone>

      <d:SecondaryCity />

      <d:CountryRegion>Danmark</d:CountryRegion>

      <d:Name>Fourth Coffee Store #22067</d:Name>

      <d:DisplayName>Fourth Coffee Store #22067, Aalborg, Nordjyllands Amt,
Danmark</d:DisplayName>

      <d:Manager>Alan Steiner</d:Manager>

      <d:StoreOpen>Y</d:StoreOpen>

      <d:StoreType>Drive-Thru</d:StoreType>

                                                                                               221
       <d:SeatingCapacity m:type="Edm.Int64" m:null="true" />

       <d:Open m:type="Edm.Int64">700</d:Open>

       <d:Close m:type="Edm.Int64">1800</d:Close>

       <d:IsWiFiHotSpot m:type="Edm.Boolean">0</d:IsWiFiHotSpot>

       <d:IsWheelchairAccessible m:type="Edm.Boolean">0</d:IsWheelchairAccessible>

       <d:AcceptsOnlineOrders m:type="Edm.Boolean">0</d:AcceptsOnlineOrders>

       <d:AcceptsCoffeeCards m:type="Edm.Boolean">1</d:AcceptsCoffeeCards>

       <d:CreatedDate m:type="Edm.DateTime">2010-11-03T00:00:00</d:CreatedDate>

       <d:LastUpdatedDate m:type="Edm.DateTime">2010-11-03T23:31:36</d:LastUpdatedDate>

     </m:properties>

    </content>

    <rights type="text">© 2011 Microsoft and its suppliers. This API and any results cannot
be used or accessed without Microsoft’s express written permission.</rights>

</entry>



URL with JSON Response
The DateTime properties are specified in the JSON response by using the ODATA JSON
Serialization format for Edm.DateTime. This format uses the following formula:
"\/Date(<ticks>["+" | "-" <offset>)\/"
where:
<ticks> = number of milliseconds since midnight Jan 1, 1970
<offset> = number of minutes to add or subtract
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops('-22067')?$format=json&key=queryKey




{

    "d":{

       "__copyright":"\u00a9 2011 Microsoft and its suppliers.     This API and any results
cannot be used or accessed without Microsoft’s express written permission.",

       "__metadata":{



"uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fou
rthCoffeeSample/FourthCoffeeShops('-22067')"

       },

                                                                                          222
        "EntityID":"-22067",

        "Latitude":57.003766,

        "Longitude":9.874434,

        "AddressLine":"Løven",

        "PrimaryCity":"Aalborg",

        "Subdivision":"Nordjyllands Amt",

        "PostalCode":"9200",

        "Phone":"0800-XXXXX",

        "SecondaryCity":"",

        "CountryRegion":"Danmark",

        "Name":"Fourth Coffee Store #22067",

        "DisplayName":"Fourth Coffee Store #22067, Aalborg, Nordjyllands Amt, Danmark",

        "Manager":"Alan Steiner",

        "StoreOpen":"Y",

        "StoreType":"Drive-Thru",

        "SeatingCapacity":null,

        "Open":700,

        "Close":1800,

        "IsWiFiHotSpot":false,

        "IsWheelchairAccessible":false,

        "AcceptsOnlineOrders":false,

        "AcceptsCoffeeCards":true,

        "CreatedDate":"\/Date(634181256403200000)\/",

        "LastUpdatedDate":"\/Date(634182103363200000)\/"

    }

}




EXAMPLE: Get entity location information for two entity IDs
This example returns location information for the FourthCoffeeShops entities with entity IDs of '-
22067' and '-7891'.
URL with Atom Response


                                                                                                223
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops?$filter=entityId in('-22067','-
7891')&$select=Latitude,Longitude,AddressLine,PrimaryCity,PostalCode&key=queryKey




<feed xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
xmlns="http://www.w3.org/2005/Atom">

 <title type="text" />

 <id>uuid:d359c52a-63a7-469d-bad9-7b54baada637;id=54</id>

 <rights type="text">© 2011 Microsoft and its suppliers. This API and any results cannot
be used or accessed without Microsoft’s express written permission.</rights>

 <updated>2011-01-11T02:33:30Z</updated>

 <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-22067')</id>

   <title type="text" />

   <updated>2011-01-11T02:33:30Z</updated>

   <content type="application/xml">

     <m:properties>

       <d:Latitude m:type="Edm.Double">57.003766</d:Latitude>

       <d:Longitude m:type="Edm.Double">9.874434</d:Longitude>

       <d:AddressLine>Løven</d:AddressLine>

       <d:PrimaryCity>Aalborg</d:PrimaryCity>

       <d:PostalCode>9200</d:PostalCode>

     </m:properties>

   </content>

 </entry>

 <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-7891')</id>

   <title type="text" />


                                                                                      224
     <updated>2011-01-11T02:33:30Z</updated>

     <content type="application/xml">

        <m:properties>

          <d:Latitude m:type="Edm.Double">40.781604</d:Latitude>

          <d:Longitude m:type="Edm.Double">-74.181775</d:Longitude>

          <d:AddressLine>148 Franklin St</d:AddressLine>

          <d:PrimaryCity>Belleville</d:PrimaryCity>

          <d:PostalCode>07109</d:PostalCode>

        </m:properties>

     </content>

    </entry>

</feed>



URL with JSON Response
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe
eSample/FourthCoffeeShops?$filter=entityId in('-22067','-
7891')&$select=Latitude,Longitude,AddressLine,PrimaryCity,PostalCode&$format=json&key=que
ryKey




{

    "d":{

        "__copyright":"\u00a9
2011 Microsoft and its suppliers.        This API and any results cannot be used or accessed wi
thout Microsoft’s express written permission.",

        "results":[

            {

                "__metadata":{

                     "uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9
496133d4f23/FourthCoffeeSample/FourthCoffeeShops('-22067')"

                },

                "Latitude":57.003766,

                "Longitude":9.874434,

                "AddressLine":"Løven",


                                                                                            225
                  "PrimaryCity":"Aalborg",

                  "PostalCode":"9200"

             },

             {

                  "__metadata":{

                       "uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9
496133d4f23/FourthCoffeeSample/FourthCoffeeShops('-7891')"

                  },

                  "Latitude":40.781604,

                  "Longitude":-74.181775,

                  "AddressLine":"148 Franklin St",

                  "PrimaryCity":"Belleville",

                  "PostalCode":"07109"

             }

         ]

     }

}

HTTP Status Codes


     For more details about these HTTP status codes, see Status Codes and Errors.
When the request is successful, the following HTTP status code is returned.
   200
When the request is not successful, the response returns one of the following errors.
   400
   401
   500
   503

See Also
Query by Area
Query by Property


Query Options
When you use the Query API, you can specify query options that define what data is returned and
how it is formatted. Query options are specified as URL parameters. The query options used by
the Query API include a subset of the query options defined by an Open Data Protocol (OData)

                                                                                              226
specification. In addition to the OData query options, the Query API also provides custom query
options, such as a spatial filter. Use spatial filter to define the area to query.

OData Query Options


Query Option                Description                                OData Specification

$filter                     Specifies a conditional expression for a   $filter
                            list of properties and values.


                                 You cannot filter on the latitude
                                 and longitude entity properties.
                            The Query API supports logical
                            operators and precedence grouping.
                            For a complete list of the supported
                            operators, see the Supported $filter
                            Operators section below.
                            The Query API also supports the
                            StartsWith and EndsWith functions to
                            perform wildcard searches. Only one
                            wildcard search can be performed at a
                            time, and wildcard searches cannot be
                            combined with additional $filter
                            expressions. Wildcard searches are not
                            supported for NavteqNA and NavteqEU
                            data sources. For more information, see
                            The Wildcard Search Functions
                            section below.
                            Examples:
                               $filter=City Eq 'Seattle' And
                                 OpenOnSunday Eq 'Y'
                               $filter=StartsWith(Locality,'San')

$format                     Specifies the format of the HTTP     $format
                            response. The supported formats for
                            the Query API are JSON and Atom. The
                            default format is Atom.
                            Example: $format=json

$inlinecount                Specifies whether or not to return a       $inlinecount
                            count of the results in the response.
                            Possible values for this query option
                            include:

                                                                                             227
Query Option   Description                                   OData Specification
                  allpages
                  none [default]
               Example: $inlinecount=allpages

$orderby       Specifies one or more properties to use       $orderby
               to sort the results of a query. You can
               specify up to three (3) properties.
               Results are sorted in ascending order.
               Each type of query, such as Query by
               ID or Query by Property, has a default
               sort order for query results. If the
               $orderby option is not specified, query
               results are sorted using the default sort
               for that query type. For information
               about the default sort rules, see the
               documentation for each query type.


                    You cannot use the latitude and
                    longitude properties to sort
                    results. You can use the
                    elevation property.


                    When you specify the $orderby
                    query option, you must also
                    specify a spatial filter or a $filter
                    query option. For information
                    about spatial filters, see Query
                    by Area.
               Example: $orderby=PostalCode

$select        Specifies the data source properties to       $select
               return in the response. If the $select
               query option is not specified or if it is set
               to "*" ($select=*), all data source
               properties are returned.
               Example: $select=Name,Phone

$skip          Specifies to not return a specified           $skip
               number of query results. For example, if
               this value is set to 50, then the first
               result that is returned is the 51st result.

                                                                                   228
Query Option                 Description                                  OData Specification
                             You can use the $skip query option with
                             the $top query option to display a
                             subset of the query results. For
                             example, the following parameter
                             combinations provide sets of 10 results
                             at a time.
                             &$skip=0&$top=10 [provides results 1
                             to 10]
                             &$skip=10&$top=10 [provides results
                             11 to 20]
                             Example: $skip=10

$top                         Specifies the maximum number of              $top
                             results to return for a query. The default
                             value is 25. The maximum number that
                             the Query API can return is 250 results.
                             Example: $top=10


Supported $filter Comparison Operators


      When you are performing a StartsWith or EndsWith wildcard search, you cannot use the
      And or Or comparison operators to combine multiple $filter expressions.


Operator                                           Description

Logical Operators

Eq                                                 Equal

Ne                                                 Not equal

Gt                                                 Greater than

Ge                                                 Greater than or equal

Lt                                                 Less than

Le                                                 Less than or equal

And                                                Logical and


                                                       Not supported when combined with
                                                       StartsWith or EndsWith wildcard


                                                                                                229
Operator                                           Description
                                                        searches.

Or                                                 Logical or


                                                        Not supported when combined with
                                                        StartsWith or EndsWith wildcard
                                                        searches.

Not                                                Logical negation

Grouping Operator

()                                                 Precedence grouping



Wildcard Search Functions


      Wildcard searches are not supported for NavteqNA and NavteqEU data sources.
      Wildcard searches do not support And or Or comparison operators. Therefore, you
      cannot combine a wildcard search with additional $filter expressions, and you cannot
      request more than one wildcard search at a time.


$filter=StartsWith(property,searchString) eq       Finds all property values that start with
true                                               „searchString‟.
                                                   Example:$filter=StartsWith(Locality,'San') eq
                                                   true

$filter=EndsWith(property,searchString) eq true    Finds all property values that end with
                                                   'searchString'
                                                   Example:$filter=EndsWith(Locality,'York') eq
                                                   true


Spatial Filter Query Options
Use the spatial filter in your query to set the area to search. The Query API offers three spatial
filters.
Search a set distance from a location
spatialFilter=nearby(latitude,longitude,maximum distance in kilometers)

Search in a bounding box (an area defined by pairs of longitude and latitude values)
spatialFilter=bbox(South Latitude,West Longitude,North Latitude,East Longitude)



                                                                                                     230
Search near a route
When you perform a nearRoute search, entities that are within one (1) mile or 1.6 kilometers are
returned.
spatialFilter=nearRoute(latitude or address of route start,longitude or address of route
end)


Query Response Description
When you query a data source using the Query API, the response returns a list of entities that
met the query criteria. Information returned for each entity includes a Query by ID URL that
returns the complete information for that entity. Depending on the query options, all or a subset of
the entity properties are also returned.
If a response format is not specified by using the $format query option, the results are returned in
ATOM format. You can also set the $format parameter to json if you want to have the response
returned in JSON format.
The data schema for the query is based on the OData AtomPub Format for ATOM responses and
the OData: JavaScript Object Notation (JSON) Format for JSON responses. More details and
example responses for each type of query are found in the specific query topics.

Query API Response Examples
The following examples show sample responses for a Query API. The property names, such as
IsWiFiHotSpot, are the names assigned to these properties according to the data source schema.
ATOM Example
<feed xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
xmlns="http://www.w3.org/2005/Atom">

  <title type="text" />

  <id>uuid:876b2e49-e480-40b8-8282-9929ced06f7f;id=46</id>

  <updated>2010-11-09T22:53:36Z</updated>

  <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-715')</id>

    <title type="text" />

    <updated>2010-11-09T22:53:36Z</updated>

    <content type="application/xml">

       <m:properties>

        <d:IsWiFiHotSpot m:type="Edm.Boolean">1</d:IsWiFiHotSpot>

        <d:LastUpdatedDate m:type="Edm.DateTime">2010-11-03T23:31:37</d:LastUpdatedDate>

                                                                                                231
       </m:properties>

     </content>

    </entry>

    <entry>



<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth
CoffeeSample/FourthCoffeeShops('-661')</id>

     <title type="text" />

     <updated>2010-11-09T22:53:36Z</updated>

     <content type="application/xml">

       <m:properties>

          <d:IsWiFiHotSpot m:type="Edm.Boolean">0</d:IsWiFiHotSpot>

          <d:LastUpdatedDate m:type="Edm.DateTime">2010-11-03T00:00:00</d:LastUpdatedDate>

       </m:properties>

     </content>

    </entry>

</feed>



JSON Example


     The DateTime properties are specified in the JSON response by using the ODATA JSON
     Serialization format for Edm.DateTime. This format uses the following formula:
     "\/Date(<ticks>["+" | "-" <offset>)\/"
     where:
     <ticks> = number of milliseconds since midnight Jan 1, 1970
     <offset> = number of minutes to add or subtract
{

    "d":{

       "results":[

            {

                "__metadata":{

                     "uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9
496133d4f23/FourthCoffeeSample/FourthCoffeeShops('-715')"

                },

                "IsWiFiHotSpot":true

                                                                                            232
                 "LastUpdatedDate":"\/Date(634182103373200000)\/"

            },

            {

                 "__metadata":{

                      "uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9
496133d4f23/FourthCoffeeSample/FourthCoffeeShops('-661')"

                 },

                 "IsWiFiHotSpot":false

                 "LastUpdatedDate":"\/Date(634181256403200000)\/"

            },

        ]

    }

}


Query API Sample Code (C#)
The following C# code provides examples of how to query a data source using the Query API.
using System;

using System.Net;

using System.Xml;

namespace QueryAPIExamples

{

    /// <summary>

    /// Using the Spatial Data Services Query API to query the test data source
FourthCoffeeSample

    /// </summary>

    public class SpatialDataQuerying

    {



    string BingMapsKey = "InsertYourBngMapsKeyHere";



    string DataSourceID = "20181f26d9e94c81acdf9496133d4f23";

    static void Main()

    {

        SpatialDataQuerying queryTest = new SpatialDataQuerying();



                                                                                             233
     queryTest.RunExampleQueries();

     Console.ReadLine();



}



#region Run the Queries



/// <summary>

/// Run the Bing Spatial Data Query examples in this class.

/// Requires the spatial data to already be uploaded.

/// </summary>

public void RunExampleQueries()

{

    ExampleFindByAreaRadius();

    ExampleFindByBoundingBox();

    ExampleFindByProperty();

    ExampleQueryByIdAtom();

    // ExampleQueryByIdJson();

}

#endregion



#region Query By Area

public void ExampleFindByAreaRadius()

{

     Console.WriteLine("\nExampleFindByAreaRadius");



    // Find all previously uploaded MyShops entities located within

    // a certain radius around a point.

    // Custom name of spatial data source created during upload

    string dataSourceName = "FourthCoffeeSample";

    // Name of entities in the data source

    string dataEntityName = "FourthCoffeeShops";

    // Unique access ID assigned to your data source by Bing Maps

    // e.g. f8986xxxxxxxc844b

                                                                      234
       string accessId = DataSourceID;

       // Your Bing Maps Spatial Data Services query key.

       string bingMapsKey = BingMapsKey;

       // Coordinates of the point to search from.

       double SearchLatitude = 47.63674;

       double SearchLongitude =   - 122.30413;

       // Search radius

       double Radius = 3; // km

       // Setup REST request to query our uploaded customer data

       string requestUrl =
string.Format("http://spatial.virtualearth.net/REST/v1/data/{0}/{1}/{2}" +

        "?spatialFilter=nearby({3},{4},{5})&key={6}",accessId,dataSourceName,

        dataEntityName,SearchLatitude, SearchLongitude, Radius, bingMapsKey);

       // Send the request and get back an XML response.

       XmlDocument response = GetXmlResponse(requestUrl);

       // Display each entity's info.

       ProcessEntityElements(response);

   }

   #endregion



   #region Helper Methods




   public static XmlDocument GetXmlResponse(string requestUrl)

   {

        try

        {

              HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;

              HttpWebResponse response = request.GetResponse() as HttpWebResponse;



              XmlDocument xmlDoc = new XmlDocument();

              xmlDoc.Load(response.GetResponseStream());

              return (xmlDoc);




                                                                                          235
        }

        catch (Exception e)

        {

             Console.WriteLine(e.Message);



             Console.Read();

             return null;

        }

}



/// <summary>

/// Display each "entry" in the Bing Spatial Data Services Atom (XML) response.

/// </summary>

/// <param name="entryElements"></param>

private void ProcessEntityElements(XmlDocument response)

{

    XmlNodeList entryElements = response.GetElementsByTagName("entry");

    for (int i = 0; i <= entryElements.Count - 1; i++)

    {

        XmlElement element = (XmlElement)entryElements[i];

        XmlElement contentElement = (XmlElement)element.GetElementsByTagName(

            "content")[0];

        XmlElement propElement = (XmlElement)

            contentElement.GetElementsByTagName("m:properties")[0];

        XmlNode nameElement = propElement.GetElementsByTagName("d:Name")[0];

        if (nameElement == null)

            throw new Exception("Name not found");

        XmlNode latElement = propElement.GetElementsByTagName("d:Latitude")[0];

        if (latElement == null)

            throw new Exception("Latitude not found");

        XmlNode longElement = propElement.GetElementsByTagName("d:Longitude")

            [0];

        if (longElement == null)

            throw new Exception("Longitude not found");

                                                                                  236
        string name = nameElement.InnerText;

        double latitude = 0;

        Double.TryParse(latElement.InnerText, out latitude);

        double longitude = 0;

        Double.TryParse(longElement.InnerText, out longitude);

        Console.WriteLine("Coordinates of '{0}': {1}, {2}", name, latitude,

         longitude);

    }

}

#endregion



#region Query by Property

public void ExampleFindByProperty()

{

        Console.WriteLine("\nExampleFindByProperty");

    // Find all previously uploaded MyShops entities that accept

    // online orders.

    // Custom name of spatial data source created during upload

    string dataSourceName = "FourthCoffeeSample";

    // Name of entities in the data source

    string dataEntityName = "FourthCoffeeShops";

    // Unique access ID assigned to your data source by Bing Maps

    // e.g. f8986xxxxxxxc844b

    string accessId = DataSourceID;

    // Your Bing Maps Spatial Data Services query key.

    string bingMapsKey = BingMapsKey;

    // Setup REST request to query our uploaded customer data

    string requestUrl = String.Format(

        "http://spatial.virtualearth.net/REST/v1/data/{0}/{1}/{2}" +

        "?$filter=AcceptsOnlineOrders Eq True&key={3}", accessId,

        dataSourceName, dataEntityName, bingMapsKey);

    // Send the request and get back an XML response.

    XmlDocument response = GetXmlResponse(requestUrl);

    // Display each entity's info.

                                                                              237
    ProcessEntityElements(response);

}

#endregion



#region Query by Bounding Box

public void ExampleFindByBoundingBox()

{

     Console.WriteLine("\nExampleFindByBoundingBox");

    // Find all previously uploaded MyShops entities located within

    // the specified bounding box.

    // Custom name of spatial data source created during upload

     string dataSourceName = "FourthCoffeeSample";

     // Name of entities in the data source

     string dataEntityName = "FourthCoffeeShops";

    // Unique access ID assigned to your data source by Bing Maps

    // e.g. f8986xxxxxxxc844b

    string accessId = DataSourceID;

    // Your Bing Maps Spatial Data Services query key.

    string bingMapsKey = BingMapsKey;

    // Coordinates of the bounding box's corners

    double lat1 = 47.61247675940658;

    double long1 =   - 122.3237670214032;

    double lat2 = 47.68239156080077;

    double long2 =   - 122.27996173131822;

    // Setup REST request to query our uploaded customer data

    string requestUrl = String.Format(

     "http://spatial.virtualearth.net/REST/v1/data/{0}/{1}/{2}" +

     "?spatialFilter=bbox({3},{4},{5},{6})&key={7}", accessId,

     dataSourceName, dataEntityName, lat1, long1, lat2, long2, bingMapsKey);

    // Send the request and get back an XML response.

    XmlDocument response = GetXmlResponse(requestUrl);

    // Display each entity's info.

    ProcessEntityElements(response);

}

                                                                               238
   #endregion



   #region Query By ID

   /// <summary>

   /// Query by ID using ATOM protocol

   /// </summary>

   public void ExampleQueryByIdAtom()

   {

        Console.WriteLine("\nExampleQueryByIdAtom");

       //
http://spatial.virtualearth.net/REST/v1/data/accessId/dataSourceName/entityTypeName('enti
tyId')?key=queryKey

       //
http://spatial.virtualearth.net/REST/v1/data/f8986xxxxxxxc844b/MyShopsSample/MyShops('1')
?key=queryKey

       // Custom name of spatial data source created during upload

    string dataSourceName = "FourthCoffeeSample";

       // Name of entities in the data source

       string dataEntityName = "FourthCoffeeShops";

       // Unique access ID assigned to your data source by Bing Maps

       // e.g. f8986xxxxxxxc844b

       string accessId = DataSourceID;

       // ID of the entity to search for

       int entityId = -22067;

       // Your Bing Maps Spatial Data Services query key.

       string bingMapsKey = BingMapsKey;

       string requestUrl = string.Format("http://spatial.virtualearth.net" +

        "/REST/v1/data/{0}/{1}/{2}('{3}')?key={4}", accessId, dataSourceName,

        dataEntityName, entityId, bingMapsKey);

       // By default, the Spatial Data API returns

       // data responses in Atom (xml) format.

       XmlDocument xmlResponse = GetXmlResponse(requestUrl);

       // Select the first shop data in the xml results.

       XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlResponse.NameTable);



                                                                                      239
            nsmgr.AddNamespace("a", "http://www.w3.org/2005/Atom");

            nsmgr.AddNamespace("m",

             "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");

            nsmgr.AddNamespace("d",

             "http://schemas.microsoft.com/ado/2007/08/dataservices");

            XmlNode firstShopNode = xmlResponse.SelectSingleNode(

             "//a:entry/a:content/m:properties", nsmgr);

            // Extract result data from the xml nodes.

            int retrievedEntityId = int.Parse(firstShopNode.SelectSingleNode(

             "d:EntityID", nsmgr).FirstChild.Value);

            string postalCode = firstShopNode.SelectSingleNode(

             "d:PostalCode", nsmgr).FirstChild.Value;

            double latitude = double.Parse(firstShopNode.SelectSingleNode(

             "d:Latitude", nsmgr).FirstChild.Value);

            double longitude = double.Parse(firstShopNode.SelectSingleNode(

             "d:Longitude", nsmgr).FirstChild.Value);

            Console.WriteLine(string.Format("Found EntityID {0} Postal Code: {1} Lat,Lon:
({2},{3})",

               retrievedEntityId,postalCode, latitude, longitude));

        }



        #endregion;




    }

}




Query API Sample Code (VB)
The following Visual Basic code provides examples of how to query a data source using the
Query API.
Imports System

Imports System.Net



                                                                                            240
Imports System.Xml

Imports Microsoft.VisualBasic

''' <summary>

''' Using the Spatial Data Services Query API to query the test data source
FourthCoffeeSample

''' </summary>

Public Class SpatialDataQuerying



   Private MyKey As String = "InsertYourBingMapsKey"



   Private DataSourceID As String = "20181f26d9e94c81acdf9496133d4f23"




#Region "Run the Queries"



   ''' <summary>

   ''' Run the Bing Spatial Data Query examples in this class.

   ''' Requires the spatial data to already be uploaded.

   ''' </summary>

   Public Sub RunExampleQueries()

       ExampleFindByAreaRadius()

       ExampleFindByBoundingBox()

       ExampleFindByProperty()

       ExampleQueryByIdAtom()

       ' ExampleQueryByIdJson();

   End Sub

#End Region



#Region "Query By Area"

   Public Sub ExampleFindByAreaRadius()

       Console.WriteLine(vbLf & "ExampleFindByAreaRadius")



       ' Find all previously uploaded MyShops entities located within

       ' a certain radius around a point.


                                                                              241
       ' Custom name of spatial data source created during upload

       Dim dataSourceName As String = "FourthCoffeeSample"

       ' Name of entities in the data source

       Dim dataEntityName As String = "FourthCoffeeShops"

       ' Unique access ID assigned to your data source by Bing Maps

       ' e.g. f8986xxxxxxxc844b

       Dim accessId As String = DataSourceID

       ' Your Bing Maps Spatial Data Services query key.

       Dim bingMapsKey As String = MyKey

       ' Coordinates of the point to search from.

       Dim SearchLatitude As Double = 47.63674

       Dim SearchLongitude As Double = -122.30413

       ' Search radius

       Dim Radius As Double = 3 ' km

       ' Setup REST request to query our uploaded customer data

       Dim requestUrl As String =
String.Format("http://spatial.virtualearth.net/REST/v1/data/{0}/{1}/{2}" &
"?spatialFilter=nearby({3},{4},{5})&key={6}", accessId, dataSourceName, dataEntityName,
SearchLatitude, SearchLongitude, Radius, MyKey)

       ' Send the request and get back an XML response.

       Dim response As XmlDocument = GetXmlResponse(requestUrl)

       ' Display each entity's info.

       ProcessEntityElements(response)

   End Sub

#End Region



#Region "Helper Methods"




   Public Shared Function GetXmlResponse(ByVal requestUrl As String) As XmlDocument

       Try

              Dim request As HttpWebRequest = TryCast(WebRequest.Create(requestUrl),
HttpWebRequest)

              Dim response As HttpWebResponse = TryCast(request.GetResponse(),
HttpWebResponse)

                                                                                       242
           Dim xmlDoc As New XmlDocument()

           xmlDoc.Load(response.GetResponseStream())

           Return (xmlDoc)



       Catch e As Exception

           Console.WriteLine(e.Message)



           Console.Read()

           Return Nothing

       End Try

   End Function



   ''' <summary>

   ''' Display each "entry" in the Bing Spatial Data Services Atom (XML) response.

   ''' </summary>>

   Private Sub ProcessEntityElements(ByVal response As XmlDocument)

       Dim entryElements As XmlNodeList = response.GetElementsByTagName("entry")

       For i As Integer = 0 To entryElements.Count - 1

           Dim element As XmlElement = CType(entryElements(i), XmlElement)

           Dim contentElement As XmlElement =
CType(element.GetElementsByTagName("content")(0), XmlElement)

           Dim propElement As XmlElement =
CType(contentElement.GetElementsByTagName("m:properties")(0), XmlElement)

           Dim nameElement As XmlNode = propElement.GetElementsByTagName("d:Name")(0)

           If nameElement Is Nothing Then

                 Throw New Exception("Name not found")

           End If

           Dim latElement As XmlNode = propElement.GetElementsByTagName("d:Latitude")(0)

           If latElement Is Nothing Then

                 Throw New Exception("Latitude not found")

           End If

           Dim longElement As XmlNode =
propElement.GetElementsByTagName("d:Longitude")(0)


                                                                                        243
              If longElement Is Nothing Then

                  Throw New Exception("Longitude not found")

              End If

              Dim name As String = nameElement.InnerText

              Dim latitude As Double = 0

              Double.TryParse(latElement.InnerText, latitude)

              Dim longitude As Double = 0

              Double.TryParse(longElement.InnerText, longitude)

              Console.WriteLine("Coordinates of '{0}': {1}, {2}", name, latitude,
longitude)

         Next i

   End Sub

#End Region



#Region "Query by Property"

   Public Sub ExampleFindByProperty()

         Console.WriteLine(vbLf & "ExampleFindByProperty")

         ' Find all previously uploaded MyShops entities that accept

         ' online orders.

         ' Custom name of spatial data source created during upload

         Dim dataSourceName As String = "FourthCoffeeSample"

         ' Name of entities in the data source

         Dim dataEntityName As String = "FourthCoffeeShops"

         ' Unique access ID assigned to your data source by Bing Maps

         ' e.g. f8986xxxxxxxc844b

         Dim accessId As String = DataSourceID

         ' Your Bing Maps Spatial Data Services query key.

         Dim bingMapsKey As String = MyKey

         ' Setup REST request to query our uploaded customer data

         Dim requestUrl As String =
String.Format("http://spatial.virtualearth.net/REST/v1/data/{0}/{1}/{2}" &
"?$filter=AcceptsOnlineOrders Eq True&key={3}", accessId, dataSourceName, dataEntityName,
MyKey)

         ' Send the request and get back an XML response.



                                                                                      244
       Dim response As XmlDocument = GetXmlResponse(requestUrl)

       ' Display each entity's info.

       ProcessEntityElements(response)

   End Sub

#End Region



#Region "Query by Bounding Box"

   Public Sub ExampleFindByBoundingBox()

       Console.WriteLine(vbLf & "ExampleFindByBoundingBox")

       ' Find all previously uploaded MyShops entities located within

       ' the specified bounding box.

       ' Custom name of spatial data source created during upload

       Dim dataSourceName As String = "FourthCoffeeSample"

       ' Name of entities in the data source

       Dim dataEntityName As String = "FourthCoffeeShops"

       ' Unique access ID assigned to your data source by Bing Maps

       ' e.g. f8986xxxxxxxc844b

       Dim accessId As String = DataSourceID

       ' Your Bing Maps Spatial Data Services query key.

       Dim bingMapsKey As String = MyKey

       ' Coordinates of the bounding box's corners

       Dim lat1 As Double = 47.612476759406583

       Dim long1 As Double = -122.3237670214032

       Dim lat2 As Double = 47.682391560800767

       Dim long2 As Double = -122.27996173131822

       ' Setup REST request to query our uploaded customer data

       Dim requestUrl As String =
String.Format("http://spatial.virtualearth.net/REST/v1/data/{0}/{1}/{2}" &
"?spatialFilter=bbox({3},{4},{5},{6})&key={7}", accessId, dataSourceName, dataEntityName,
lat1, long1, lat2, long2, MyKey)

       ' Send the request and get back an XML response.

       Dim response As XmlDocument = GetXmlResponse(requestUrl)

       ' Display each entity's info.

       ProcessEntityElements(response)


                                                                                      245
   End Sub

#End Region




#Region "Query By ID"

   ''' <summary>

   ''' Query by ID using ATOM protocol

   ''' </summary>

   Public Sub ExampleQueryByIdAtom()

       Console.WriteLine(vbLf & "ExampleQueryByIdAtom")

       '
http://spatial.virtualearth.net/REST/v1/data/accessId/dataSourceName/entityTypeName('enti
tyId')?key=queryKey

       '
http://spatial.virtualearth.net/REST/v1/data/f8986xxxxxxxc844b/MyShopsSample/MyShops('1')
?key=queryKey

       ' Custom name of spatial data source created during upload

       Dim dataSourceName As String = "FourthCoffeeSample"

       ' Name of entities in the data source

       Dim dataEntityName As String = "FourthCoffeeShops"

       ' Unique access ID assigned to your data source by Bing Maps

       ' e.g. f8986xxxxxxxc844b

       Dim accessId As String = DataSourceID

       ' ID of the entity to search for

       Dim entityId As Integer = -22067

       ' Your Bing Maps Spatial Data Services query key.

       Dim bingMapsKey As String = MyKey

       Dim requestUrl As String = String.Format("http://spatial.virtualearth.net" &
"/REST/v1/data/{0}/{1}/{2}('{3}')?key={4}", accessId, dataSourceName, dataEntityName,
entityId, MyKey)

       ' By default, the Spatial Data API returns

       ' data responses in Atom (xml) format.

       Dim xmlResponse As XmlDocument = GetXmlResponse(requestUrl)

       ' Select the first shop data in the xml results.

       Dim nsmgr As New XmlNamespaceManager(xmlResponse.NameTable)

                                                                                        246
        nsmgr.AddNamespace("a", "http://www.w3.org/2005/Atom")

        nsmgr.AddNamespace("m",
"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata")

        nsmgr.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices")

        Dim firstShopNode As XmlNode =
xmlResponse.SelectSingleNode("//a:entry/a:content/m:properties", nsmgr)

        ' Extract result data from the xml nodes.

        Dim retrievedEntityId As Integer =
Integer.Parse(firstShopNode.SelectSingleNode("d:EntityID", nsmgr).FirstChild.Value)

        Dim postalCode As String = firstShopNode.SelectSingleNode("d:PostalCode",
nsmgr).FirstChild.Value

        Dim latitude As Double =
Double.Parse(firstShopNode.SelectSingleNode("d:Latitude", nsmgr).FirstChild.Value)

        Dim longitude As Double =
Double.Parse(firstShopNode.SelectSingleNode("d:Longitude", nsmgr).FirstChild.Value)

        Console.WriteLine(String.Format("Found EntityID {0} Postal Code: {1} Lat,Lon:
({2},{3})", retrievedEntityId, postalCode, latitude, longitude))

    End Sub



#End Region ';




End Class




Status Codes and Errors
Each response to a request provides an HTTP status code. This article describes these codes.


HTTP Status Codes
The following table lists the most common HTTP status codes. Additional information may be
provided with a specific request.


                                                                                             247
HTTP Status Code   Short Description       Details

200                OK                      The request is successful.

201                Created                 A new resource is created.

202                Accepted                The request has been accepted
                                           for processing.

400                Bad Request             The request contained an error.

401                Unauthorized            Access was denied. You may
                                           have entered your credentials
                                           incorrectly, or you might not
                                           have access to the requested
                                           resource or operation.

403                Forbidden               The request is for something
                                           forbidden. Authorization will not
                                           help.

404                Not Found               The requested resource was
                                           not found.

500                Internal Server Error   Your request could not be
                                           completed because there was a
                                           problem with the service.

503                Service Unavailable     There's a problem with the
                                           service right now. Please try
                                           again later.




                                                                           248

				
DOCUMENT INFO
Shared By:
Categories:
Tags: bing.pdf
Stats:
views:98
posted:5/8/2012
language:English
pages:248