You are on page 1of 155

Contents

Bing Spatial Data Services .............................................................................................................. 2 Getting Started with the Spatial Data Services ............................................................................ 3 Bing Spatial Data Services API Reference .................................................................................. 4 Dataflow and Data Source Job Requirements ......................................................................... 5 Geocode Dataflow API ............................................................................................................. 5 Create a Geocode Job and Upload Data .............................................................................. 7 Get Status of a Geocode Job .............................................................................................. 13 Download Geocode Job Results ......................................................................................... 17 Geocode Dataflow Response Description .......................................................................... 21 Geocode Dataflow Walkthrough .......................................................................................... 28 Geocode Dataflow Sample Code ........................................................................................ 35 Geocode Dataflow Data Schema ........................................................................................ 45 Geocode Dataflow Sample Input and Output Data ............................................................. 53 Entity Types ......................................................................................................................... 65 Data Source Management API ............................................................................................... 77 Load Data Source Dataflow ................................................................................................ 78 Create a Load Data Source Job and Input Entity Data.................................................... 79 Get Status of a Load Data Source Job ............................................................................ 88 Load Data Source Dataflow Response Description ......................................................... 95 Load Data Source Data Schema and Sample Input ...................................................... 102 Get Data Source Information ............................................................................................. 108 Delete a Data Source ........................................................................................................ 115 Query API ............................................................................................................................. 117 Query by Area ................................................................................................................... 118 Query by Property ............................................................................................................. 132 Query by ID ....................................................................................................................... 139 Query Options ................................................................................................................... 149 Query Response Description ............................................................................................ 152 Status Codes and Errors ...................................................................................................... 154

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. 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 to search for entities in a particular area. You can also Query by Property and Query by ID.

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. If you are reading this SDK online, you can download the Bing Spatial Data Services SDK CHM file or PDF file for offline viewing. The Bing Spatial Data Services documentation contains reference topics for the following API: Geocode Dataflow API Data Source Management API Use this API to geocode a set of spatial data. 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. Use this API to query a data source.

Query API

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.

Bing Spatial Data Services API Reference

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

Getting Started with the Spatial Data Services


The Bing Spatial Data Services provide 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 Developer Account


To use the Bing Spatial Data Services, you must have a Bing Maps Developer Account. Once you have a Bing Maps Developer Account, you can create Bing Maps Key to use with the Bing Spatial Data Services. For information about getting a Bing Maps Developer Account and Bing Maps Keys, see Getting a Bing Maps Key.

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. If you are an enterprise customer, you can use the Bing Maps Account Center (https://www.bingmapsportal.com) to geocode and publish data to a new data source. For more information, see Geocode and Publish Entity Data to a Data Source.

How to: Update a data source


Use the Load Data Source Dataflow to update an existing data source. If you are an enterprise customer, you can use the Bing Maps Account Center (https://www.bingmapsportal.com) to geocode and publish data to an existing data source. For more information, see Geocode and Publish Entity Data to a Data Source.

How to: Delete a data source


Use the Delete a Data Source API to delete 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 Developer Account.

How to: Query a data source


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

Sample Data Source: FourthCoffeeSample


FourthCoffeeSample is the name of a sample data source that you can use to learn about the Query API. You can also use it to learn how to get information about a data source by using the Data Source Management API. The FourthCoffeeSample data source contains an entity type named FourthCoffeeShops. You can use any Bing Maps Key to query this data source. 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. To find out the entity properties for this datasource, use the following URL by replacing YourBingMapsKey with any Bing Maps Key.
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe eSample/$metadata?key=YourBingMapsKey

To query this data source, use the following base URL. See the Query API for URL templates and examples.
http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe eSample/FourthCoffeeShops

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.

Bing Spatial Data Services API Reference


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

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. 4

Geocode Dataflow API Data Source Management API Query API

Describes the API that geocodes sets of spatial data. Describes the API that creates and manages data sources. Describes the API that queries a data source. You can query for entities in a given area or search by entity property or ID. Describes the HTTP errors that can occur when you use the Bing Spatial Data Services APIs.

Status Codes and Errors

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 Developer Account. You can run a total of 50 dataflow and data source jobs in a 24 hour period for a Bing Maps Developer 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 Developer 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. 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 reversegeocode 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. 5

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 Get Status of a Geocode Job Download Geocode Job Results Geocode Dataflow Response Description Geocode Dataflow Walkthrough Geocode Dataflow Sample Code Geocode Dataflow Data Schema Geocode Dataflow Sample Input and Output Data Describes how to create a job to geocode and reverse-geocode the data. Describes how to get the status of a geocode job. Describes how to download geocoded results. Describes the information returned in the HTTP responses. Provides a detailed overview of how to use the Geocode Dataflow. Provides complete sample code that uses the Geocode Dataflow to geocode data. Describes the data schema for the input data and the geocoded results. Shows examples of all types of accepted input formats. This includes XML examples and examples of sets of values separated by pipe (|), comma, or tab characters Provides a list of supported entity types. 6

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 reversegeocode 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.
Parameter Alia s Description Values

dataLocati on

Optional. Specifies the location of the data to download.

A Windows Azure Blob Service location that contains the data to process. The data must be in XML format. The Blob Service uses the following URL formats: http://account-name.blob.core.windows.net/myDataFile https://account-name.blob.core.windows.net/myDataFile For more information, see Addressing Blob Service Requests. Before you make your request to start the dataflow job, make sure that the Blob Service URL is available publicly or shared with a signature key. If the URL is shared with 7

You must set the dataLocati on parameter

Parameter

Alia s

Description

Values

to the location of the data or include the data to process in the HTTP request. If you do both, the URL returns an error. description Optional. A description of the geocode dataflow. Required. The format of the input data file.

a signature key, it must be encoded. For more information, see Managing Access to Containers and Blobs. The following content types are supported for data that is retrieved from an HTTP server. application/xml text/xml text/plain application/octet-stream

Example: dataLocation=http://myServer.myDomain.com/spatialDat aSource A user-defined string that identifies the dataflow. Example: description=Seattle Stores Geocode One of the following values: xml csv tab pipe

input

For more information about input files for a Geocode Dataflow, see Geocode Dataflow Data Schema. Example: input=csv key Required. A Bing Maps Key to use for the geocode job. o Optional. The output format for the response. A Bing Maps Key obtained from the Bing Maps Account Center.

output

One of the following values: json [default] 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. 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:

// geocode. // and pipe. //

dataFilePath: The path to the file that contains the spatial data to

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

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. // queryStringBuilder.Append("input=").Append(Uri.EscapeUriString(dataFormat)); queryStringBuilder.Append("&"); queryStringBuilder.Append("key=").Append(Uri.EscapeUriString(key));

if (!String.IsNullOrEmpty(description)) { //

10

// 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()) { 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); }

11

//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; } } }

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 400 500 12 When the request is not successful, the response returns one of the following errors.

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.
Parameter Alias Description Values

jobID

Required. The ID of the job.

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

key

Required. The Bing Maps Key that you used to create the

A Bing Maps Key from the Bing Maps Account Center. Example: 13

Parameter

Alias

Description

Values

geocode job. output o Optional. The output format for the response.

key=abc123def456ghi789abc123def456ghi789 One of the following values: json [default] 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-bystep description of how to use the Geocode Dataflow. The walkthrough includes example URLs and HTTP responses.
class DownloadDetails { 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:

14

// //

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 // 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())

15

{ 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();

} else if (reader.Value.Equals("failed")) { statusDetails.failedlink = reader.ReadString(); } } } } }

16

} 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 400 500 503 When the request is not successful, the response returns one of the following HTTP status codes.

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 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 17

"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 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.

18

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()) { StreamWriter successfile = new StreamWriter("Success.txt"); using (StreamReader r = new StreamReader(receiveStream)) { string line; while ((line = r.ReadLine()) != null) { successfile.Write(line); } } successfile.Close();

19

} }

//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);

20

} } 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
copyright

XML
Copyright

Type

Description

string string

A copyright notice. A URL that references a brand image to support contractual branding requirements. The HTTP Status code for the request. A description of the HTTP status code. A status code that offers additional information 21

brandLogoUri

BrandLogoUri

statusCode

StatusCode

integer

statusDescription

StatusDescription

string

authenticationResultCode

AuthenticationResultCode

One of the following values:


ValidCredentials

JSON

XML

Type
InvalidCredentials CredentialsExpired NotAuthorized NoCredentials None

Description

about authentication success or failure.

traceId

TraceId

string

A unique identifier for the request. A collection of ResourceSet objects. A ResourceSet is a container of Resources returned by the request. For more information, see the ResourceSet section below. A collection of error descriptions. For example, ErrorDetails can identify parameter values that are not valid or are missing.

resourceSets

ResourceSets

collection

errorDetails

ErrorDetails

string[]

ResourceSet The ResourceSet container provides the following information.


JSON
estimatedTotal

XML
EstimatedTotal

Type

Description

long

An estimate of the total number of resources in 22

JSON

XML

Type

Description

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
id

XML
Id

Type

Description

string

A unique string that identifies the dataflow job. There are no requirements for the string format. A URL that is defined by its role and name attributes.
role:self:

links

Link

URL

Use to check the status of your job.


role:output

and

name:succeeded:

Use to download data that was processed successfully. and name:failed: Use to download data that was not processed successfully.
role:output description Description

string

A user-defined description of the dataflow job. If a description is not 23

JSON

XML

Type

Description

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. 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. The total number of entities that were uploaded. The number of entities that were processed. This number included entities that were processed successfully 24

completedDate

CompletedDate

DateTime

totalEntityCount

TotalEntityCount

integer

processedEntityCount

ProcessedEntityCount

integer

JSON

XML

Type

Description

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. Additional error information that is provided when the Status is set to Aborted.

errorMessage

ErrorMessage

string

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":[ {

"__type":"DataflowJob:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1", "id":"5bf10c37df944083b1879fbb0556e67e", "links":[ { "role":"self",

25

"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 } ] } ], "statusCode":200, "statusDescription":"OK", "traceId":"e8bfe25fdc4f4bc5824cda4e568e1c19" }

XML Example 26

<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> <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>

27

</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> <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">

28

<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

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">

29

<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> <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 30

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> <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>

31

<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

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">

32

<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> <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">

33

<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> </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" >

34

<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: // 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 {

35

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: // geocode. // and pipe. // key: The Bing Maps Key to use for this job. The same key is used to get job dataFormat: The format of the input data. Possible values are xml, csv, tab dataFilePath: The path to the file that contains the spatial data to

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();

//

36

// 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);

// // The HTTP method must be 'POST'. // request.Method = "POST"; request.ContentType = contentType;

37

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)) throw new Exception ("The 'Location' header is missing from the HTTP response when creating a goecode job.");

return dataflowJobLocation; } } }

38

//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 // always appear after the 'Link' fields in the HTTP response.

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

if (response.StatusCode != HttpStatusCode.OK)

39

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();

} else if (reader.Value.Equals("failed")) { statusDetails.failedlink = reader.ReadString(); }

40

} } } }

} 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)) { //Create a request to download successfully geocoded data. You must add the Bing Maps Key to the // request. UriBuilder successUriBuilder = new UriBuilder(statusDetails.suceededlink + @"?key=" + key); HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(successUriBuilder.Uri); download location URL provided in the response to the job status

41

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(); }

} }

//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

42

// request.

download location URL provided in the response to the job status

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(); }

} } }

43

// // 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];

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 {

44

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); } } } }

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

45

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 GeocodeEntity/GeocodeResponse/Address/@PostalCode GeocodeEntity/GeocodeResponse/Address/@PostalTown GeocodeEntity/GeocodeResponse/RooftopLocation/@Latitude GeocodeEntity/GeocodeResponse/RooftopLocation/@Longitude GeocodeEntity/GeocodeResponse/InterpolatedLocation/@Latitude GeocodeEntity/GeocodeResponse/InterpolatedLocation/@Longitude

46

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" /> </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" />

47

</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" />

<xs:complexType name="ReverseGeocodeRequest"> <xs:complexContent> <xs:extension base="BaseGeoRequest"> <xs:sequence> <xs:element ref="Location" />

48

</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> <xs:element name="GeocodeEntity" type="GeocodeEntity" />

<xs:complexType name="GeocodeFeed"> <xs:sequence> <xs:element ref="GeocodeEntity" maxOccurs="unbounded" /> </xs:sequence>

49

</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

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 50

Field

Operation

Values

Address.AddressLine

Geocode Request Geocode Response

A string specifying the street line 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 Geocode Response

A string specifying the 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 Geocode Response

A string specifying the country or 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. A string that contains a full formatted address Note: Do not use this field as a geocode request value. This field is used in the response.

Address.FormattedAddress

Geocode Response

Address.Locality

Geocode Request Geocode Response

A string specifying the populated place for the address. This commonly refers to a city, but may refer to a suburb or a neighborhood in certain countries. 51

Field

Operation

Values

Example: Seattle Address.PostalCode Geocode Request Geocode Response A string specifying the post code, postal code, or ZIP Code of an address. Example: 98178 Address.PostalTown ConfidenceFilter.MinimumConfidence Geocode Request Geocode Request A string specifying the postal city of an address. A string specifying the minimum confidence required for the result. The following are possible confidence values: Low Medium High

Example: High Location.Latitude Location.Longitude Reverse Geocode Request A set of double values 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 RooftopLocation.Longitude Geocode Response A pair of double values representing degrees of latitude and longitude that are associated with an address. A pair of double values representing degrees of latitude and longitude that are the result of interpolating between two points. A string specifying the confidence of the result. 52

InterpolatedLocation.Latitude InterpolatedLocation.Longitude

Geocode Response

Confidence

Geocode Response

Field

Operation

Values

The following are possible confidence values: DisplayName Geocode Response Low Medium High

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. 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 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

53

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> <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">

54

<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> </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">

55

<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" /> <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" />

56

</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> <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">

57

<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> <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" />

58

<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> <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">

59

<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 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||||||||||||||||||||||||||||

60

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 980524434|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 980524434|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

61

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 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->->->

62

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 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.

63

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 980524434",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,,,

64

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 980524434",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 AdminDivision1

A physical address of a location. A first-order, initial political subdivision of a [Sovereign], such as a state, a province, a department, a region, or a prefecture. A second-order political subdivision of a [CountryRegion], a division of an [AdminDivision1] or a [Dependent]. A third-order political subdivision of a [CountryRegion], a division of an 65

AdminDivision2

AdminDivision3

EntityType

Description

[AdminDivision2]. AdministrativeBuilding AdministrativeDivision AgriculturalStructure Airport A building that contains governmental offices or facilities. An administrative division of a [CountryRegion], undifferentiated as to administrative level. A [Structure] used for agricultural purposes. A place where aircraft regularly land and take off, with runways, navigational aids, and facilities for handling passengers and/or cargo. An improved surface suitable for landing airplanes. A facility that contains rides and other attractions, such as a theme park. A place where archeological remains, old structures, or cultural artifacts are located. A place where marine life is displayed to the public. A logical grouping of [Island]s. A [Railway] that carries automobiles. A low-lying area mostly or wholly surrounded by higher ground. A site of a land battle of historical importance. An area of water partially enclosed by an indentation of shoreline. A [Coast] with a surface of sand, pebbles, or small rocks. A post or station at an international boundary for regulating the movement of people and goods. A structure erected across an obstacle, such as a stream or road, that is used by vehicles and pedestrians. A category that identifies a kind of business. 66

AirportRunway AmusementPark AncientSite Aquarium Archipelago Autorail Basin Battlefield Bay Beach BorderPost

Bridge

BusinessCategory

EntityType

Description

BusinessCenter BusinessName BusinessStructure BusStation Camp Canal Cave CelestialFeature Cemetery Census1 Census2

A place where a number of businesses are located. A name that identifies a business. A [Structure] used for commercial purposes. A place where buses pick up and discharge passengers. A site occupied by tents, huts, or other shelters for temporary use. An artificially constructed watercourse. An underground passageway or chamber, or a cavity on the side of a cliff. A spherical body in space. A burial place or a burial ground. One of the set of the most detailed, lowest-level [CensusDistrict]s. One of the set of second-order [CensusDistrict]s composed by aggregating [Census1]s. A district defined by a national census bureau and used for statistical data collection. A body of water between two landmasses. A building for public Christian worship. A building that contains the administrative offices of a municipal government. A high, steep-to-perpendicular slope that overlooks a lower area or a water body. An area of homogenous climactic conditions, as defined by modified Koeppen classes. An area of land adjacent to a [WaterFeature]. A facility for community recreation and meetings. A very large landmass, surrounded by water 67

CensusDistrict Channel Church CityHall Cliff ClimateRegion Coast CommunityCenter Continent

EntityType

Description

and larger than an [Island], that forms one of the primary divisions of land on a [CelestialFeature]. ConventionCenter CountryRegion Courthouse Crater A large meeting hall for conventions and other meetings, and shows. A primary [PoliticalUnit]. A building in which courts of law are held. A generally circular, saucer-shaped, or bowlshaped depression caused by volcanic or meteorite explosive action. An area of land with strong local identity, but no political status. A large area of ocean where surface water flows in a certain constant general direction. A barrier constructed across a stream to impound water. An area where a [River] divides into many separate water channels as it enters a [Sea] or a [Lake]. 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. A large area with low rainfall and little or no vegetation. An area in political dispute that is not considered part of any [CountryRegion]. A land region where all surface water drains into one specific [WaterFeature]. A wave form, a ridge, or a star-shaped feature composed of sand. A place where the destructive force of a specific earthquake is centered. A region with a homogeneous ecosystem, flora, 68

CulturalRegion Current Dam Delta

Dependent

Desert DisputedArea DrainageBasin Dune EarthquakeEpicenter Ecoregion

EntityType

Description

and/or fauna. EducationalStructure ElevationZone Factory FerryRoute A place for providing instruction. An area where the surface elevation of all land is within a defined range. A building or set of buildings where goods are manufactured, processed, or fabricated. A route used by a boat, or by other floating conveyances regularly used to transport people and vehicles across a [WaterFeature]. A structure and associated facilities where a ferry boat docks and takes on passengers, automobiles, and/or cargo. A place for hatching fish eggs or raising fish. A large area of trees. An [AdministrativeDivision] that no longer exists. A [PoliticalUnit] that no longer exists. A [Sovereign] that no longer exists. A defensive structure or earthwork. An enclosure for displaying selected plant life. An invisible point, line, or area on the surface of a [CelestialFeature] that is used for geographic reference. A single thing that has spatial extent and location. One of the two points of intersection of the surface of a [CelestialFeature] and its axis of rotation. A [HotSpring] that intermittently shoots water into the air. A mass of ice, usually at high latitudes or high elevations, with sufficient thickness to flow away from the source area. 69

FerryTerminal

FishHatchery Forest FormerAdministrativeDivision FormerPoliticalUnit FormerSovereign Fort Garden GeodeticFeature

GeoEntity GeographicPole

Geyser Glacier

EntityType

Description

GolfCourse GovernmentStructure Heliport Hemisphere

A recreational field where golf is played. A [Structure] typically owned and operated by a governmental entity. A place where helicopters land and take off. A half of the surface of a [Celestial Feature], usually specified as northern, southern, eastern, or western. A place where students receive advanced or specialized education, such as a college or a university. A place of historical importance. A building in which the sick or injured, especially those confined to bed, are medically treated. A place where hot water emerges from the ground. A large area covered with frozen water. An area of land set aside for aboriginal, tribal, or native populations. A [Structure] used for industrial or extractive purposes. A place where tourists and citizens can obtain information. The line running between geographic poles designated as the point where a calendar day begins. An area of land composed of the member [PoliticalUnit]s of an official governmental organization composed of two or more [Sovereign]s. An area of land completely surrounded by water and smaller than a [Continent]. A narrow strip of land connecting two larger landmasses and bordered by water on two 70

HigherEducationFacility

HistoricalSite Hospital

HotSpring Ice IndigenousPeoplesReserve IndustrialStructure InformationCenter InternationalDateline

InternationalOrganization

Island Isthmus

EntityType

Description

sides. Junction Lake LandArea A place where two or more roads join. An inland water body, usually fresh water. A relatively small area of land exhibiting a common characteristic that distinguishes it from the surrounding land. A natural geographic feature on dry land. A [Structure] that is a well-known point of reference. An imaginary line of constant latitude that circles a [CelestialFeature], in which every point on the line is equidistant from a geographic pole. A place where books and other media are stored and loaned out to the public or others. A tall structure with a major navigation light. An area of land where most of the population speaks the same language or speaks languages in the same linguistic family. An imaginary line of constant longitude on a [CelestialFeature] that runs from one geographic pole to the other. A point on the surface of a [CelestialFeature] that is the origin for lines of magnetic force. A harbor facility for small boats. A place where goods are bought and sold. A [Structure] in which the sick or injured are medically treated. A place where urban rapid transit trains pick up and drop off passengers, often underground or elevated. A place used by an armed service for storing arms and supplies, for accommodating and training troops, and as a base from which 71

Landform LandmarkBuilding LatitudeLine

Library Lighthouse LinguisticRegion

LongitudeLine

MagneticPole Marina Market MedicalStructure MetroStation

MilitaryBase

EntityType

Description

operations can be initiated. Mine A place where mineral ores are extracted from the ground by excavating surface pits and subterranean passages. 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. A commemorative structure or statue. A building for public Islamic worship. An elevated landform that rises, often steeply, above surrounding land on most sides. A group of connected [Mountain]s. A building where objects of permanent interest in one or more of the arts and sciences are preserved and exhibited. A [Structure] used for nautical purposes. A [Structure] used for navigational purposes. A section of a [PopulatedPlace], usually homogenous and/or well-known, but often with indistinct boundaries. An area in a [Desert] that contains water and plant life. A wildlife or scenic observation point. A vast expanse of salt water, one of the major [Sea]s covering part of the earth. A building that contains offices. An area maintained as a place of scenic beauty, or for recreation. A parking lot reserved for mass transit commuters. A break in a [MountainRange] used for 72

Mission

Monument Mosque Mountain MountainRange Museum

NauticalStructure NavigationalStructure Neighborhood

Oasis ObservationPoint Ocean OfficeBuilding Park ParkAndRide Pass

EntityType

Description

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. An extensive area of comparatively level to gently undulating land, lacking surface irregularities. A [CelestialFeature] that orbits a star. A section of a planetary crust that is in motion relative to other tectonic plates. An elevated plain with steep slopes on one or more sides. A tract of land used for playing team sports and/or other athletic events. A point on the surface of a [CelestialFeature] that marks an important geographical or astronomical location. A building in which police are stationed or posted. An area of land with well-defined borders that is subject to a specific political administration. A concentrated area of human settlement, such as a city, a town, or a village. A district used by a postal service as an aid in postal distribution and having a unique identifying code. One of the set of lowest-level and most detailed set of [PostCode]s in a [Sovereign]. One of the set of second-order (one level up from the lowest level) [Postcode]s in a [Sovereign], composed by aggregating [Postcode1]s. One of the set of third-order [Postcode]s in a [Sovereign], composed by aggregating 73

Plain

Planet Plate Plateau PlayingField Pole

PoliceStation PoliticalUnit PopulatedPlace Postcode

Postcode1 Postcode2

Postcode3

EntityType

Description

[Postcode2]s. Postcode4 One of the set of fourth-order [Postcode]s in a [Sovereign], composed by aggregating [Postcode3]s. A public building in which mail is received, sorted, and distributed. A facility for generating electric power. A facility for confining persons convicted or accused of crimes. A small, usually pointed [Peninsula] that often marks the terminus of a landmass. A track where races are held. A permanent twin steel-rail track on which trains move. A place comprised of ticket offices, platforms, and other facilities for loading and unloading train passengers and freight. A [Structure] used for watching or participating in sports or other athletic activities. A partly submerged feature, usually of coral, that projects upward near the water's surface and can be a navigational hazard. A large area of land where a specific characteristic of the land or its people is relatively homogenous. An area of land where the population holds relatively homogenous religious practices. A structure where organized, public religious services are held. A [Structure] used for scientific purposes. A tract of public land set aside for restricted use or reserved for future use. A house, a hut, an apartment building, or another structure where people reside. 74

PostOffice PowerStation Prison Promontory RaceTrack Railway RailwayStation

RecreationalStructure Reef

Region

ReligiousRegion ReligiousStructure ResearchStructure Reserve ResidentialStructure

EntityType

Description

RestArea River Road RoadBlock RoadIntersection Ruin Satellite School ScientificResearchBase Sea SeaplaneLandingArea ShipWreck ShoppingCenter Shrine Site SkiArea Sovereign SpotElevation Spring

A designated area, usually along a major highway, where motorists can stop to relax. A stream of running water. An open way with an improved surface for efficient transportation of vehicles. A temporary installation set up to control or block traffic along a road. A junction where two or more roads meet or cross at the same grade. A destroyed or decayed structure that is no longer functional. A [CelestialFeature] that orbits a [Planet]. A place where people, usually children, receive a basic education. A scientific facility used as a base from which research is carried out or monitored. A large area of salt water. A place on a water body where floatplanes land and take off. A site of the remains of a wrecked vessel. A collection of linked retail establishments. A structure or place that memorializes a person or religious concept. A place most notable because of an event that occurred in that location. A place developed for recreational Alpine or Nordic skiing. An independent nation-state, the highest level of political authority in that location. A point on a [CelestialFeature]'s surface with a known elevation. A place where water emerges from the ground. 75

EntityType

Description

Stadium StatisticalDistrict Structure

A structure with an enclosure for athletic games with tiers of seats for spectators. An area of land defined as a district to be used for statistical collection or service provision. A building, a facility, or a group of buildings and/or facilities used for a certain common purpose. A line that forms the border between two [Plate]s. A [Landform] related to [Plate]s and their movement. An edifice dedicated to religious worship. A large area within which the same time standard is used. A [Structure] typically used by tourists. A path, a track, or a route used by pedestrians, animals, or off-road vehicles. A [Structure] used for transportation purposes. A subterranean passageway for transportation. A feature on the floor of a [WaterFeature]. An area of land with high population density and extensive urban development. A low area surrounded by higher ground on two or more sides. A [Mountain] formed by volcanic action and composed of volcanic rock. An upright structure that encloses, divides, or protects an area. A vertical or very steep section of a [River]. A geographic feature that has water on its surface. A cylindrical hole, pit, or tunnel drilled or dug down to a depth from which water, oil, or gas 76

TectonicBoundary TectonicFeature Temple TimeZone TouristStructure Trail TransportationStructure Tunnel UnderwaterFeature UrbanRegion Valley Volcano Wall Waterfall WaterFeature Well

EntityType

Description

can be pumped or brought to the surface. Wetland Zoo An area of high soil moisture, partially or intermittently covered with shallow water. A zoological garden or park where wild animals are kept for exhibition.

Data Source Management API


Use the Data Source Management API to create, delete and get information about data sources. A data source stores entity data for a specified user-defined entity type. 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 Developer 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. 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 Developer 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 delete a data source: Use the Delete a Data Source URL to delete a data source.

In this Section
Load Data Source Dataflow Get Data Source Information Delete a Data Source Describes how to create a data source and upload entity data. Describes how to get information about one or more data sources. Describes how to delete a data source.

77

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. You can also use this API to replace the entity data of an existing data source with new data.

If you are an enterprise customer, you can 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. 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. To update the entity data in a data source, you must replace the entire set of entity data.

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 Developer Account can have up to 25 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 Entity Data Describes how to create a data source and upload entity data by using a load data source job.

78

Get Status of a Load Data Source Job Load Data Source Dataflow Response Description Load Data Source Data Schema and Sample Input

Describes how to request status for a load data source job. Describes the responses returned when you create and get status for a load data source job. Describes how to define a data schema and 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.

Create a Load Data Source Job and Input Entity Data Use the following URL to create a data source for a specified entity type and upload entity data to that data source. If the data source already exists, the data you upload replaces all of the existing data in the data source. This URL creates a load data source dataflow job.

If you are an enterprise customer, you can 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. 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 and upload entity data. This URL creates a load data source job to create or update a data source and load the entity data that you provide in the request. If the data source already exists, the entity data you provide will replace all of the entity data that exists in the data source. A data schema must be provided with the entity data and must specify a unique property for an entity ID. Each entity must have longitude and latitude properties with valid values. 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. 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 Developer Account. 79

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 as Description Values

dataSourc eName

Required The name of the data source.

A user-defined string that contains a name for the data source. A data source name can have a maximum of 50 characters and must not contain any of the following characters: *?"<>:|\/ Example: dataSourceName=FourthCoffeeSample

dataLocati on

Optional. Specifies the location of the data that you want to load into the data source. The data must contain a data schema along with the data sets. The location must be hosted by the WindowsF Azure Blob

A Windows Azure Blob Service location that contains the data to process. The Blob Service uses the following URL formats: http://account-name.blob.core.windows.net/myDataFile https://account-name.blob.core.windows.net/myDataFile For more information, see Addressing Blob Service Requests. Before you make your request to start the dataflow job, make sure that the Blob Service URL is available publicly or shared with a signature key. If the URL is shared with a signature key, it must be encoded. For more information, see Managing Access to Containers and Blobs. The following content types are supported for data that is retrieved: application/xml text/xml text/plain application/octet-stream

If you are specifying an Azure blob that is accessed by using a signature key, you must encode the URL. Example: dataLocation=http://myAzureAccount.blob.core.windows.net/my 80

Parameter

Ali as

Description

Values

Service.

EntityData Example for an Azure blob with a signature key: dataLocation=http%3a%2f%2fmyAzureAccount.blob.core.windo ws.net%2fmyEntityData%3fse%3d2012-0827T22%253A46%253A57Z%26sr%3db%26si%3d readonly%26sig%3dabcdef10389481

You must set the data 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 , the URL retur ns

81

Parameter

Ali as

Description

Values

an error . input Required. The format of the data schema andinput data. One of the following values: xml csv tab 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 tion

Required The type of operation to perform with the data. o Optional. The output format for the response. Required. The Bing Maps Key to use to create or access the data source. If you are creating a new data source, this Bing Maps Key becomes the master key for the data

One of the following values: complete: Replaces all data in the data source with the new data.

Example: loadOperation=complete One of the following values: json [default] xml Example: output=xml A Bing Maps Key obtained from the Bing Maps Account Center. For information about how to get a Bing Maps Key, see Getting a Bing Maps Key. Example: key=abc123def456ghi789abc123def456ghi789

output

key

82

Parameter

Ali as

Description

Values

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 Map s Dev elop er Acc 83

Parameter

Ali as

Description

Values

ount . queryKey Optional. A Bing Maps Key that is used to query the data source. A Bing Maps Key obtained from the Bing Maps Account Center. For information about how to get a Bing Maps Key, see Getting a Bing Maps Key. All queries on the data source can use this key. You can also use the master key to query the data source. The master key is the Bing Maps Key that you used for the key parameter when you create the data source. If you do not specify a query key, then you can query the data source with any Bing Maps Key that is associated with the same Bing Maps Developer Account as 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 Map s Dev elop er Acc ount

It is best practice to use a Bing Maps Key that is different than the master key to query the data source because the master key is also used to update and delete the data source. When you use the master key for queries, you increase the chance for the master key to be compromised by an unauthorized user. Example: queryKey=312456def132ghi789abc6473def456ghi321

84

Parameter

Ali as

Description

Values

. 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 values, depending on the format of the input data. 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 Developer 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

85

<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 Microsofts 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

86

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 Microsofts 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 } ] } ],

87

"statusCode":201, "statusDescription":"Created", "traceId":"3fa754b674cc431d8a72d86a5aea27be" }

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=xml&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 400 403 500 503 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 data sources. When the request is not successful, the response returns one of the following errors.

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. 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 88

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 of the job.

When you request a dataflow job, 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 master key for the data source. o Optional. The output format for the response.

The Bing Maps Key that was specified as the master key for the data source. For more information, see Create a Load Data Source Job and Input Entity Data. One of the following values: json [default] xml Example: o=xml

output

Response This URL supports the following response formats. JSON: application/json 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. 89

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 Microsofts 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> <Link role="self">https://spatial.virtualearth.net/REST/v1/dataflows/LoadDataSource/f8293dc72ac 04942b7cb003c9608c547</Link> <Status>Pending</Status>

90

<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 Microsofts 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> <Link role="self">https://spatial.virtualearth.net/REST/v1/dataflows/LoadDataSource/f8293dc72ac 04942b7cb003c9608c547</Link>

91

<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 Microsofts express written permission.", "resourceSets":[ { "estimatedTotal":1, "resources":[ { "__type":"DataflowJob:http:\/\/schemas.microsoft.com\/search\/local\/ws\/r est\/v1", "id":"f8293dc72ac04942b7cb003c9608c547", "links":[ {

92

"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 Microsofts express written permission.", "resourceSets":[ { "estimatedTotal":1, "resources":[ { "__type":"DataflowJob:http:\/\/schemas.microsoft.com\/search\/local\/ws\/r est\/v1", "id":"f8293dc72ac04942b7cb003c9608c547", "links":[

93

{ "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. 200 400 401 500 94 When the request is not successful, the response returns one of the following HTTP status codes.

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
copyright

XML
Copyright

Type

Description

string string

A copyright notice. A URL that references a brand image to support contractual branding requirements. The HTTP Status code for the request. A description of the HTTP status code. A status code that offers additional information about authentication success or failure.

brandLogoUri

BrandLogoUri

statusCode

StatusCode

integer

statusDescription

StatusDescription

string

authenticationResultCode

AuthenticationResultCode

One of the following values:


ValidCredentials InvalidCredentials CredentialsExpired NotAuthorized NoCredentials None

traceId

TraceId

string

A unique identifier for the request. A collection of


ResourceSet

resourceSets

ResourceSets

collection

95

JSON

XML

Type

Description

objects. A is a container of Resources returned by the request. For more information, see the ResourceSet section below.
ResourceSet 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
estimatedTotal

XML
EstimatedTotal

Type

Description

long

An estimate of the total number of resources in the ResourceSet. A collection of one or more DataflowJob resources. Information about the DataflowJob resource is found in the DataflowJob 96

resources

Resources

collection

JSON

XML

Type

Description

section. DataflowJob The DataflowJob resource container provides the following information.
JSON
id

XML
Id

Type

Description

string

A unique string that identifies the dataflow job. There are no requirements for the string format. URLs that is defined by its role and name attributes.
role:self:

links

Link

URL

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. and Use to access the error log for the job. This URL appears in the response only when the job status is set to Aborted.
role:output name:failed: description Description

string

A user-defined description of the dataflow job. If a description is not 97

JSON

XML

Type

Description

specified when the workflow is created, this field is not included or the value is null.
status Status

One of the following values:


Pending:

The status of the dataflow job.

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. 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. The total number of entities that were uploaded. The number of entities that were processed. This number included entities that were 98

completedDate

CompletedDate

DateTime

totalEntityCount

TotalEntityCount

integer

processedEntityCount

ProcessedEntityCount

integer

JSON

XML

Type

Description

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. 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.

errorMessage

ErrorMessage

string

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":[ {

"__type":"DataflowJob:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1", "id":"5bf10c37df011183b1879fbb0556e67e", "links":[ {

99

"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
<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">

100

<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> </Response>

101

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. 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. 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" /> </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>

102

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 of the entity location. Required. The longitude of the entity location. The elevation of the entity location.

double

Edm.Double

Longitude

double

Edm.Double

Elevation

double

Edm.Double

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. 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.

103

XML Data Type

OData Type

Maximum Number of Properties for the Data Type Collection

string

Edm.String

50 The maximum string length is 256 characters.

long boolean double dateTime Property Name Requirements

Edm.Int64 Edm.Boolean Edm.Double Edm.DateTime

20 40 20 5

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 (__). 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
<?xml version="1.0" standalone="yes"?> <FourthCoffeeSample> <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" />

104

<xs:element name="PrimaryCity" type="xs:string" minOccurs="0" /> <xs:element name="Subdivision" 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" /> <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>

105

</xs:schema> <FourthCoffeeShops> <AddressLine>Lven</AddressLine> <PrimaryCity>Aalborg</PrimaryCity> <Subdivision>Nordjyllands Amt</Subdivision> <CountryRegion>Danmark</CountryRegion> <PostalCode>9200</PostalCode> <Phone>303-555-0188</Phone> <Manager>Alan Steiner</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> <Close>1800</Close> <CreatedDate>2010-11-11T01:19:36.4350494Z</CreatedDate> <LastUpdatedDate>2010-11-16T01:19:36.4350494Z</LastUpdatedDate> </FourthCoffeeShops> <FourthCoffeeShops> <AddressLine>Sgade</AddressLine> <PrimaryCity>Silkeborg</PrimaryCity> <Subdivision>rhus Amt</Subdivision> <CountryRegion>Danmark</CountryRegion> <PostalCode>8600</PostalCode> <Phone>425-555-0111</Phone> <Manager>Phil Spencer</Manager>

106

<StoreOpen>Y</StoreOpen> <StoreType>Coffee Shop</StoreType> <Name>Fourth Coffee Store #22066</Name> <DisplayName>Fourth Coffee Store #22066, Silkeborg, rhus Amt, Danmark</DisplayName> <EntityID>-22066</EntityID> <Longitude>9.54552166667</Longitude> <Latitude>56.16946722222</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> </FourthCoffeeSample>

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) 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

107

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

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 Developer 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 Developer 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 dataSourcName 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 Developer 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 Developer 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 Developer 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 Developer 108

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 Developer Account.
http://spatial.virtualearth.net/REST/v1/data/$metadata?key=anyAccountKey

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 Developer 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. Required The name of the data source that you want to search. Required The entity type to search for in the data source. Optional. Specifies the format of the response. The supported formats are Atom and JSON. A string that identifies the data source. The name is part of the URL structure that identifies the data source. Example: FourthCoffeeSample A string that specifies the entity type for the data source. Example: FourthCoffeeShops One of the following values: atom [default] json

dataSourceName

entityTypeName

formatQueryOption

Example: $format=json

109

Parameter

Description

Values

key

Required. A Bing Maps Key that belongs to the Bing Maps Developer Account that manages the data source(s).

One of the Bing Maps Keys that is belongs to the Bing Maps Developer Account that manages the data source(s). If you are requesting information about a single data source, you can also use the data source master key. 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 Developer 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 Developer Account. The following example shows how to request information about all data sources that belong to a Bing Maps Developer Account. The key parameter must be set to a Bing Maps Key that belongs to the Bing Maps Developer Account. URL with Atom Response
http://spatial.virtualearth.net/REST/v1/data?key=anyAccountKey

110

The following response provides two unique URLs that represent two data sources that belong to a Bing Maps Developer 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 Microsofts express written permission.</bsi:copyright> <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 Microsofts express written permission.", "DataSources":[ { "Name":"FourthCoffeeSample", "Updated":"Thu, 10 Apr 2008 13:30:00 GMT",

111

"EntitySets":[ "FourthCoffeeShops" ] }, { "Name":"Transit", "Updated":"Thu, 10 Apr 2008 13:30:00 GMT", "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 Developer 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 Microsofts 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>

112

</app:collection> </app:workspace> </app:service>

URL with JSON response


http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffe eSample?$format=json&key=anyAccountKey { "d":{ "Copyright":" 2011 Microsoft and its suppliers. This API and any results cannot b

e used or accessed without Microsofts 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 Developer 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">

113

<Key> <PropertyRef Name="EntityID" /> </Key> <Property Name="EntityID" Type="Edm.String" Nullable="false" MaxLength="256" Unicode="true" FixedLength="false" /> <Property Name="Latitude" Type="Edm.Double"/> <Property Name="Longitude" Type="Edm.Double"/> <Property Name="AddressLine" Type="Edm.String" Nullable="true" MaxLength="256" Unicode="true" FixedLength="false" /> <Property Name="PrimaryCity" Type="Edm.String" Nullable="true" MaxLength="256" Unicode="true" FixedLength="false" /> <Property Name="Subdivision" Type="Edm.String" Nullable="true" MaxLength="256" Unicode="true" FixedLength="false" /> <Property Name="PostalCode" Type="Edm.String" Nullable="true" MaxLength="256" Unicode="true" FixedLength="false" /> <Property Name="Phone" Type="Edm.String" Nullable="true" MaxLength="256" Unicode="true" FixedLength="false" /> <Property Name="SecondaryCity" Type="Edm.String" Nullable="true" MaxLength="256" Unicode="true" FixedLength="false" /> <Property Name="CountryRegion" Type="Edm.String" Nullable="true" MaxLength="256" Unicode="true" FixedLength="false" /> <Property Name="Name" Type="Edm.String" Nullable="true" MaxLength="256" Unicode="true" FixedLength="false" /> <Property Name="DisplayName" Type="Edm.String" Nullable="true" MaxLength="256" Unicode="true" FixedLength="false" /> <Property Name="Manager" Type="Edm.String" Nullable="true" MaxLength="256" Unicode="true" FixedLength="false" /> <Property Name="StoreOpen" Type="Edm.String" Nullable="true" MaxLength="256" Unicode="true" FixedLength="false" /> <Property Name="StoreType" Type="Edm.String" Nullable="true" MaxLength="256" 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" />

114

<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> <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 400 401 500 503 When the request is not successful, the response returns one of the following errors.

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.

There are limits on the number of data source jobs that you can request. For more information see Dataflow and Data Source Job Requirements.

115

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 Developer Account that manages the data source.
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 ID for the data source.

A string containing and ID that is part of the URL structure that identifies the data 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 of the data source that you want to search.

A string that identifies the data source. The name is part of the URL structure that identifies the data 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: FourthCoffeeSample

key

Required. The master key for the data source.

The Bing Maps Key that was specified as the master key when the data source was created. Example: key=abc123def456ghi789abc123def456ghi789

116

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 example shows how to delete a data source. The key parameter must be set to the data source master key.
http://spatial.virtualearth.net/REST/v1/data/12345f26d9e9412345f94961312345/FourthCoffeeS ample?key=masterKey

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 400 401 This error code can occur in any of the following conditions: 404 500 503 This error code can occur when the data source does not exist. 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. When the request is not successful, the response returns one of the following errors.

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 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 restaurants within 20 kilometers. Use Query by Area to search for all restaurants within 20 kilometers that are open on Sundays and that serve French food. 117

Use Query by Property to search for all restaurants that have more than 20 employees. Use Query by ID to search for the resaturant 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. Describes how to query a data source for entities that satisfy a set of property value conditions. Describes how to query a data source for one or more entities by specifying entity IDs. Describes the response returned for queries. Describes query options, such as the options to filter and order results.

Query by Property

Query by ID Query Response Description Query Options

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 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. The distance unit of miles is not supported.

118

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.
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 unique ID for the data source. Required The name of the data source that you want to search. Required The entity type to search for. Required The area you want to search. You can specify this area in two ways: A latitude and longitude representing a point and a

A string containing an ID that is part of the URL structure that identifies the data source. Example: 20181f26d9e94c81acdf9496133d4f23 A string that identifies the data source. Example: FourthCoffeeSample

dataSourceName

entityTypeName

The entity type of the data source. Example: FourthCoffeeShops To define an area using a point and distance in kilometers, use the following syntax: spatialFilter=nearby(latitude, longitude, distance) where latitude and longitude represent a point on the Earth and the distance represents the maximum distance to search from that point. You must specify the distance in kilometers. The distance unit of miles is not supported. 119

spatialFilter

Parameter

Description

Values

distance in kilometers to search from that point. A set of latitude and longitude pairs that create an area called a bounding box.

Example: spatialFilter=nearby(47.6,-122.3,50.0) To define an area using a bounding box, use the following syntax: spatialFilter=bbox(South Latitude, West Longitude, North Latitude, East Longitude) where the latitude and longitude values define an area on the earth. Example: spatialFilter=bbox(47.5,-122.4,47.7,122.2) A set of query options. Each query option is specified as a single URL parameter. The following example shows how to set both the $format and the $orderby query options in the URL.
&$format=json&$orderby=ZipCode

queryOption

Optional. Specifies query options, such as format and properties to display in the response. For more information about query options, see Query Options.

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 120

Parameter

Description

Values

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 JSON 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. A string that contains the name of the callback function. Example: jsonp=MyCallbackFunction

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. Required. The Bing Maps Key to use to access the data source. The Bing Maps Keys that you can use for a data source are specified when the data source is created. For example, there may be 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 121

queryKey

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. Atom (application/atom + xml) [default] JSON (application/json)

This URL supports the following response formats.

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>

122

<rights type="text"> 2011 Microsoft and its suppliers. This API and any results cannot be used or accessed without Microsofts 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> <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>

123

<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>

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 Microsofts 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 },

124

{ "__metadata":{

"uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fou rthCoffeeSample/FourthCoffeeShops('-7891')" }, "EntityID":"-7891", "Latitude":40.781604, "Longitude":-74.181775 }, { "__metadata":{

"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

125

<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 Microsofts express written permission.</rights> <updated>2011-01-11T02:03:34Z</updated> <entry>

<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>

126

<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> <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)&$select=EntityID,Latitude,Longitude&$top=3&format=json&key=queryKe y

{ "d":{ "__copyright":"\u00a9 2011 Microsoft and its suppliers. This API and any results

cannot be used or accessed without Microsofts express written permission.",

127

"results":[ { "__metadata":{

"uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fou rthCoffeeSample/FourthCoffeeShops('-8051')" }, "EntityID":"-8051", "Latitude":40.820685, "Longitude":-74.295683 }, { "__metadata":{

"uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fou rthCoffeeSample/FourthCoffeeShops('-8174')" }, "EntityID":"-8174", "Latitude":40.849513, "Longitude":-74.292831 }, { "__metadata":{

"uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fou rthCoffeeSample/FourthCoffeeShops('-8181')" }, "EntityID":"-8181", "Latitude":40.851404, "Longitude":-74.293720 } ] } }

128

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)&$select=DisplayName,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: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 Microsofts express written permission.</rights> <updated>2011-02-03T01:36:41Z</updated> <entry>

<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth CoffeeSample/FourthCoffeeShops('-8051')</id> <title type="text" /> <updated>2011-02-03T01:36:41Z</updated> <content type="application/xml"> <m:properties> <d:DisplayName>Fourth Coffee Store #8051, Roseland, NJ, United States</d:DisplayName> <d:Latitude m:type="Edm.Double">40.820685</d:Latitude> <d:Longitude m:type="Edm.Double">-74.295682</d:Longitude> </m:properties> </content> </entry> <entry>

129

<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth CoffeeSample/FourthCoffeeShops('-8174')</id> <title type="text" /> <updated>2011-02-03T01:36:41Z</updated> <content type="application/xml"> <m:properties> <d:DisplayName>Fourth Coffee Store #8174, Caldwell, NJ, United States</d:DisplayName> <d:Latitude m:type="Edm.Double">40.849513</d:Latitude> <d:Longitude m:type="Edm.Double">-74.292831</d:Longitude> </m:properties> </content> </entry> <entry>

<id>https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fourth CoffeeSample/FourthCoffeeShops('-8181')</id> <title type="text" /> <updated>2011-02-03T01:36:41Z</updated> <content type="application/xml"> <m:properties> <d:DisplayName>Fourth Coffee Store #8181, Caldwell, NJ, United States</d:DisplayName> <d:Latitude m:type="Edm.Double">40.851404</d:Latitude> <d:Longitude m:type="Edm.Double">-74.293720</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,-

130

74.3163299560546935,5)&$select=DisplayName,Latitude,Longitude&$top=3&format=json&key=quer yKey

{ "d":{ "__copyright":"\u00a9 2011 Microsoft and its suppliers. This API and any results cannot be used or accessed wi

thout Microsofts express written permission.", "results":[ { "__metadata":{ "uri":"https:\/\/spatial.virtualearth.net\/REST\/v1\/data\/20181f26d9e94c8 1acdf9496133d4f23\/FourthCoffeeSample\/FourthCoffeeShops('-8051')" }, "DisplayName":"Fourth Coffee Store #8051, Roseland, NJ, United States", "Latitude":40.820685, "Longitude":-74.295682 }, { "__metadata":{ "uri":"https:\/\/spatial.virtualearth.net\/REST\/v1\/data\/20181f26d9e94c8 1acdf9496133d4f23\/FourthCoffeeSample\/FourthCoffeeShops('-8174')" }, "DisplayName":"Fourth Coffee Store #8174, Caldwell, NJ, United States", "Latitude":40.849513, "Longitude":-74.292831 }, { "__metadata":{ "uri":"https:\/\/spatial.virtualearth.net\/REST\/v1\/data\/20181f26d9e94c8 1acdf9496133d4f23\/FourthCoffeeSample\/FourthCoffeeShops('-8181')" }, "DisplayName":"Fourth Coffee Store #8181, Caldwell, NJ, United States",

131

"Latitude":40.851404, "Longitude":-74.293720 } ] } }

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 400 401 500 503 When the request is not successful, the response returns one of the following errors.

See Also 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.
http://spatial.virtualearth.net/REST/v1/data/accessId/dataSourceName/entityTypeName?$filt er=filterString&queryOption1&queryOption2&queryOptionN&jsonp=jsonCallBackFunction&jsonso= jsonState&key=queryKey

132

Template Parameters

Parameter names and values are not case-sensitive except for the queryKey parameter value.
Parameter Description Values

accessId

Required. A unique ID for the data source.

A string containing and ID that is part of the URL structure that identifies the data 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. Required The entity type to search for. Required. The search condition based on property values. The entity type of the data source. Example: FourthCoffeeStores A conditional expression that uses property values. An entity is returned when the expression is true for that entitys values. This parameter is an OData query option. Currently, the Query API only supports logical operators. Example: $filter=CountryRegion Eq 'Washington' and Employees Ge 10

entityTypeName

filterString

queryOptions

Optional. Options for this query. For more information about query options, see Query Options.

A set of query values. Each query value is specified as an individual URL parameter. The following example shows how to set both the $format and the $orderby query options in the 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 133

Parameter

Description

Values

properties to filter results by using the $filter query option. jsonp Optional. Name of JSON 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. A string that contains the name of the callback function. Example: jsonp=MyCallbackFunction

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. Required. The Bing Maps Key to use to access the data source. The Bing Maps Keys that you can use for a data source are specified when the data source is created. For example, there may be 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

queryKey

134

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. 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/FourthCoffe eSample/FourthCoffeeShops?$filter=PrimaryCity Eq'Clearwater' And StoreType Eq 'Coffee Shop'&$select=IsWiFiHotSpot&$orderby=IsWiFiHotSpot desc&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 Microsofts 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" />

135

<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>

<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>

136

<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('-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/20181f26d9e94c81acdf9496133d4f23/FourthCoffe eSample/FourthCoffeeShops?$filter=PrimaryCity Eq'Clearwater' And StoreType Eq 'Coffee Shop'&$select=IsWiFiHotSpot&$orderby=IsWiFiHotSpot desc&$format=json&key=queryKey

{ "d":{ "__copyright":"\u00a9 2011 Microsoft and its suppliers. This API and any results

cannot be used or accessed without Microsofts express written permission.", "results":[ { "__metadata":{

137

"uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9 496133d4f23/FourthCoffeeSample/FourthCoffeeShops('-715')" }, "IsWiFiHotSpot":true }, { "__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 } ] }

138

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 400 401 500 503 When the request is not successful, the response returns one of the following errors.

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

139

(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 unique ID for the data source.

A string containing and ID that is part of the URL structure that identifies the data source. Example: 20181f26d9e94c81acdf9496133d4f23 A string that identifies the data source. Example: FourthCoffeeSample

dataSourceName

Required The name of the data source that you want to search. Required The entity type to search for. Required when searching for a single entity. The entity type name and the entity ID string. Required when searching for multiple entities. A commaseparated list

entityTypeName

A string that identifies the entity type of the data source. Example: FourthCoffeeShops The entity type of the data source and the entity ID string to search for in the data source defined by using the following format: EntityTypeName(EntityIdString) Example: FourthCoffeeShops('4232')

entityTypeName(entityTypeID)

$filter=entityId in (entityId1, entityId2, entityIdN

A list of entity ID strings to search for in the data source. You can specify up to 50 entity ID strings. Example: $filter=entityId in ('4024', '234', '8982')

140

Parameter

Description

Values

of entity ID strings to search for in the datasource. queryOptions Optional. Options for this query. For more information about query options, see Query Options. A set of query options. Each query option is specified as an individual URL parameter. The following example shows how to set both the $format and the $orderby query options in the URL.
&$format=json&$orderby=ZipCode

Example: $top=3 Example: $filter=ZipCode Eq '98052' 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. Name of JSON 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

A string that contains the name of the callback function. Example: jsonp=MyCallbackFunction

141

Parameter

Description

Values

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 value is provided as the second parameter to the callback function provided in the JSONP parameter. Required. The Bing Maps Key to use to access the data source. The Bing Maps Keys that you can use for a data source are specified when the data source is created. For example, there may be 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=20181f26d9e94c81acdf9496133d4f23

queryKey

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. 142

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. 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>Lven</d:AddressLine> <d:PrimaryCity>Aalborg</d:PrimaryCity>

143

<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> <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 Microsofts 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

144

{ "d":{ "__copyright":"\u00a9 2011 Microsoft and its suppliers. This API and any results

cannot be used or accessed without Microsofts express written permission.", "__metadata":{

"uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/Fou rthCoffeeSample/FourthCoffeeShops('-22067')" }, "EntityID":"-22067", "Latitude":57.003766, "Longitude":9.874434, "AddressLine":"Lven", "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)\/",

145

"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
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 Microsofts 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>Lven</d:AddressLine>

146

<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" /> <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":{

147

"__copyright":"\u00a9 2011 Microsoft and its suppliers. This API and any results cannot be used or accessed wi

thout Microsofts 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":"Lven", "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 148

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) specification. In addition to the OData query options, the Query API also provides custom query options, such as a spatial filter, that you can use to Query by Area.

OData Query Options


Query Option Description OData Specification

$filter

Specifies a conditional expression for a list of properties and values.

$filter

You cannot filter on the latitude and longitude entity properties. The Query API currently supports logical operators and precedence grouping. For a complete list of the supported operators, see the Supported $filter Operators section below. Example: $filter=City Eq 'Seattle' And OpenOnSunday Eq 'Y' $format Specifies the format of the HTTP response. The supported formats for the Query API are JSON and Atom. The default format is Atom. $format

149

Query Option

Description

OData Specification

Example: $format=json $inlinecount Specifies whether or not to return a count of the results in the response. Possible values for this query option include: allpages none [default] $inlinecount

Example: $inlinecount=allpages $orderby Specifies one or more properties to use 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. $orderby

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 150

Query Option

Description

OData Specification

$select

Specifies the data source properties to 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

$select

$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. 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 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

$top

Supported $filter Operators


Operator Description

Logical Operators Eq Ne Gt Equal Not equal Greater than 151

Operator

Description

Ge Lt Le And Or Not Grouping Operator ()

Greater than or equal Less than Less than or equal Logical and Logical or Logical negation

Precedence grouping

Spatial Filter Query Options You can query for entities in a given area by setting a spatial filter in your query. The Query API offers two spatial filters. Search in a set distance from a location
spatialFilter=nearby(latitude,longitude,distance)

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)

For more information about how to use the spatial filter query options, see Query by Area.

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 152

<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> </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 153

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 "LastUpdatedDate":"\/Date(634182103373200000)\/" }, { "__metadata":{ "uri":"https://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9 496133d4f23/FourthCoffeeSample/FourthCoffeeShops('-661')" }, "IsWiFiHotSpot":false "LastUpdatedDate":"\/Date(634181256403200000)\/" }, ] } }

Status Codes and Errors


Each response to a request provides an HTTP status code. This article describes these codes.

154

HTTP Status Codes


The following table lists the most common HTTP status codes. Additional information may be provided with a specific request.
HTTP Status Code Short Description Details

200 201 202 400 401

OK Created Accepted Bad Request Unauthorized

The request is successful. A new resource is created. The request has been accepted for processing. The request contained an error. Access was denied. You may have entered your credentials incorrectly, or you might not have access to the requested resource or operation. The request is for something forbidden. Authorization will not help. The requested resource was not found. Your request could not be completed because there was a problem with the service. There's a problem with the service right now. Please try again later.

403

Forbidden

404 500

Not Found Internal Server Error

503

Service Unavailable

155

You might also like