Upgrading From MapPoint Web Services to Bing Maps

57
Upgrading to Bing Maps From MapPoint Web Service

Transcript of Upgrading From MapPoint Web Services to Bing Maps

Page 1: Upgrading From MapPoint Web Services to Bing Maps

Upgrading to Bing Maps

From MapPoint Web Service

Page 2: Upgrading From MapPoint Web Services to Bing Maps

Table of Contents

Introduction....................................................................................................................................................................... 1

Purpose of this Guide .................................................................................................................................................................... 1

Why Bing Maps? .............................................................................................................................................................................. 2

Service Comparison ........................................................................................................................................................................ 2

Hosted Data in Bing Maps ........................................................................................................................................................... 3

Suggested Upgrade Plan ............................................................................................................................................................. 4

Next Steps .......................................................................................................................................................................................... 5

Authentication .................................................................................................................................................................. 6

MapPoint ............................................................................................................................................................................................ 6

Bing Maps .......................................................................................................................................................................................... 6

Mapping Examples ......................................................................................................................................................... 7

Maps ..................................................................................................................................................................................................... 7

Localization ..................................................................................................................................................................................... 10

Geocoding ....................................................................................................................................................................................... 12

Reverse Geocoding ...................................................................................................................................................................... 15

Adding a Pushpin ......................................................................................................................................................................... 16

Routing ............................................................................................................................................................................................. 18

MapPoint Web Service Method Upgrade Table .............................................................................................. 23

Development Cycle ..................................................................................................................................................... 24

MapPoint ......................................................................................................................................................................................... 24

Bing Maps ....................................................................................................................................................................................... 24

Code and Response Listings .................................................................................................................................... 27

Bing Maps JSON Classes ........................................................................................................................................................... 27

JSON Response: Bing Maps Geocoding .............................................................................................................................. 33

Page 3: Upgrading From MapPoint Web Services to Bing Maps

Code Listings for Other Languages ....................................................................................................................... 35

VB .NET ............................................................................................................................................................................................. 35

Java..................................................................................................................................................................................................... 39

PHP ..................................................................................................................................................................................................... 44

C# ....................................................................................................................................................................................................... 53

Page 4: Upgrading From MapPoint Web Services to Bing Maps

1

Introduction

As part of the MapPoint Web Service (MWS) end of service announcement, the Bing platform team has

created a program to provide you with a set of resources and tools to upgrade your MWS applications to

Bing Maps APIs before November 18, 2011. The core resources will be released over approximately 2

months and are segmented to support your planning and development phases. A summary of what you

can expect includes:

This Upgrade Guide, which provides a detailed comparison between MWS and Bing Maps, as well

as best practices for the upgrade process and your development processes.

A collection of toolkits and sample code to accelerate the upgrade process and to help your

developers quickly get up to speed on Bing Maps APIs.

Assistance connecting you with a Microsoft Bing Maps partner should you require hands-on

support during your upgrade.

As an MWS customer, the benefits of upgrading your application to Bing Maps are numerous. Over the

coming months, we invite you to leverage these committed resources and other opportunities we will

make available to make your upgrade efficient and straightforward. We are here to help.

Purpose of this Guide

The MapPoint Web Service to Bing Maps Upgrade Guide is the first guide released to support you in your

Bing Maps upgrade. This initial resource includes detailed comparisons between MWS and Bing Maps,

with a primary focus on the Bing Maps REST API, as well as comparative code samples and suggestions

for how to upgrade MWS applications to utilize the most current versions of Bing Maps APIs. As you read

this document you should gain an understanding of the benefits of Bing Maps APIs and how to leverage

Bing Maps to upgrade and improve your existing MWS applications.

To support a wide variety of scenarios, the code samples in this guide are provided in C#, VB.NET, Java,

and PHP.

IMPORTANT NOTE: Static vs. Dynamic Maps

As a MWS customer, your mapping applications exclusively use static maps – maps that are loaded into

an application or web page as images and require new images to be loaded any time the content or

context of a map changes. This guide assumes that you will choose to upgrade your MWS applications

using static maps to an equivalent application using static maps delivered via the Bing Maps REST

Imagery API.

However, Bing Maps also offers AJAX and Silverlight map controls that enable you to load dynamic maps

into applications using JavaScript or .NET. Dynamic maps can be manipulated onscreen by the user, as

Page 5: Upgrading From MapPoint Web Services to Bing Maps

2

well as programmatically from your code and provide significant functionality beyond the capabilities of

static maps. If you are interested in exploring the option of using dynamic maps within your new Bing

applications, please visit the MSDN Bing Maps AJAX control documentation for more information.

Why Bing Maps?

Bing Maps offers numerous advantages over MWS, including:

Enhanced geocoding and address parsing functionality for more accurate results.

Cleaner road map imagery and more complete road data.

High resolution imagery available in Aerial and Birdseye views.

Faster performance delivered through Bing cloud-based services.

A cleaner, more modern, programming model.

Service Comparison

Each MWS service has a high level equivalent in the Bing Maps REST Services.

MapPoint Web Service Bing Maps REST Services

Find Service Locations API

Render Service Imagery API

Route Service Routes API

Customer Data Service Spatial Data API

REST vs. SOAP

The primary difference between MWS and the Bing Maps REST API is that MWS is implemented as a

SOAP (Simple Object Access Protocol) API, whereas Bing Maps REST Services use REST (Representational

State Transfer) APIs and architecture.

In MWS, SOAP is used to pass XML representations of objects through the web, which can make for large

amounts of data being transferred depending on request complexity.

Conversely, REST services tend to be “lighter weight”, due to smaller amounts of data transferred and

faster responses. In general, REST is a much simpler development model than SOAP, as it makes use of

the built-in standards within HTTP for such things as authentication and content type negotiation. The

Bing Maps REST API is the recommended upgrade path for MWS customers looking for similar static map

based experiences and will be the focus of nearly all comparative examples and upgrade paths in this

guide.

Page 6: Upgrading From MapPoint Web Services to Bing Maps

3

REST vs. SOAP: Improved Performance

The Bing Maps REST API is capable of returning responses in JSON or XML format (MWS only supports

XML). The XML responses from REST tend to be smaller than equivalent SOAP XML responses because

SOAP services “wrap” responses with additional service-related information. The smaller size

characteristics of REST responses generally translate into faster response times between the client and

server.

Adding to the improved performance of the Bing Maps REST API is the fact that Bing services and content

are hosted in Microsoft’s CDN and Dynamic Compute centers. This enables end users to access services

and content from datacenters closest to their location for lower latency and faster responses while

simultaneously increasing the overall stability and scalability of all services.

REST vs. SOAP: A Simplified API

The architecture and workflows of the Bing Maps REST API are simpler than the equivalent MWS API

components which enable more efficient development and a simple upgrade project. Bing Maps REST API

responses in JSON format are easily consumed in a various languages and platforms, including .NET and

JavaScript, without the additional complexity found in processing MWS SOAP API responses. Another

simplification is the authentication mechanism used by the Bing Maps REST API. MWS uses digest

authentication to authenticate users, which is relatively easy to implement within the .NET framework and

IIS, but can require extra development effort in languages that do not natively support digest

authentication.

In the Bing Maps REST API, you only need to append a Bing Maps Key to your requests – there is no need

for any additional authentication, and getting a key is as easy as applying for one via the Bing Maps

Developer Center. See Getting a Bing Maps Key on MSDN for more details on how to create a Bing Maps

Developer Account and obtain a Bing Maps Key.

Hosted Data in Bing Maps

The MWS hosted data services will no longer be available once the transition from the MWS to Bing Maps

is complete. To replace the MapPoint hosted data functionality, the Bing Spatial Data API provides bulk

geocoding as well as custom data upload and querying.

NOTE: the custom data upload and querying features of the Bing Spatial Data API were released on

November 18, 2010 in BETA form with a locked API specification. MWS customers have been given

exclusive access to this BETA in order to facilitate planning, development and testing phases. Please visit

the MWS upgrade portal to download the API documentation. The estimated release timeframe for

version 1 of the data upload and querying APIs is early 2010.

More detailed information on how to leverage the Bing Spatial Data API for data upload and query will be

released in a forthcoming supplement to this guide.

Page 7: Upgrading From MapPoint Web Services to Bing Maps

4

Suggested Upgrade Plan

To assist you with planning, we have compiled this list of high-level steps to use as a baseline plan to

move your codebase and development practices to Bing Maps equivalents. While your ultimate upgrade

plan will depend on your specific situation, the following steps outline suggested components of any plan:

1. Create a Bing Maps account at the Bing Maps Account Center. You can find more information

about creating a Bing Maps account in the Development Cycle section of this Upgrade Guide.

2. Generate a Bing Maps key. When creating this key, set the “key type” to “developer” and set its

associated URL to http://localhost.

a. Enterprise customers should think of “Developer” keys as the replacement for MWS

“staging” access – the choice for your development, non-production needs.

3. Send an email including this new (or existing if you are already using Bing Maps) Bing Maps

Account Center Acct ID to your Bing sales professional to “activate” your account and to ensure

proper access privileges to Bing services and enterprise support options. If you do not have your

sales person’s email address, [email protected] can help you acquire this information.

4. Download your location data from the MapPoint Customer Service Site.

5. Reformat location data to match the required schema for the Bing Spatial Services API. See the

documentation for the BETA upload and query features on the MWS upgrade portal for

additional information.

6. Upload location data to the Bing Spatial Data Services either through the API or through the Bing

Maps portal.

7. Upgrade MWS calls for geocoding, routing, and render services to equivalent Bing Maps REST API

features using your Bing Maps key for authentication (see the corresponding sections of this

guide for each of these topics).

8. Upgrade MapPoint Customer Data Service queries to the Bing Spatial Data Services using your

Bing Maps key for authentication.

9. Test your upgraded application.

10. Generate an “Enterprise” (i.e. “MWS production”) Bing Maps key or update your existing

“Developer” key to “Enterprise” using the Bing Maps Account Center. If you are an Enterprise

customer, you can create a new Enterprise key after a Microsoft sales representative has activated

your account.

11. Replace references to your Bing Maps key registered for http://localhost with your new Enterprise

key.

12. Retest your upgraded application.

13. Deploy your application to your production environment.

Page 8: Upgrading From MapPoint Web Services to Bing Maps

5

Next Steps

The remaining sections of this Upgrade Guide provide sample code that introduces you to the basics of

how to upgrade the most commonly used MWS functionality using Bing Maps REST APIs. You will also

find discussions on the differences in the general development cycle and authentication between the two

platforms.

Over the coming weeks, we will release additional guide supplements that will significantly expand the

scope of resources available to include:

Additional code samples and discussions to address more advanced topics such as how to use

the Bing Maps Spatial API for custom data hosting and querying.

Upgrade tools to assist in facilitating baseline development functions.

All of this information will be posted to the MapPoint portal and we will send you email notifications as

new content becomes available.

Page 9: Upgrading From MapPoint Web Services to Bing Maps

6

Authentication

This section of the upgrade guide discusses the differences in authentication methods between MWS and

Bing Maps REST APIs. The main difference between these services is that MWS uses username and

password for authentication whereas the Bing Maps REST APIs use a Bing Maps key.

NOTE: The examples in this guide assume that you have a production Bing Maps account. If you do not

have enterprise access (with ability to create “Enterprise” keys), send an email including your Bing Maps

Account Center Acct ID to your Bing sales professional and ask them to “activate” your account; this will

ensure you have proper access privileges to Bing services and enterprise support options. If you do not

have your sales person’s email address, [email protected] can help you acquire this information.

MapPoint

Authenticating using the MWS SOAP API requires an explicit username and password. In order to access

MWS from within an application, you must first initialize references to any of the services you want to

access by providing a username and password, as shown in Listing 1.

FindServiceSoap findService = new FindServiceSoap(); findService.Credentials = new System.Net.NetworkCredential(mapPointUser, mapPointPassword); findService.PreAuthenticate = true; RouteServiceSoap routeService = new RouteServiceSoap(); routeService.Credentials = new System.Net.NetworkCredential(mapPointUser, mapPointPassword); routeService.PreAuthenticate = true; RenderServiceSoap renderService = new RenderServiceSoap(); renderService.Credentials = new System.Net.NetworkCredential(mapPointUser, mapPointPassword); renderService.PreAuthenticate = true;

Listing 1 Initializing references to MapPoint Web Service

Bing Maps

In the Bing Maps REST API, a Bing Maps key must be passed with each request, included as a parameter

to the URL. In the URL shown in Listing 2, replace BingMapsKey with your application’s key. Notice that

authentication in Bing Maps is simpler than MapPoint and that there are no usernames or passwords sent

with the requests.

http://dev.virtualearth.net/REST/v1/Locations/query?key=BingMapsKey

Listing 2 Using a Bing Maps key to access the Bing Maps REST Locations API

For more information on how to obtain a Bing Maps Key, see Getting a Bing Maps Key.

Page 10: Upgrading From MapPoint Web Services to Bing Maps

7

Mapping Examples

This section provides descriptions and examples of how to upgrade your applications that use MWS to

use the Bing Maps REST API. All of the major functionality in MWS has equivalent functionality in Bing

Maps, and indeed many features have been significantly improved or enhanced. However, before going

into great detail about any particular functionality, it is worth looking at some basic examples that

demonstrate Bing Maps equivalents for the most commonly used mapping functionality in MWS.

This section of the upgrade guide shows Bing Maps equivalents for the following MWS functions:

1. Maps

2. Geocoding (by address)

3. Reverse Geocoding

4. Adding a Pushpin

5. Displaying Routes

6. Getting Directions for a Route

All examples in this article use the Bing Maps REST API. To read a discussion of the differences between

the MWS SOAP API and the Bing Maps REST API, see the Service Comparison section of this Guide.

Maps

The most basic function of any mapping API is loading or generating a static map. The following examples

demonstrate how to generate a static map image for a given location (e.g., Seattle, WA).

Before: In MapPoint

In MWS, you must first geocode a location by constructing and passing a FindSpecification object to

the FindService.Find web method. You then extract the location from the returned FindResults

object and pass it into the RenderService.GetMap() method, which returns a static map image to

display. Listing 3 shows an example of how to obtain a static map using MWS.

FindSpecification findSpec = new FindSpecification(); findSpec.DataSourceName = "MapPoint.NA"; findSpec.InputPlace = "Seattle, WA"; FindResults foundResults = findService.Find(findSpec); ViewByHeightWidth[] myViewsview = new ViewByHeightWidth[1]; myViewsview[0] = foundResults.Results[0].FoundLocation.BestMapView.ByHeightWidth; RenderServiceSoap renderService = new RenderServiceSoap(); MapSpecification mapSpec = new MapSpecification(); mapSpec.DataSourceName = "MapPoint.NA";

Page 11: Upgrading From MapPoint Web Services to Bing Maps

8

mapSpec.Views = myViewsview; mapSpec.Options = new MapOptions(); mapSpec.Options.ReturnType = MapReturnType.ReturnUrl; MapImage[] mapImages = renderService.GetMap(mapSpec);

Listing 3 Obtaining a static map using MapPoint Web Service

This example code is also available in VB.NET, Java, and PHP.

The code in Listing 3 produces a map (located at MapImage[0].Url) that looks like Figure 1.

Figure 1 Static map of Seattle obtained using MapPoint Web Service

After: In Bing Maps

Using the Bing Maps REST API, you can retrieve a static map image with a single request to the Imagery

API. For example, the URL in Listing 4 will retrieve the map shown in Figure 2, which is centered on the

same location as the one in Figure 1 above.

http://dev.virtualearth.net/REST/v1/Imagery/Map/Road/Seattle,WA?mapVersion=v1&key=BingMapsKey

Listing 4 Sample Bing Maps REST URL for obtaining a static map

Page 12: Upgrading From MapPoint Web Services to Bing Maps

9

Figure 2 Static map of Seattle obtained from Bing Maps REST Imagery API

The image returned by this REST request can be processed in the same way as a MapPoint Web Service

MapImage class. For example, you may use the image request URL as the ImageUrl for a BitmapImage or

reference the URL in the src parameter in an HTML <img> element.

The mapVersion=v1 parameter shown in Listing 4 requests the map image version in Figure 2. These new

map images will become the default in the future.

Note that if you want to produce a map without a pushpin, you can specify the latitude, longitude, and

zoom level in your request instead of a named location, as shown in Listing 5.

http://dev.virtualearth.net/REST/v1/Imagery/Map/Road/47.619048,-122.35384/15?mapVersion=v1&key=BingMapsKey

Listing 5 Bing Maps REST URL to obtain a static map without a pushpin

Bing Maps has alternate map imagery sets such as Aerial or AerialWithLabels that be selected with the

imagerySet parameter. The example URL in Listing 6 displays a map using the imagery set

AerialWithLabels as seen in Figure 3.

http://dev.virtualearth.net/REST/v1/Imagery/Map/AerialWithLabels/47.60358,-122.329454/10?mapVersion=v1&key=BingMapsKey

Listing 6 Bing Maps REST URL to obtain an AerialWithLabels static map

Page 13: Upgrading From MapPoint Web Services to Bing Maps

10

Figure 3 Static map of Seattle obtained from Bing Maps REST Imagery API using AerialWithLabels

For more information on the full capabilities of the Bing Maps REST Imagery API, see

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

Note: Authentication

MapPoint: The MapPoint example code in this article assumes that references to the MapPoint SOAP web

services have been initialized as described in the Authentication section of this guide.

Bing Maps: Authentication in Bing Maps requires a Bing Maps key. For any of the Bing Maps REST

examples in this article, replace BingMapsKey in the URL with your Bing Maps key.

Localization

Localization of maps is the process of rendering maps in a specific language other than the default (US

English in both MWS and Bing Maps). Both MWS and the Bing Maps REST API support localization.

Before: In MapPoint

Localizing map images in MapPoint requires you to change the header of the SOAP request. In the

example shown in Listing 7, CultureInfo.Name is set to “fr” in order to return an image localized to

French. Once the culture is set, further requests against the service using the same service instance

continue to use that culture. Each MapPoint service instance must have its culture set individually.

Page 14: Upgrading From MapPoint Web Services to Bing Maps

11

FindSpecification findSpec = new FindSpecification(); findSpec.DataSourceName = "MapPoint.EU"; findSpec.InputPlace = "Paris, France"; FindResults foundResults = findService.Find(findSpec); ViewByHeightWidth[] myViewsview = new ViewByHeightWidth[1]; myViewsview[0] = foundResults.Results[0].FoundLocation.BestMapView.ByHeightWidth; MapSpecification mapSpec = new MapSpecification(); mapSpec.DataSourceName = "MapPoint.EU"; mapSpec.Views = myViewsview; mapSpec.Options = new MapOptions(); mapSpec.Options.ReturnType = MapReturnType.ReturnUrl; CultureInfo cultureInfo = new CultureInfo(); cultureInfo.Name = "fr"; UserInfoRenderHeader renderHeader = new UserInfoRenderHeader(); renderHeader.Culture = cultureInfo; renderService.UserInfoRenderHeaderValue = renderHeader; MapImage[] mapImages = renderService.GetMap(mapSpec);

Listing 7 Loading a localized map using MapPoint Web Service

This example code is also available in VB.NET, Java, and PHP.

Figure 4 Localized map of Paris generated by MapPoint Web Service

Page 15: Upgrading From MapPoint Web Services to Bing Maps

12

After: In Bing Maps

To easily localize a Bing Maps static map for a language or culture, add the culture parameter to the

request. The example in Listing 8 returns a map of Paris in French. The resulting map is shown in Figure 5.

http://dev.virtualearth.net/REST/v1/Imagery/Map/Road/Paris,France?mapVersion=v1&culture=fr-FR&key=BingMapsKey

Listing 8 Loading a localized map using the Bing Maps REST Imagery API

Figure 5 Localized map of Paris generated by Bing Maps REST Imagery API

For more information on localization, see the Bing Maps API documentation for culture parameters at

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

Geocoding

Geocoding is the process of determining a specific latitude and longitude for a street address or other

geographic feature. The following examples highlight the differences in geocoding syntax between MWS

and the Bing Maps REST API for a formatted address.

Before: In MapPoint

In MWS, the address to be geocoded can be provided either as a single string, as shown in Listing 9, or as

a structured set of parameters.

Page 16: Upgrading From MapPoint Web Services to Bing Maps

13

string textAddress = "1 Microsoft Way, Redmond, WA 98052"; FindAddressSpecification findSpec = new FindAddressSpecification(); findSpec.DataSourceName = "MapPoint.NA"; findSpec.InputAddress = findService.ParseAddress(textAddress, null); FindResults foundResults = findService.FindAddress(findSpec); double latitude = foundResults.Results[0].FoundLocation.LatLong.Latitude; double longitude = foundResults.Results[0].FoundLocation.LatLong.Longitude;

Listing 9 Geocoding by address using MapPoint Web Service

This example code is also available in VB.NET, Java, and PHP.

After: In Bing Maps

Geocoding with Bing Maps is performed using the Bing Maps Locations API which returns latitude,

longitude, and other information.

The request in Listing 10 shows how to geocode an address using a Bing Maps Locations API query.

http://dev.virtualearth.net/REST/v1/Locations/1 Microsoft Way, Redmond, WA 98052?key=BingMapsKey

Listing 10 Geocoding by address using the Bing Maps REST Locations API

The Locations API provides multiple URL templates for geocoding a location. In addition to the query

shown in Listing 10, there are structured and unstructured URL templates for geocoding an address. The

request in Listing 11 shows how to geocode an address using a structured URL. The format of the

structured URL varies by country.

http://dev.virtualearth.net/REST/v1/Locations/US/WA/98052/Redmond/1 Microsoft Way?o=xml&key=BingMapsKey

Listing 11 Geocoding by structured URL using the Bing Maps REST Locations API

The request in Listing 12 shows how to geocode the same address as an unstructured URL that specifies

the address with parameters.

http://dev.virtualearth.net/REST/v1/Locations?CountryRegion=US&adminDistrict=WA&postalCode=98052&locality=Redmond&addressLine=1 Microsoft Way&o=xml&key=BingMapsKey

Listing 12 Geocoding by unstructured URL using the Bing Maps REST Locations API

For more information on Locations URL templates, see the Locations API documentation.

MapPoint Data Sources vs. Bing Maps Regions

In MapPoint, a region-specific DataSourceName must be provided with every geocode request. However,

Bing Maps queries global locations, as in the example in Listing 10. It is not necessary to know what

region a search should be performed in for Bing Maps.

Page 17: Upgrading From MapPoint Web Services to Bing Maps

14

Bing Maps Response Processing

The code sample in Listing 13 demonstrates how to call the Locations API from C# and then process the

results, using the same address as in Listing 10. By default, the Bing Maps REST Locations API returns a

response in JSON format (alternatively, it can also return XML responses).

string textAddress = "1 Microsoft Way, Redmond, WA 98052"; string requestUrl = string.Format( "http://dev.virtualearth.net/REST/v1/Locations/" + "{0}?key={1}", textAddress, BingMapsKey); BingMapsRestV1.Response jsonResponse = GetResponse(requestUrl); double latitude = jsonResponse.ResourceSets[0].Resources[0].Point.Coordinates[0]; double longitude = jsonResponse.ResourceSets[0].Resources[0].Point.Coordinates[1]; // latitude = 47.639747, longitude = -122.129731

Listing 13 Using the Bing Maps REST Locations API from C#

The code for the GetResponse() method is shown in Listing 14.

private BingMapsRestV1.Response GetResponse(string requestUrl) { HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(BingMapsRestV1.Response)); object objResponse = jsonSerializer.ReadObject(response.GetResponseStream()); BingMapsRestV1.Response jsonResponse = objResponse as BingMapsRestV1.Response; return jsonResponse; } }

Listing 14 Code for the GetResponse() method, an example method for handling JSON responses

This example code is also available in VB.NET, Java, and PHP. For an example of processing XML rather

than JSON responses, see the XML processing code listing.

BingMapsRestV1.Response is an example class that was created for this article and is used for

deserializing the JSON response into objects. The JSON response contains common response information

and the search results. The full JSON response can be found in the section JSON Response: Bing Maps

Geocoding.

For more information on JSON deserialization, see http://msdn.microsoft.com/en-

us/library/bb412179.aspx.

Page 18: Upgrading From MapPoint Web Services to Bing Maps

15

Reverse Geocoding

Reverse geocoding allows you to search for an address or place by specifying latitude and longitude

coordinates.

Before: In MapPoint

In MapPoint, the GetLocationInfo() method returns Location information, as shown in Listing 15.

LatLong location = new LatLong(); location.Latitude = 47.639747; location.Longitude = -122.129731; Location[] results = findService.GetLocationInfo(location, "MapPoint.NA", null);

Listing 15 Using GetLocationInfo() to reverse geocode in MapPoint Web Service

This example code is also available in VB.NET, Java, and PHP.

The value of results[0].Address.FormattedAddress is "1 Microsoft Way, Redmond, WA 98052-6399",

the first reverse geocoded address found at the provided coordinates.

After: In Bing Maps

In Bing Maps, the Locations API contains information about points, addresses, places, or other locations

for reverse geocoding. The request in Listing 16 returns Location information for the given latitude and

longitude.

http://dev.virtualearth.net/REST/v1/Locations/47.639747,-122.129731?key=BingMapsKey

Listing 16 Using the Bing Maps REST Locations API to reverse geocode

The code in Listing 17 shows how to deserialize the reverse geocoded location from the JSON response.

string point = "47.639747,-122.129731"; // Latitude,Longitude string requestUrl = string.Format( "http://dev.virtualearth.net/REST/v1/Locations/{0}?key={1}", point, BingMapsKey); BingMapsRestV1.Response jsonResponse = GetResponse(requestUrl); BingMapsRestV1.Location location = jsonResponse.ResourceSets[0].Resources[0] as BingMapsRestV1.Location;

Listing 17 Deserializing a reverse geocoded location from a JSON response

This example code is also available in VB.NET, Java, and PHP.

The value of location.Address.FormattedAddress is "1 Microsoft Way, Redmond, WA 98052-6399".

Page 19: Upgrading From MapPoint Web Services to Bing Maps

16

Adding a Pushpin

Both MWS and the Bing Maps REST API allow you to generate a static map with one or more pushpins on

it. Pushpins are used to mark specific locations on a map.

Before: In MapPoint

In MapPoint, Pushpin objects are added to the Pushpins[] property of the MapSpecification object that is

passed as a parameter to the GetMap() request, as shown in Listing 18.

LatLong location = new LatLong(); location.Latitude = 47.620548; location.Longitude = -122.34874; Pushpin pushpin = new Pushpin(); pushpin.LatLong = location; pushpin.IconDataSource = "MapPoint.Icons"; pushpin.IconName = "0"; ViewByHeightWidth view = new ViewByHeightWidth(); view.Width = 350; view.Height = 350; view.CenterPoint = location; MapSpecification mapSpec = new MapSpecification(); mapSpec.DataSourceName = "MapPoint.NA"; mapSpec.Pushpins = new Pushpin[] { pushpin }; mapSpec.Views = new ViewByHeightWidth[1] { view }; mapSpec.Options = new MapOptions(); mapSpec.Options.ReturnType = MapReturnType.ReturnUrl; mapSpec.Options.Zoom = 0.001; MapImage[] mapImages = renderService.GetMap(mapSpec);

Listing 18 Loading a static map with a pushpin using MapPoint Web Service

This example code is also available in VB.NET, Java, and PHP.

Page 20: Upgrading From MapPoint Web Services to Bing Maps

17

Figure 6 A static map with a pushpin from MapPoint Web Service

After: In Bing Maps

In Bing Maps, pushpin coordinates are included as parameters in the request URL. The example in Listing

19 specifies a center point (latitude and longitude) for the map as well as a pushpin latitude and

longitude.

http://dev.virtualearth.net/REST/v1/Imagery/Map/Road/47.620548,-122.34874/16?mapVersion=v1&pushpin=47.620548,-122.34874&key=BingMapsKey

Listing 19 Loading a static map with a pushpin using the Bing Maps REST Imagery API.

The URL in Listing 19 returns the map image shown in Figure 7.

Figure 7 A static map with a pushpin from Bing Maps

Page 21: Upgrading From MapPoint Web Services to Bing Maps

18

The Bing Maps Imagery API also allows you to specify multiple pushpins, change the pushpin style, and

label pushpins. For more information on pushpin options in the Bing Maps REST API, see

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

Routing

Displaying Routes

Both MWS and the Bing Maps REST API allow you to generate static maps with customized routes drawn

on them. In both of the examples below, routes are calculated and drawn on a map by providing the

service with a series of waypoints (coordinates).

Before: In MapPoint

In MWS, plotting a route requires latitude and longitude coordinates for all the points on the route. For

example, in Listing 20 below, we first geocode the locations of Seattle and Redmond using the Find

service, and then pass them to the Route service as an array of LatLong objects. Note that Routing is

provided via the RouteService (which returns a Route object), and route images are returned by the

RenderService (by passing in the Route as a property of the MapSpecification).

const string dataSourceName = "MapPoint.NA"; FindSpecification findSpec = new FindSpecification(); findSpec.DataSourceName = dataSourceName;"MapPoint.NA"; findSpec.InputPlace = "Seattle, WA"; FindResults seattleResults = findService.Find(findSpec); findSpec.InputPlace = "Redmond, WA"; FindResults redmondResults = findService.Find(findSpec); LatLong[] latLongs = new LatLong[] { seattleResults.Results[0].FoundLocation.LatLong, redmondResults.Results[0].FoundLocation.LatLong }; Route myRoute = routeService.CalculateSimpleRoute(latLongs, dataSourceName,"MapPoint.NA", SegmentPreference.Quickest); ViewByHeightWidth[] myRouteViews = new ViewByHeightWidth[1]; myRouteViews[0] = myRoute.Itinerary.View.ByHeightWidth; MapSpecification mapSpec = new MapSpecification(); mapSpec.DataSourceName = dataSourceName;"MapPoint.NA"; mapSpec.Route = myRoute; mapSpec.Views = myRouteViews;

Page 22: Upgrading From MapPoint Web Services to Bing Maps

19

mapSpec.Options = new MapOptions(); mapSpec.Options.ReturnType = MapReturnType.ReturnUrl; MapImage[] myMapsmapImages = renderService.GetMap(mapSpec);

Listing 20 Displaying a route on a map using MapPoint Web Service

This example code is also available in VB.NET, Java, and PHP.

The code in Listing 20 produces a map image that looks like Figure 8.

Figure 8 Map with a route loaded using MapPoint Web Service

After: In Bing Maps

The Bing Maps REST API can plot map routes using multiple waypoints (e.g. start, end, and intermediate

stops). Waypoints are specified by the waypoint parameter (which can optionally be abbreviated in the

URL as wp). The Imagery API can return maps with routes highlighting the waypoint parameters in the

request. In the example URL in Listing 21, wp.0 and wp.1 are the waypoints comprising the route. Notice

that the waypoint locations are specified as strings in the request (Seattle WA and Redmond WA) rather

than coordinates. However, a waypoint location can also be specified as a Point (latitude, longitude), a

landmark, or an address. Note that in MWS the number of waypoints is limited to 50 while in Bing Maps the

limit is 25.

http://dev.virtualearth.net/REST/v1/Imagery/Map/Road/Routes?wp.0=Seattle WA&wp.1=Redmond WA&mapVersion=v1&key=BingMapsKey

Listing 21 URL to load a static map image with a route on it using the Bing Maps REST Imagery API

The URL in Listing 21 produces the map image shown in Figure 9.

Page 23: Upgrading From MapPoint Web Services to Bing Maps

20

Figure 9 A static image with a route, generated by

For more information on the routing options available in the Bing Maps Routes API, see

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

Getting Directions for a Route

In addition to providing map images that include routes, both MWS and the Bing Maps REST API return

additional information about calculated routes, such as distances, estimated driving time, and turn-by-

turn directions. In both cases, individual steps in a route are described in terms of geographical location,

instructions about how and when to turn, and other informational notes.

Before: In MapPoint

In MapPoint, route waypoints must be individually constructed as Waypoint objects and then passed as

part of the RouteSpecification. The Route object returned by RouteService.CalculateRoute()

includes an Itinerary property from which you can extract detailed route steps. The code in Listing 22 finds

a route between Seattle and Redmond and prints the route itinerary steps to the console.

const string dataSourceName = "MapPoint.NA"; FindSpecification findSpec = new FindSpecification(); findSpec.DataSourceName = dataSourceName; findSpec.InputPlace = "Seattle, WA"; FindResults startResult = findService.Find(findSpec); findSpec.InputPlace = "Redmond, WA"; FindResults endResult = findService.Find(findSpec);

Page 24: Upgrading From MapPoint Web Services to Bing Maps

21

SegmentSpecification[] routeSegmentsSpec = new SegmentSpecification[2]; routeSegmentsSpec[0] = new SegmentSpecification(); routeSegmentsSpec[0].Waypoint = new Waypoint(); routeSegmentsSpec[0].Waypoint.Name = startResult.Results[0].FoundLocation.Entity.Name; routeSegmentsSpec[0].Waypoint.Location = startResult.Results[0].FoundLocation; routeSegmentsSpec[1] = new SegmentSpecification(); routeSegmentsSpec[1].Waypoint = new Waypoint(); routeSegmentsSpec[1].Waypoint.Name = endResult.Results[0].FoundLocation.Entity.Name; routeSegmentsSpec[1].Waypoint.Location = endResult.Results[0].FoundLocation; RouteSpecification routeSpec = new RouteSpecification(); routeSpec.DataSourceName = dataSourceName; routeSpec.Segments = routeSegmentsSpec; Route myRoute; myRoute = routeService.CalculateRoute(routeSpec); for (int i = 0; i < myRoute.Itinerary.Segments[0].Directions.Length; i++) { Console.WriteLine(myRoute.Itinerary.Segments[0].Directions[i].Instruction); }

Listing 22 Extracting route directions using the MapPoint Web Service

This example code is also available in VB.NET, Java, and PHP.

After: In Bing Maps

The equivalent code to Listing 22 using the Bing Maps REST Routes API is more concise. Waypoints are

included as parameters in the request URL, as shown in Listing 23. By default, the mode of travel for the

route is assumed to be driving; walking instructions are also available by specifying the optional

travelMode parameter. For more information on REST API features including route optimization options,

see the Routes API documentation.

http://dev.virtualearth.net/REST/v1/Routes?wp.0=Seattle, WA&wp.1=Redmond,

WA&key=BingMapsKey

Listing 23 Retrieving route information using the Bing Maps REST Routes API

In Listing 24, the JSON response from Listing 23 is deserialized into a Route object, which contains the

individual legs and itinerary items.

string waypoint0 = "Seattle, WA"; string waypoint1 = "Redmond, WA"; string requestUrl = string.Format( "http://dev.virtualearth.net/REST/v1/Routes?wp.0={0}&wp.1={1}&key={2}", waypoint0, waypoint1, BingMapsKey);

Page 25: Upgrading From MapPoint Web Services to Bing Maps

22

BingMapsRestV1.Response response = GetResponse(requestUrl); BingMapsRestV1.Route route = response.ResourceSets[0].Resources[0] as BingMapsRestV1.Route; foreach (BingMapsRestV1.ItineraryItem itineraryItem in route.RouteLegs[0].ItineraryItems) { System.Console.WriteLine(string.Format("{0},{1} : {2}", itineraryItem.ManeuverPoint.Coordinates[0], // Latitude itineraryItem.ManeuverPoint.Coordinates[1], // Longitude itineraryItem.Instruction.Text)); }

Listing 24 Extracting route directions using the Bing Maps REST Routes API

This example code is also available in VB.NET, Java, and PHP.

For more information on the Bing Maps REST Routes API, see http://msdn.microsoft.com/en-

us/library/ff701705.aspx.

Page 26: Upgrading From MapPoint Web Services to Bing Maps

23

MapPoint Web Service Method Upgrade Table

The table below shows the equivalent Bing Maps REST API calls for all of the most used MWS methods.

You can click on any of the linked MapPoint methods to navigate to the section of this upgrade guide

that discusses that method and its Bing Maps equivalent. You can click on any of the Bing Maps methods

to be taken to the web-based MSDN documentation on that method.

MapPoint

Functionality

MapPoint Method Bing Maps Method or REST API Request

Find Service Find /Locations/query

Find Service FindAddress /Locations

Find Service FindById /data/accessID/dataSourceName 1

Find Service FindByProperty /data/accessID/dataSourceName/ entityTypeName/filter 1

Find Service FindNearby /data/accessID/dataSourceName/entityTypeName?spatialFilter=nearby 1

Find Service GetLocationInfo /Locations/point

Find Service ParseAddress /Locations/query

Render

Service

GetMap /Imagery/Map

Route Service CalculateRoute, CalculateSimpleRoute

/Routes

Customer

Data Service

StartBatchGeocode /Dataflows/Geocode 1

Customer

Data Service

StartDownload /Dataflows/Geocode 1

Customer

Data Service

GetJobState /Dataflows/Geocode/jobID 1

1. Available through the Bing Spatial Data Services.

Page 27: Upgrading From MapPoint Web Services to Bing Maps

24

Development Cycle

This section of the upgrade guide highlights the differences in the overall application development cycle

between MWS and Bing Maps REST APIs. The goal of this section is to demonstrate how you, as a

developer, will need to modify (and in most cases simplify) your application design practices during and

after upgrading to Bing Maps.

MapPoint Web Service

MWS staging and production environments are two functionally-identical, yet separate, service

environments.

The MapPoint Customer Data Service (CDS) was introduced with MWS version 3.5, and allows developers

to upload and download point of interest (POI) data programmatically. After uploading a POI data source

to MWS servers, developers can use the tools on the MapPoint Customer Services Site (CSS) to correct

and add entities to the data source.

Developers can test applications that make use of custom data sources using the MWS staging

environment. When the data source is ready, and initial testing is complete, developers can use the

Customer Service Site to submit the tested data to the MWS production environment. In order to move

into production, application code must be updated to reference the production version of

mappoint.wsdl.

The staging and production environments (and associated WSDL files) for MWS are available in two

different locations.

The staging environment URL is:

HTTP: http://staging.mappoint.net/standard-30/mappoint.wsdl

HTTPS: https://staging.mappoint.net/secure-30/mappoint.wsdl

The production environment URL is:

HTTP: http://service.mappoint.net/standard-30/mappoint.wsdl

HTTPS: https://service.mappoint.net/secure-30/mappoint.wsdl

Bing Maps

In Bing Maps, you no longer need to work with two different environments for staging and production

applications, nor do you need to access WSDL contracts when writing applications that make use of the

REST APIs.

Page 28: Upgrading From MapPoint Web Services to Bing Maps

25

The best approach for developing with Bing Maps is to generate two Bing Maps keys for any application

being developed: one for the development environment (a key of “Developer” type) and one for the

production environment (a key of “Enterprise” type). When moving between one environment and

another (e.g. “test” to “go-live”), all you need to change is the Bing Maps key itself or use the “update”

function to perform an inline change of key type. This method ensures that your applications will run with

identical behavior in both staging and production.

Prior to upgrading a MWS application or starting development on a new Bing Maps application, you

should generate a Bing Maps key using the Bing Maps Account Center

(http://www.bingmapsportal.com/). A Bing Maps key must be registered against a particular domain;

often, for development purposes, you will register your key against http://localhost using the

“Developer” key type.

When the mapping application is tested and ready to be deployed to a production environment, a

production Bing Maps key is required, which can also be obtained from the Bing Maps Account Center

using the “Enterprise” type. Alternatively, you can use the Update feature in the Bing Maps Account

Center to change your “Developer” key to “Enterprise” (see Figure 10 for example). The production key

must be registered against your production domain (for desktop and mobile applications

http://localhost can be still be used for production applications). Your application should be re-tested

to ensure that no issues arise from the key change and you can then complete your production

deployment.

By default, each Bing Maps account is limited to five (5) Bing Maps keys. However, additional keys can be

provided if required. Contact the Bing Maps Account Administrators at [email protected] if you

require additional keys.

Page 29: Upgrading From MapPoint Web Services to Bing Maps

26

Figure 10 Bing Maps Account Center – Update Keys Feature

Useful Links

Bing Maps Portal (account setup, reporting and key management)

http://www.bingmapsportal.com/

Getting a Bing Maps Key

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

Viewing Bing Maps Usage Reports

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

Page 30: Upgrading From MapPoint Web Services to Bing Maps

27

Code and Response Listings

This section contains extended sample code, code for helper classes referenced in this document, and full

listings of responses (JSON and XML) retrieved from the Bing Maps REST API.

Bing Maps JSON Classes

The listing below shows the sample JSON deserialization classes used in this guide with

DataContractJsonSerializer for extracting information from Bing Maps REST API responses.

using System.Runtime.Serialization; namespace BingMapsMigrationWsExamples.BingMapsRestV1 { [DataContract] public class Address { [DataMember(Name = "addressLine")] public string AddressLine { get; set; } [DataMember(Name = "adminDistrict")] public string AdminDistrict { get; set; } [DataMember(Name = "adminDistrict2")] public string AdminDistrict2 { get; set; } [DataMember(Name = "countryRegion")] public string CountryRegion { get; set; } [DataMember(Name = "formattedAddress")] public string FormattedAddress { get; set; } [DataMember(Name = "locality")] public string Locality { get; set; } [DataMember(Name = "postalCode")] public string PostalCode { get; set; } } public enum AuthenticationResultCode { None, NoCredentials, ValidCredentials, InvalidCredentials, CredentialsExpired, NotAuthorized,

Page 31: Upgrading From MapPoint Web Services to Bing Maps

28

} [DataContract] public class BoundingBox { [DataMember(Name = "southLatitude")] public double SouthLatitude { get; set; } [DataMember(Name = "westLongitude")] public double WestLongitude { get; set; } [DataMember(Name = "northLatitude")] public double NorthLatitude { get; set; } [DataMember(Name = "eastLongitude")] public double EastLongitude { get; set; } } public enum Confidence { High, Medium, Low, Unknown, } [DataContract] public class Hint { [DataMember(Name = "hintType")] public string HintType { get; set; } [DataMember(Name = "value")] public string Value { get; set; } } [DataContract] public class Instruction { [DataMember(Name = "maneuverType")] public string ManeuverType { get; set; } [DataMember(Name = "text")] public string Text { get; set; } //[DataMember(Name = "value")] //public string Value { get; set; } } [DataContract] public class ItineraryItem

Page 32: Upgrading From MapPoint Web Services to Bing Maps

29

{ [DataMember(Name = "travelMode")] public string TravelMode { get; set; } [DataMember(Name = "travelDistance")] public double TravelDistance { get; set; } [DataMember(Name = "travelDuration")] public long TravelDuration { get; set; } [DataMember(Name = "maneuverPoint")] public Point ManeuverPoint { get; set; } [DataMember(Name = "instruction")] public Instruction Instruction { get; set; } [DataMember(Name = "compassDirection")] public string CompassDirection { get; set; } [DataMember(Name = "hint")] public Hint[] Hint { get; set; } [DataMember(Name = "warning")] public Warning[] Warning { get; set; } } [DataContract] public class Line { [DataMember(Name = "point")] public Point[] Point { get; set; } } [DataContract] public class Link { [DataMember(Name = "role")] public string Role { get; set; } [DataMember(Name = "name")] public string Name { get; set; } [DataMember(Name = "value")] public string Value { get; set; } } [DataContract(Namespace = "http://schemas.microsoft.com/search/local/ws/rest/v1")] public class Location : Resource {

Page 33: Upgrading From MapPoint Web Services to Bing Maps

30

[DataMember(Name="entityType")] public string EntityType { get; set; } [DataMember(Name="address")] public Address Address { get; set; } [DataMember(Name = "confidence")] public string Confidence { get; set; } } [DataContract] public class Point : Shape { /// <summary> /// Latitude,Longitude /// </summary> [DataMember(Name = "coordinates")] public double[] Coordinates { get; set; } //[DataMember(Name = "latitude")] //public double Latitude { get; set; } //[DataMember(Name = "longitude")] //public double Longitude { get; set; } } [DataContract] [KnownType(typeof(Location))] [KnownType(typeof(Route))] public class Resource { [DataMember(Name = "name")] public string Name { get; set; } [DataMember(Name = "id")] public string Id { get; set; } [DataMember(Name = "link")] public Link[] Link { get; set; } [DataMember(Name = "point")] public Point Point { get; set; } [DataMember(Name = "boundingBox")] public BoundingBox BoundingBox { get; set; } } [DataContract] public class ResourceSet { [DataMember(Name="estimatedTotal")]

Page 34: Upgrading From MapPoint Web Services to Bing Maps

31

public long EstimatedTotal { get; set; } [DataMember(Name="resources")] public Resource[] Resources { get; set; } } [DataContract] public class Response { [DataMember(Name = "copyright")] public string Copyright { get; set; } [DataMember(Name = "brandLogoUri")] public string BrandLogoUri { get; set; } [DataMember(Name = "statusCode")] public int StatusCode { get; set; } [DataMember(Name = "statusDescription")] public string StatusDescription { get; set; } [DataMember(Name = "authenticationResultCode")] public string AuthenticationResultCode { get; set; } [DataMember(Name = "errorDetails")] public string[] errorDetails { get; set; } [DataMember(Name = "traceId")] public string TraceId { get; set; } [DataMember(Name = "resourceSets")] public ResourceSet[] ResourceSets { get; set; } } [DataContract(Namespace = "http://schemas.microsoft.com/search/local/ws/rest/v1")] public class Route : Resource { [DataMember(Name = "distanceUnit")] public string DistanceUnit { get; set; } [DataMember(Name = "durationUnit")] public string DurationUnit { get; set; } [DataMember(Name = "travelDistance")] public double TravelDistance { get; set; } [DataMember(Name = "travelDuration")] public long TravelDuration { get; set; } [DataMember(Name = "routeLegs")]

Page 35: Upgrading From MapPoint Web Services to Bing Maps

32

public RouteLeg[] RouteLegs { get; set; } [DataMember(Name = "routePath")] public RoutePath RoutePath { get; set; } } [DataContract] public class RouteLeg { [DataMember(Name = "travelDistance")] public double TravelDistance { get; set; } [DataMember(Name = "travelDuration")] public long TravelDuration { get; set; } [DataMember(Name = "actualStart")] public Point ActualStart { get; set; } [DataMember(Name = "actualEnd")] public Point ActualEnd { get; set; } [DataMember(Name = "startLocation")] public Location StartLocation { get; set; } [DataMember(Name = "endLocation")] public Location EndLocation { get; set; } [DataMember(Name = "itineraryItems")] public ItineraryItem[] ItineraryItems { get; set; } } [DataContract] public class RoutePath { [DataMember(Name = "line")] public Line Line { get; set; } } [DataContract] [KnownType(typeof(Point))] public class Shape { [DataMember(Name = "boundingBox")] public double[] BoundingBox { get; set; } } [DataContract] public class Warning { [DataMember(Name = "warningType")] public string WarningType { get; set; }

Page 36: Upgrading From MapPoint Web Services to Bing Maps

33

[DataMember(Name = "severity")] public string Severity { get; set; } [DataMember(Name = "value")] public string Value { get; set; } } }

Listing 25 JSON Deserialization classes for Bing Maps REST API responses

JSON Response: Bing Maps Geocoding

The URL in Listing 26 returns the JSON response in Listing 27. This JSON response has location

information for the requested address.

Request URL:

http://dev.virtualearth.net/REST/v1/Locations/1 Microsoft Way, Redmond, WA 98052?key=BingMapsKey

Listing 26 Bing Maps geocoding URL

Response:

{ "authenticationResultCode": "ValidCredentials", "brandLogoUri": "http:\/\/dev.virtualearth.net\/Branding\/logo_powered_by.png", "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.", "resourceSets": [ { "estimatedTotal": 1, "resources": [ { "__type": "Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1", "bbox": [ 47.635884282429323, -122.13737419709076, 47.643609717570676, -122.12208780290925 ], "name": "1 Microsoft Way, Redmond, WA 98052-8300", "point": { "type": "Point", "coordinates": [ 47.639747,

Page 37: Upgrading From MapPoint Web Services to Bing Maps

34

-122.129731 ] }, "address": { "addressLine": "1 Microsoft Way", "adminDistrict": "WA", "adminDistrict2": "King Co.", "countryRegion": "United States", "formattedAddress": "1 Microsoft Way, Redmond, WA 98052-8300", "locality": "Redmond", "postalCode": "98052-8300" }, "confidence": "High", "entityType": "Address" } ] } ], "statusCode": 200, "statusDescription": "OK", "traceId": "47cbacd7ff3d478690f7ec1fc58ec3e7|EWRM001666|02.00.147.700|EWRMSNVM001816, EWRMSNVM001703, EWRMSNVM001702" }

Listing 27 JSON Response from Bing Maps Geocoding request

Page 38: Upgrading From MapPoint Web Services to Bing Maps

35

Code Listings for Other Languages

This section contains equivalent code listings in VB.NET, Java, and PHP for all the C# listings throughout

this Guide.

VB .NET

MapPoint: Getting a Static Map

Dim findSpec As New FindSpecification() findSpec.DataSourceName = "MapPoint.NA" findSpec.InputPlace = "Seattle, WA" Dim foundResults As FindResults = findService.Find(findSpec) Dim myViews As ViewByHeightWidth() = New ViewByHeightWidth(0) {} myViews(0) = foundResults.Results(0).FoundLocation.BestMapView.ByHeightWidth Dim mapSpec As New MapSpecification() mapSpec.DataSourceName = "MapPoint.NA" mapSpec.Views = myViews Dim mapImages As MapImage() = renderService.GetMap(mapSpec)

Listing 28 MapPoint VB.NET Code for getting a static map using MapPoint Web Service

MapPoint: Getting a Localized Static Map

Dim findSpec As New FindSpecification() findSpec.DataSourceName = "MapPoint.EU" findSpec.InputPlace = "Paris, France" Dim foundResults As FindResults = findService.Find(findSpec) Dim view As ViewByHeightWidth() = New ViewByHeightWidth(0) {} view(0) = foundResults.Results(0).FoundLocation.BestMapView.ByHeightWidth Dim mapSpec As New MapSpecification() mapSpec.DataSourceName = "MapPoint.EU" mapSpec.Views = view mapSpec.Options = New MapOptions() mapSpec.Options.ReturnType = MapReturnType.ReturnUrl Dim cultureInfo As New CultureInfo() cultureInfo.Name = "fr" Dim renderHeader As New UserInfoRenderHeader() renderHeader.Culture = cultureInfo renderService.UserInfoRenderHeaderValue = renderHeader

Page 39: Upgrading From MapPoint Web Services to Bing Maps

36

Dim mapImages As MapImage() = renderService.GetMap(mapSpec)

Listing 29 MapPoint VB.NET code for getting a localized map image

Bing Maps: GetResponse()

Dim request As HttpWebRequest = TryCast(WebRequest.Create(requestUrl), HttpWebRequest) Using response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse) Dim jsonSerializer As New DataContractJsonSerializer(GetType(Response)) Dim objResponse As Object = jsonSerializer.ReadObject(response.GetResponseStream()) Dim jsonResponse As Response = TryCast(objResponse, Response) Return jsonResponse End Using

Listing 30 VB.NET code for the GetResponse() method, an example method for handling JSON responses

MapPoint: Geocoding

Dim textAddress As String = "1 Microsoft Way, Redmond, WA 98052" Dim findSpec As New FindAddressSpecification() findSpec.DataSourceName = "MapPoint.NA" findSpec.InputAddress = findService.ParseAddress(textAddress, Nothing) Dim foundResults As FindResults = findService.FindAddress(findSpec) Dim latitude As Double = foundResults.Results(0).FoundLocation.LatLong.Latitude Dim longitude As Double = foundResults.Results(0).FoundLocation.LatLong.Longitude

Listing 31 MapPoint VB.NET code for geocoding an address

Bing Maps: Geocoding

Dim textAddress As String = "1 Microsoft Way, Redmond, WA 98052" Dim requestUrl As String = String.Format("http://dev.virtualearth.net/REST/v1/Locations/{0}?key={1}", textAddress, BingMapsKey) Dim jsonResponse As Response = GetResponse(requestUrl) Dim latitude As Double = jsonResponse.ResourceSets(0).Resources(0).Point.Coordinates(0) Dim longitude As Double = jsonResponse.ResourceSets(0).Resources(0).Point.Coordinates(1)

Listing 32 Bing Maps VB.NET code for geocoding an address

MapPoint: Reverse Geocoding

Dim location As New LatLong() location.Latitude = 47.639747 location.Longitude = -122.129731 Dim results As Location() = findService.GetLocationInfo(location, "MapPoint.NA", Nothing)

Listing 33 MapPoint VB.NET code for reverse geocoding

Page 40: Upgrading From MapPoint Web Services to Bing Maps

37

Bing Maps: Reverse Geocoding

Dim point As String = "47.639747,-122.129731" ' Latitude,Longitude Dim requestUrl As String = String.Format("http://dev.virtualearth.net/REST/v1/Locations/{0}?key={1}", point, BingMapsKey) Dim jsonResponse As Response = GetResponse(requestUrl) Dim location As Location = TryCast(jsonResponse.ResourceSets(0).Resources(0), Location)

Listing 34 Bing Maps VB.NET code for reverse geocoding

MapPoint: Adding a Pushpin

Dim location As New LatLong() location.Latitude = 47.620548 location.Longitude = -122.34874 Dim pushpin As New Pushpin() pushpin.LatLong = location pushpin.IconDataSource = "MapPoint.Icons" pushpin.IconName = "0" Dim view As New ViewByHeightWidth() view.Width = 350 view.Height = 350 view.CenterPoint = location Dim mapSpec As New MapSpecification() mapSpec.DataSourceName = "MapPoint.NA" mapSpec.Pushpins = New Pushpin() {pushpin} mapSpec.Views = New ViewByHeightWidth(0) {view} mapSpec.Options = New MapOptions() mapSpec.Options.ReturnType = MapReturnType.ReturnUrl mapSpec.Options.Zoom = 0.001 Dim mapImages As MapImage() = renderService.GetMap(mapSpec)

Listing 35 MapPoint VB.NET code for adding a pushpin

MapPoint: Displaying Routes

Dim findSpec As New FindSpecification() findSpec.DataSourceName = "MapPoint.NA" findSpec.InputPlace = "Seattle, WA" Dim seattleResults As FindResults = findService.Find(findSpec) findSpec.InputPlace = "Redmond, WA" Dim redmondResults As FindResults = findService.Find(findSpec)

Page 41: Upgrading From MapPoint Web Services to Bing Maps

38

Dim latLongs As LatLong() = New LatLong() {seattleResults.Results(0).FoundLocation.LatLong, redmondResults.Results(0).FoundLocation.LatLong} Dim myRoute As Route = routeService.CalculateSimpleRoute(latLongs, "MapPoint.NA", SegmentPreference.Quickest) Dim myRouteViews As ViewByHeightWidth() = New ViewByHeightWidth(0) {} myRouteViews(0) = myRoute.Itinerary.View.ByHeightWidth Dim mapSpec As New MapSpecification() mapSpec.DataSourceName = "MapPoint.NA" mapSpec.Route = myRoute mapSpec.Views = myRouteViews mapSpec.Options = New MapOptions() mapSpec.Options.ReturnType = MapReturnType.ReturnUrl Dim mapImages As MapImage() = renderService.GetMap(mapSpec)

Listing 36 MapPoint VB.NET code for displaying a route

MapPoint: Getting Directions for a Route

Const dataSourceName As String = "MapPoint.NA" Dim findSpec As New FindSpecification() findSpec.DataSourceName = dataSourceName findSpec.InputPlace = "Seattle, WA" Dim startResult As FindResults = findService.Find(findSpec) findSpec.InputPlace = "Redmond, WA" Dim endResult As FindResults = findService.Find(findSpec) Dim routeSegmentsSpec As SegmentSpecification() = New SegmentSpecification(1) {} routeSegmentsSpec(0) = New SegmentSpecification() routeSegmentsSpec(0).Waypoint = New Waypoint() routeSegmentsSpec(0).Waypoint.Name = startResult.Results(0).FoundLocation.Entity.Name routeSegmentsSpec(0).Waypoint.Location = startResult.Results(0).FoundLocation routeSegmentsSpec(1) = New SegmentSpecification() routeSegmentsSpec(1).Waypoint = New Waypoint() routeSegmentsSpec(1).Waypoint.Name = endResult.Results(0).FoundLocation.Entity.Name routeSegmentsSpec(1).Waypoint.Location = endResult.Results(0).FoundLocation Dim routeSpec As New RouteSpecification() routeSpec.DataSourceName = dataSourceName routeSpec.Segments = routeSegmentsSpec Dim myRoute As Route myRoute = routeService.CalculateRoute(routeSpec)

Page 42: Upgrading From MapPoint Web Services to Bing Maps

39

For i As Integer = 0 To myRoute.Itinerary.Segments(0).Directions.Length - 1 Console.WriteLine(myRoute.Itinerary.Segments(0).Directions(i).Instruction) Next

Listing 37 MapPoint VB.NET code for getting directions for a route

Bing Maps: Getting Directions for a Route

Dim waypoint0 As String = "Seattle, WA" Dim waypoint1 As String = "Redmond, WA" Dim requestUrl As String = String.Format("http://dev.virtualearth.net/REST/v1/Routes?wp.0={0}&wp.1={1}&key={2}", waypoint0, waypoint1, BingMapsKey) Dim response As Response = GetResponse(requestUrl) Dim route As Route = TryCast(response.ResourceSets(0).Resources(0), Route) For Each itineraryItem As ItineraryItem In route.RouteLegs(0).ItineraryItems System.Console.WriteLine(String.Format("{0},{1} : {2}", itineraryItem.ManeuverPoint.Coordinates(0), itineraryItem.ManeuverPoint.Coordinates(1), itineraryItem.Instruction.Text)) Next

Listing 38 Bing Maps VB.NET code for getting directions for a route

Java

MapPoint: Getting a Static Map

FindSpecification findSpec = new FindSpecification(); findSpec.setDataSourceName("MapPoint.NA"); findSpec.setInputPlace("Seattle, WA"); FindResults foundResults = findService.find(findSpec); ViewByHeightWidth[] myViews = new ViewByHeightWidth[1]; myViews[0] = foundResults.getResults()[0].getFoundLocation() .getBestMapView().getByHeightWidth(); MapSpecification mapSpec = new MapSpecification(); mapSpec.setDataSourceName("MapPoint.NA"); mapSpec.setViews(myViews); mapSpec.setOptions(new MapOptions()); mapSpec.getOptions().setReturnType(MapReturnType.ReturnUrl); MapImage[] maps = renderService.getMap(mapSpec);

Listing 39 MapPoint Java code for getting a static map

Page 43: Upgrading From MapPoint Web Services to Bing Maps

40

MapPoint: Getting a Localized Static Map

CultureInfo cultureInfo = new CultureInfo(); cultureInfo.setName("fr"); UserInfoRenderHeader renderHeader = new UserInfoRenderHeader(); renderHeader.setCulture(cultureInfo); FindSpecification findSpec = new FindSpecification(); findSpec.setDataSourceName("MapPoint.EU"); findSpec.setInputPlace("Paris, France"); FindResults foundResults = findService.find(findSpec); ViewByHeightWidth[] myViews = new ViewByHeightWidth[1]; myViews[0] = foundResults.getResults()[0].getFoundLocation() .getBestMapView().getByHeightWidth(); MapSpecification mapSpec = new MapSpecification(); mapSpec.setDataSourceName("MapPoint.EU"); mapSpec.setViews(myViews); mapSpec.setOptions(new MapOptions()); mapSpec.getOptions().setReturnType(MapReturnType.ReturnUrl); MapImage[] maps = renderService.getMap(mapSpec);

Listing 40 MapPoint Java code for getting a localized static map

Bing Maps: GetResponse()

private JSONObject getResponse(URI requestURI) throws MalformedURLException, IOException, JSONException, URISyntaxException { URLConnection connection = requestURI.toURL().openConnection(); String line; StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); while ((line = reader.readLine()) != null) { builder.append(line); } return new JSONObject(builder.toString()); }

Listing 41 Java code for the GetResponse() method, an example method for handling JSON responses

MapPoint: Geocoding

String textAddress = "1 Microsoft Way, Redmond, WA 98052"; FindAddressSpecification findSpec = new FindAddressSpecification(); findSpec.setDataSourceName("MapPoint.NA"); findSpec.setInputAddress(findService.parseAddress(textAddress, null)); FindResults foundResults = findService.findAddress(findSpec);

Page 44: Upgrading From MapPoint Web Services to Bing Maps

41

LatLong coords = foundResults.getResults()[0].getFoundLocation() .getLatLong(); double latitude = coords.getLatitude(); double longitude = coords.getLongitude();

Listing 42 MapPoint Java code to geocode an address

Bing Maps: Geocoding

String textAddress = "1 Microsoft Way, Redmond, WA 98052"; URI requestURI = new URI("http", null, "dev.virtualearth.net", 80, "/REST/v1/Locations/" + textAddress, "key=" + BING_MAPS_KEY, null); JSONObject jsonResponse = getResponse(requestURI); JSONArray coords = jsonResponse.getJSONArray("resourceSets") .getJSONObject(0).getJSONArray("resources").getJSONObject(0) .getJSONObject("point").getJSONArray("coordinates"); double latitude = coords.getDouble(0); double longitude = coords.getDouble(1);

Listing 43 Bing Maps Java code for geocoding an address

MapPoint: Reverse Geocoding

LatLong location = new LatLong(); location.setLatitude(47.639747); location.setLongitude(-122.129731); Location[] results = findService.getLocationInfo(location, "MapPoint.NA", null);

Listing 44 MapPoint Java code for reverse geocoding

Bing Maps: Reverse Geocoding

String point = "47.639747,-122.129731"; // Latitude,Longitude URI requestURI = new URI("http", null, "dev.virtualearth.net", 80, "/REST/v1/Locations/" + point, "key=" + BING_MAPS_KEY, null); JSONObject jsonResponse = getResponse(requestURI); String formattedAddress = jsonResponse.getJSONArray("resourceSets") .getJSONObject(0).getJSONArray("resources").getJSONObject(0) .getJSONObject("address").getString("formattedAddress"); System.out.println(formattedAddress);

Listing 45 Bing Maps Java code for reverse geocoding

MapPoint: Adding a Pushpin

LatLong location = new LatLong(); location.setLatitude(47.620548); location.setLongitude(-122.34874); Pushpin pushpin = new Pushpin(); pushpin.setLatLong(location); pushpin.setIconDataSource("MapPoint.Icons");

Page 45: Upgrading From MapPoint Web Services to Bing Maps

42

pushpin.setIconName("0"); ViewByHeightWidth view = new ViewByHeightWidth(); view.setWidth(350d); view.setHeight(350d); view.setCenterPoint(location); MapSpecification mapSpec = new MapSpecification(); mapSpec.setDataSourceName("MapPoint.NA"); mapSpec.setPushpins(new Pushpin[] { pushpin }); mapSpec.setViews(new ViewByHeightWidth[] { view }); mapSpec.setOptions(new MapOptions()); mapSpec.getOptions().setReturnType(MapReturnType.ReturnUrl); mapSpec.getOptions().setZoom(0.001); MapImage[] mapImages = renderService.getMap(mapSpec);

Listing 46 MapPoint Java code for adding a pushpin

MapPoint: Displaying Routes

String dataSourceName = "MapPoint.NA"; FindSpecification findSpec = new FindSpecification(); findSpec.setDataSourceName(dataSourceName); findSpec.setInputPlace("Seattle, WA"); FindResults seattleResults = findService.find(findSpec); findSpec.setInputPlace("Redmond, WA"); FindResults redmondResults = findService.find(findSpec); LatLong[] latLongs = new LatLong[] { seattleResults.getResults()[0].getFoundLocation().getLatLong(), redmondResults.getResults()[0].getFoundLocation().getLatLong() }; Route myRoute = routeService.calculateSimpleRoute(latLongs, dataSourceName, SegmentPreference.Quickest); ViewByHeightWidth[] myRouteViews = new ViewByHeightWidth[1]; myRouteViews[0] = myRoute.getItinerary().getView().getByHeightWidth(); MapSpecification mapSpec = new MapSpecification(); mapSpec.setDataSourceName(dataSourceName); mapSpec.setRoute(myRoute); mapSpec.setViews(myRouteViews); mapSpec.setOptions(new MapOptions()); mapSpec.getOptions().setReturnType(MapReturnType.ReturnUrl); MapImage[] myMaps = renderService.getMap(mapSpec);

Listing 47 MapPoint Java code for displaying a route

Page 46: Upgrading From MapPoint Web Services to Bing Maps

43

MapPoint: Getting Directions for a Route

String dataSourceName = "MapPoint.NA"; FindSpecification findSpec = new FindSpecification(); findSpec.setDataSourceName(dataSourceName); findSpec.setInputPlace("Seattle, WA"); FindResults startResult = findService.find(findSpec); findSpec.setInputPlace("Redmond, WA"); FindResults endResult = findService.find(findSpec); SegmentSpecification[] routeSegmentsSpec = new SegmentSpecification[2]; routeSegmentsSpec[0] = new SegmentSpecification(); routeSegmentsSpec[0].setWaypoint(new Waypoint()); routeSegmentsSpec[0].getWaypoint().setName( startResult.getResults()[0].getFoundLocation().getEntity() .getName()); routeSegmentsSpec[0].getWaypoint().setLocation( startResult.getResults()[0].getFoundLocation()); routeSegmentsSpec[1] = new SegmentSpecification(); routeSegmentsSpec[1].setWaypoint(new Waypoint()); routeSegmentsSpec[1].getWaypoint().setName( endResult.getResults()[0].getFoundLocation().getEntity() .getName()); routeSegmentsSpec[1].getWaypoint().setLocation( endResult.getResults()[0].getFoundLocation()); RouteSpecification routeSpec = new RouteSpecification(); routeSpec.setDataSourceName(dataSourceName); routeSpec.setSegments(routeSegmentsSpec); Route myRoute; myRoute = routeService.calculateRoute(routeSpec); for (int i = 0; i < myRoute.getItinerary().getSegments()[0] .getDirections().length; i++) { System.out.println(myRoute.getItinerary().getSegments()[0] .getDirections()[i].getInstruction()); }

Listing 48 MapPoint Java code for getting directions for a route

Bing Maps: Getting Directions for a Route

String waypoint0 = "Seattle, WA"; String waypoint1 = "Redmond, WA"; URI requestURI = new URI("http", null, "dev.virtualearth.net", 80, "/REST/v1/Routes", "wp.0=" + waypoint0 + "&wp.1=" + waypoint1 + "&key=" + BING_MAPS_KEY, null); JSONObject jsonResponse = getResponse(requestURI);

Page 47: Upgrading From MapPoint Web Services to Bing Maps

44

JSONArray itineraryItems = jsonResponse.getJSONArray("resourceSets") .getJSONObject(0).getJSONArray("resources").getJSONObject(0) .getJSONArray("routeLegs").getJSONObject(0) .getJSONArray("itineraryItems"); for (int index = 0; index < itineraryItems.length(); ++index) { JSONObject itineraryItem = itineraryItems.getJSONObject(index); JSONArray coords = itineraryItem.getJSONObject("maneuverPoint") .getJSONArray("coordinates"); String instruction = itineraryItem.getJSONObject("instruction") .getString("text"); System.out.println("" + coords.getString(0) + "," + coords.getString(1) + " : " + instruction); }

Listing 49 Bing Maps Java code for getting directions for a route

PHP

Bing Maps Initialization

The following Bing Maps PHP example code assumes that you have defined your BingMapsKey as $key.

$key='Replace With Your Bing Maps Key';

MapPoint PHP SOAP Client Initialization

The following MapPoint PHP example code assumes that the code in 0 has already been declared and

initSoapClient() was executed.

// Initialize SOAP client instance function initSoapClient() { global $client; //MapPoint Web Service user name goes here. $mapPointUserName = ""; //MapPoint Web Service password goes here. $mapPointPassword = ""; //The MapPoint Web Service staging environment $mapPointWsdl = "http://staging.mappoint.net/standard-30/mappoint.wsdl"; $client = new nusoap_client($mapPointWsdl, true); $err = $client->getError(); if ($err) { die('An error occurred while the WSDL was being accessed: '.$err); } $client->setCredentials($mapPointUserName,$mapPointPassword,'digest'); }

Page 48: Upgrading From MapPoint Web Services to Bing Maps

45

// Check for SOAP error function checkSoapClientErrors($client, $res = null) { // Check for a fault if ($client->fault) { throwError('Fault occured while trying to route against MapPoint:\n'.print_r($res,true),$client); return 0; } // Check for errors $err = $client->getError(); if ($err) { throwError('Fault occured while trying to route against MapPoint:\n'.$err,$client); return 0; } } // Handle error function throwError($errMess,$client=null) { if ($client) { $errMess.="<h2>Request</h2>\n".htmlspecialchars($client->request, ENT_QUOTES); $errMess.="<h2>Response</h2>\n".htmlspecialchars($client->response, ENT_QUOTES); $errMess.="<h2>Debug</h2>\n".htmlspecialchars($client->debug_str, ENT_QUOTES); } error_log($errMess); die("<pre>".$errMess."</pre>"); }

Listing 50 MapPoint PHP SOAP client initialization

MapPoint: Getting a Static Map

global $client; $address = array( 'PrimaryCity' => "Seattle", //SecondaryCity is not required for U.S. addresses. 'Subdivision' => "WA", 'CountryRegion' => 'USA' ); $findAddressSpecification = array( 'DataSourceName' => 'MapPoint.NA',

Page 49: Upgrading From MapPoint Web Services to Bing Maps

46

'InputAddress' => $address, ); $findAddress = array('specification' => $findAddressSpecification); //Call the FindAddress method. $findResult=$client->call('FindAddress', array('parameters' => $findAddress)); checkSoapClientErrors($client, $findResult); $viewByHeightWidth = $findResult['FindAddressResult']['Results']['FindResult']['FoundLocation']['BestMapView']['ByHeightWidth']; $myViews[] = new soapval('MapView', 'ViewByHeightWidth', $viewByHeightWidth, false, 'http://s.mappoint.net/mappoint-30/'); $mapSpecification = array( 'DataSourceName' => 'MapPoint.NA', 'Views' => array('MapView' => $myViews), 'Options' => array('ReturnType' => 'ReturnUrl') ); $getMap = array('specification' => $mapSpecification); //Call the GetMap method. $renderResult=$client->call('GetMap', array('parameters' => $getMap)); checkSoapClientErrors($client, $renderResult); //Display image $imgUrl=$renderResult['GetMapResult']['MapImage']['Url']; echo('<img src="'.$imgUrl.'"/>');

Listing 51 MapPoint: Getting a Static Map

MapPoint: Getting a Localized Static Map

global $client; $address = array( 'PrimaryCity' => "Paris", 'CountryRegion' => 'France' ); $findAddressSpecification = array( 'DataSourceName' => 'MapPoint.EU', 'InputAddress' => $address, ); $findAddress = array('specification' => $findAddressSpecification); //Call the FindAddress method. $findResult=$client->call('FindAddress', array('parameters' => $findAddress)); checkSoapClientErrors($client, $findResult); $viewByHeightWidth = $findResult['FindAddressResult']['Results']['FindResult']['FoundLocation']['BestMapView']['ByHeightWidth'];

Page 50: Upgrading From MapPoint Web Services to Bing Maps

47

$myViews[] = new soapval('MapView', 'ViewByHeightWidth', $viewByHeightWidth, false, 'http://s.mappoint.net/mappoint-30/'); $mapSpecification = array( 'DataSourceName' => 'MapPoint.EU', 'Views' => array('MapView' => $myViews), 'Options' => array('ReturnType' => 'ReturnUrl') ); $getMap = array('specification' => $mapSpecification); //Call the GetMap method. $renderResult=$client->call('GetMap', array('parameters' => $getMap)); checkSoapClientErrors($client, $renderResult); //Display image $imgUrl=$renderResult['GetMapResult']['MapImage']['Url']; echo('<img src="'.$imgUrl.'"/>');

Listing 52 MapPoint: Getting a Localized Static Map

MapPoint: Geocoding

global $client; $address = array( 'PrimaryCity' => "Seattle", //SecondaryCity is not required for U.S. addresses. 'Subdivision' => "WA", 'CountryRegion' => 'USA' ); $findAddressSpecification = array( 'DataSourceName' => 'MapPoint.NA', 'InputAddress' => $address, ); $findAddress = array('specification' => $findAddressSpecification); //Call the FindAddress method. $findResult=$client->call('FindAddress', array('parameters' => $findAddress)); checkSoapClientErrors($client, $findResult); $lat=$findResult['FindAddressResult']['Results']['FindResult']['FoundLocation']['LatLong']['Latitude']; $lon=$findResult['FindAddressResult']['Results']['FindResult']['FoundLocation']['LatLong']['Longitude']; echo("The latitude/longitude for the address is: $lat/$lon");

Listing 53 MapPoint: Geocoding

Page 51: Upgrading From MapPoint Web Services to Bing Maps

48

Bing Maps: Geocoding

global $key; // URL of Bing Maps REST Services Locations API $locationURL = "http://dev.virtualearth.net/REST/v1/Locations"; $address = str_ireplace(" ","%20","1 Microsoft Way, Redmond, WA 98052"); // Compose URI for Locations API request $findURL = $locationURL."/".$address."?output=xml&key=".$key; // get the response from the Locations API and store it in a string $output = file_get_contents($findURL); // create an XML element based on the XML string $response = new SimpleXMLElement($output); // Extract data (e.g. latitude and longitude) from the results // latitude = 47.639747, longitude = -122.129731 $latitude = $response->ResourceSets->ResourceSet->Resources->Location->Point->Latitude; $longitude = $response->ResourceSets->ResourceSet->Resources->Location->Point->Longitude; // Setup the parameters for the Imagery API request (using a center point) $imageryBaseURL = "http://dev.virtualearth.net/REST/v1/Imagery/Map"; $imagerySet = "Road"; $centerPoint = $latitude.",".$longitude; $zoomLevel = "15"; echo "<img src='".$imageryURL = $imageryBaseURL."/".$imagerySet."/".$centerPoint."/".$zoomLevel."?key=".$key."'/>\n";

Listing 54 Bing Maps: Geocoding

MapPoint: Reverse Geocoding

global $client; $lat = 47.639747; $long = -122.129731; $latLong = array( 'Latitude' => $lat, 'Longitude' => $long ); $getLocationInfo = array('location' => $latLong, 'dataSourceName' => 'MapPoint.NA'); //Call the FindAddress method.

Page 52: Upgrading From MapPoint Web Services to Bing Maps

49

$findResult=$client->call('GetLocationInfo', array('parameters' => $getLocationInfo)); checkSoapClientErrors($client, $findResult); $address=$findResult['GetLocationInfoResult']['Location'][0]['Address']['FormattedAddress']; echo("First matched result for ($lat,$long): $address");

Listing 55 MapPoint: Reverse Geocoding

Bing Maps: Reverse Geocoding

global $key; $point = "47.639747,-122.129731"; // Latitude,Longitude $locationURL = "http://dev.virtualearth.net/REST/v1/Locations"; // Compose URI for Locations API request $findURL = $locationURL."/".$point."?output=xml&key=".$key; // get the response from the Locations API and store it in a string $output = file_get_contents($findURL); // create an XML element based on the XML string $response = new SimpleXMLElement($output); echo "Found address: ".$response->ResourceSets->ResourceSet->Resources->Location->Address->FormattedAddress;

Listing 56 Bing Maps: Reverse Geocoding

MapPoint: Adding a Pushpin

global $client; $lat = 47.620548; $long = -122.34874; $viewByHeightWidth = array( 'Height' => 350, 'Width' => 350, 'CenterPoint' => array( 'Latitude' => $lat, 'Longitude' => $long ) ); $myViews[] = new soapval('MapView', 'ViewByHeightWidth', $viewByHeightWidth, false, 'http://s.mappoint.net/mappoint-30/'); $pushpin = array( 'LatLong' => array( 'Latitude' => $lat,

Page 53: Upgrading From MapPoint Web Services to Bing Maps

50

'Longitude' => $long ), 'IconDataSource' => 'MapPoint.Icons', 'IconName' => '0' ); $mapSpecification = array( 'DataSourceName' => 'MapPoint.NA', 'Views' => array('MapView' => $myViews), 'Pushpins' => array( $pushpin ), 'Options' => array('ReturnType' => 'ReturnUrl', 'Zoom' => 0.001) ); $getMap = array('specification' => $mapSpecification); //Call the GetMap method. $renderResult=$client->call('GetMap', array('parameters' => $getMap)); checkSoapClientErrors($client, $renderResult); //Display image $imgUrl=$renderResult['GetMapResult']['MapImage']['Url']; echo('<img src="'.$imgUrl.'"/>');

Listing 57 MapPoing: Adding a Pushpin

MapPoint: Displaying Routes

global $client; $dataSourceName = 'MapPoint.NA'; // FindSpecification $findSpecification = array( 'DataSourceName' => $dataSourceName, 'InputPlace' => 'Seattle, WA' ); $findParams = array('specification' => $findSpecification); $findResults1 = $client->call('Find', array('parameters' => $findParams)); checkSoapClientErrors($client); $location1 = $findResults1['FindResult']['Results']['FindResult']['FoundLocation']; $findSpecification['InputPlace'] = 'Redmond, WA'; $findResults2 = $client->call('Find', array('parameters' => $findParams)); checkSoapClientErrors($client); $location2 = $findResults2['FindResult']['Results']['FindResult']['FoundLocation']; // RouteSpecification $routeSpec = array( 'DataSourceName' => $dataSourceName );

Page 54: Upgrading From MapPoint Web Services to Bing Maps

51

$routeParams = array( 'latLongs' => array( 'LatLong' => array( $location1['LatLong'], $location2['LatLong'] ) ), 'dataSourceName' => $dataSourceName, 'preference' => 'Quickest' // SegmentPreference ); $routeResults = $client->call('CalculateSimpleRoute', array('parameters' => $routeParams)); checkSoapClientErrors($client); // ViewByHeightWidth $view = null; $view = array( 'CenterPoint' => $location1['LatLong'], 'Width' => 320, 'Height' => 300 ); $myViews[] = new soapval('MapView', 'ViewByHeightWidth', $view, false, 'http://s.mappoint.net/mappoint-30/'); // MapOptions $mapOptions = array( 'ReturnType' => 'ReturnUrl' ); // MapSpecification $mapSpec = array( 'DataSourceName' => $dataSourceName, 'Route' => $routeResults['CalculateSimpleRouteResult'], 'Options' => $mapOptions, 'Views' => array('MapView' => $myViews) ); $mapParams = array('specification' => $mapSpec); $mapResults = $client->call('GetMap', array('parameters' => $mapParams)); checkSoapClientErrors($client); echo("Map image:<br>"); echo('<img src="' . $mapResults['GetMapResult']['MapImage']['Url'] . '"/>');

Listing 58 MapPoint: Displaying Routes

MapPoint: Getting Directions for a Route

global $client; $dataSourceName = 'MapPoint.NA';

Page 55: Upgrading From MapPoint Web Services to Bing Maps

52

// FindSpecification $findSpecification = array( 'DataSourceName' => $dataSourceName, 'InputPlace' => 'Seattle, WA' ); $findParams = array('specification' => $findSpecification); $findResults1 = $client->call('Find', array('parameters' => $findParams)); checkSoapClientErrors($client); $location1 = $findResults1['FindResult']['Results']['FindResult']['FoundLocation']; // FindSpecification $findSpecification['InputPlace'] = 'Redmond, WA'; $findResults2 = $client->call('Find', array('parameters' => $findParams)); checkSoapClientErrors($client); $location2 = $findResults2['FindResult']['Results']['FindResult']['FoundLocation']; $segments = array(); // Waypoint $segments[0]=array('Waypoint'=>array('Location'=>array('LatLong'=>$location1['LatLong']))); $segments[1]=array('Waypoint'=>array('Location'=>array('LatLong'=>$location2['LatLong']))); // RouteSpecification $routeSpec = array( 'DataSourceName' => $dataSourceName, 'Segments' => array('SegmentSpecification' => $segments) ); $routeResults = $client->call('CalculateRoute', array('parameters' => array('specification' => $routeSpec))); checkSoapClientErrors($client); $segments = $routeResults['CalculateRouteResult']['Itinerary']['Segments']['Segment']; echo("Directions:<br>"); for($index = 0;$index < count($segments); $index++) { if (count($segments[$index]['Directions'])==1) { $direction = $segments[$index]['Directions']['Direction']; echo("" . $direction['LatLong']['Latitude'] . "," . $direction['LatLong']['Longitude']); echo(" : "); echo("" . $direction['Instruction']); echo("<br>"); } }

Listing 59 MapPoint: Getting Directions for a Route

Page 56: Upgrading From MapPoint Web Services to Bing Maps

53

Bing Maps: Getting Directions for a Route

global $key; $waypoint0 = "Seattle WA"; $waypoint1 = "Redmond WA"; $imagerySet = "Road"; $routeBaseURL = "http://dev.virtualearth.net/REST/v1/Routes"; // Compose URI for Route API request $waypoint0 = str_ireplace(" ","%20",$waypoint0); $waypoint1 = str_ireplace(" ","%20",$waypoint1); $routeURL = $routeBaseURL."?waypoint.0=".$waypoint0."&waypoint.1=".$waypoint1."&output=xml&key=".$key; // get the response from the Route API and store it in a string $output = file_get_contents($routeURL); // create an XML element based on the XML string $response = new SimpleXMLElement($output); $route = $response->ResourceSets->ResourceSet->Resources->Route; $unit = ($route->DistanceUnit == "Kilometer") ? "km" : "mi"; echo "<table>\n"; echo "<tr>\n<td>Start</td><td>".$route->RouteLeg->StartLocation->Name."</td>\n</tr>\n"; $i = 1; foreach ($route->RouteLeg->ItineraryItem as $item) { echo "<tr>\n"; echo "<td>".$i."</td><td>".$item->Instruction."</td><td>".(float)($item->TravelDistance).$unit."</td>"; echo "</tr>\n"; $i++; } echo "</table>\n";

Listing 60 Bing Maps: Getting Directions for a Route

C#

Bing Maps: Geocoding with XML Responses

string textAddress = "1 Microsoft Way, Redmond, WA 98052"; string requestUrl = string.Format( "http://dev.virtualearth.net/REST/v1/Locations/" + "{0}?o=xml&key={1}", textAddress, BingMapsKey); XmlDocument xmlResponse = GetXmlResponse(requestUrl);

Page 57: Upgrading From MapPoint Web Services to Bing Maps

54

// Process response XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlResponse.NameTable); nsmgr.AddNamespace("b", "http://schemas.microsoft.com/search/local/ws/rest/v1"); XmlNode firstLocation = xmlResponse.SelectSingleNode("//b:Response/b:ResourceSets/b:ResourceSet/b:Resources/b:Location", nsmgr); double latitude = double.Parse(firstLocation.SelectSingleNode("b:Point/b:Latitude", nsmgr).FirstChild.Value); double longitude = double.Parse(firstLocation.SelectSingleNode("b:Point/b:Longitude", nsmgr).FirstChild.Value);

Listing 61 Bing Maps geocoding with XML response

Bing Maps: GetXmlResponse()

/// <summary> /// Send the request to the Bing Maps REST API and deserialize the XML response. /// </summary> private XmlDocument GetXmlResponse(string requestUrl) { HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(response.GetResponseStream()); return xmlDoc; } }

Listing 62 Bing Maps XML response processing code