Académique Documents
Professionnel Documents
Culture Documents
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
MapPoint Web Service Method Upgrade Table .............................................................................................. 23 Development Cycle ..................................................................................................................................................... 24
MapPoint ......................................................................................................................................................................................... 24 Bing Maps ....................................................................................................................................................................................... 24
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.
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.
Service Comparison
Each MWS service has a high level equivalent in the Bing Maps REST Services. MapPoint Web Service Find Service Render Service Route Service Customer Data Service Bing Maps REST Services Locations API Imagery API Routes API Spatial Data API
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.
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 persons email address, mpnet@microsoft.com 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 applications 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.
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. 2. 3. 4. 5. 6. Maps Geocoding (by address) Reverse Geocoding Adding a Pushpin Displaying Routes 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";
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
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
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.
10
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
Figure 4
11
Listing 8
Loading a localized map using the Bing Maps REST Imagery API
Figure 5
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.
12
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
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=W A&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.
13
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/enus/library/bb412179.aspx.
14
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.
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".
15
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
16
Figure 6
Figure 7
17
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;
18
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
19
Figure 9
For more information on the routing options available in the Bing Maps Routes API, see http://msdn.microsoft.com/en-us/library/ff701705.aspx.
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);
20
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
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);
21
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/enus/library/ff701705.aspx.
22
1.
23
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.
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.
24
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 mpnet@microsoft.com if you require additional keys.
25
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
26
27
} [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
28
{ [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 {
29
[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")]
30
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")]
31
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; }
32
[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
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,
33
-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
34
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
35
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
36
37
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
38
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
39
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);
40
LatLong coords = foundResults.getResults()[0].getFoundLocation() .getLatLong(); double latitude = coords.getLatitude(); double longitude = coords.getLongitude();
Listing 42 MapPoint Java code to geocode an address
41
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
42
43
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';
44
// 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>"); }
45
'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']['Be stMapView']['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
46
$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
47
48
$findResult=$client->call('GetLocationInfo', array('parameters' => $getLocationInfo)); checkSoapClientErrors($client, $findResult); $address=$findResult['GetLocationInfoResult']['Location'][0]['Address']['Forma ttedAddress']; echo("First matched result for ($lat,$long): $address");
Listing 55 MapPoint: Reverse Geocoding
49
'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
50
$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);
51
// 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
52
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);
53
// 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:ResourceS ets/b:ResourceSet/b:Resources/b:Location", nsmgr); double latitude = double.Parse(firstLocation.SelectSingleNode("b:Point/b:Latit ude", nsmgr).FirstChild.Value); double longitude = double.Parse(firstLocation.SelectSingleNode("b:Point/b:Long itude", nsmgr).FirstChild.Value);
Listing 61 Bing Maps geocoding with XML response
54