Professional Documents
Culture Documents
In This Section............................................................................................................................ 11 See Also ..................................................................................................................................... 12 Getting Started with the 7.0 Map Control ...................................................................................... 12 Create a Bing Maps Account and Get a Key ............................................................................. 12 Get Familiar with the Bing Maps AJAX 7.0 Control ................................................................... 12 What's New in the AJAX Map Control ........................................................................................... 12 New Features ............................................................................................................................. 12 Developing with the 7.0 Map Control............................................................................................. 13 In This Section............................................................................................................................ 13 Loading the AJAX Map Control ..................................................................................................... 13 Displaying the Default Map ........................................................................................................ 13 Customizing the Map When Loading ......................................................................................... 16 Example ..................................................................................................................................... 16 Setting Map Control Parameters ................................................................................................... 17 Parameters ................................................................................................................................. 17 Setting Parameters..................................................................................................................... 18 See Also ..................................................................................................................................... 18 Changing the Map View ................................................................................................................ 19 Setting the Initial Map View ........................................................................................................ 19 Changing the Map View ............................................................................................................. 20 Adding Entities to the Map ............................................................................................................. 22 Adding Single Entities to the Map .............................................................................................. 22 Adding a Pushpin .................................................................................................................... 22 Adding a Shape ...................................................................................................................... 25 Adding Multiple Entities to the Map ............................................................................................ 26 Changing Entities on the Map .................................................................................................... 27 Customizing Your Pushpins .......................................................................................................... 30 Customizing Your Pushpin Icon ................................................................................................. 30 Creating a Pushpin Infobox ........................................................................................................ 31 Displaying Location Search Results Using the REST Services .................................................... 33 Initialize the Map ........................................................................................................................ 34 Add Controls ............................................................................................................................... 35 Make a Geocode REST Request ............................................................................................... 35
Display the Results..................................................................................................................... 36 Getting Route Directions Using the REST Services ...................................................................... 39 Initialize the Map ........................................................................................................................ 39 Construct the Route Request ..................................................................................................... 40 Display the Results..................................................................................................................... 40 Working with Tile Layers ............................................................................................................... 43 Adding a Tile Layer .................................................................................................................... 43 Using Events in the AJAX Control ................................................................................................. 45 Example ..................................................................................................................................... 45 Returning a Localized Map ............................................................................................................ 49 Setting the Culture...................................................................................................................... 49 Supported Cultures .................................................................................................................... 49 Remarks ..................................................................................................................................... 50 Building Your Own Module ............................................................................................................ 50 Develop Your Module ................................................................................................................. 51 Register and Load Your Module ................................................................................................ 52 Use Your Module........................................................................................................................ 52 See Also ..................................................................................................................................... 54 Microsoft.Maps API Reference ...................................................................................................... 54 In This Section............................................................................................................................ 54 Data Structures ....................................................................................................................... 54 Mapping .................................................................................................................................. 54 Entities .................................................................................................................................... 54 User Location .......................................................................................................................... 55 Dynamic Module Loading ....................................................................................................... 55 AltitudeReference Enumeration ..................................................................................................... 55 Constants ................................................................................................................................... 55 Methods ...................................................................................................................................... 55 Example ..................................................................................................................................... 56 AnimationVisibility Enumeration .................................................................................................... 57 Constants ................................................................................................................................... 57 Color Class .................................................................................................................................... 57 Constructor ................................................................................................................................. 58 Properties ................................................................................................................................... 58 Static Methods............................................................................................................................ 58 Methods ...................................................................................................................................... 58 Example ..................................................................................................................................... 59
Coordinates Class ......................................................................................................................... 62 Properties ................................................................................................................................... 62 See Also ..................................................................................................................................... 62 EntityCollection Class .................................................................................................................... 62 Constructor ................................................................................................................................. 62 Methods ...................................................................................................................................... 63 Events ........................................................................................................................................ 64 Example ..................................................................................................................................... 66 EntityCollectionOptions Object ...................................................................................................... 68 Properties ................................................................................................................................... 68 Example ..................................................................................................................................... 68 Events Object ................................................................................................................................ 70 Methods ...................................................................................................................................... 70 Example ..................................................................................................................................... 71 GeoLocationProvider Class ........................................................................................................... 73 Constructor ................................................................................................................................. 73 Methods ...................................................................................................................................... 73 Example ..................................................................................................................................... 75 See Also ..................................................................................................................................... 77 Infobox Class ................................................................................................................................. 77 Constructor ................................................................................................................................. 77 Methods ...................................................................................................................................... 77 Events ........................................................................................................................................ 80 Remarks ..................................................................................................................................... 80 Example ..................................................................................................................................... 81 InfoboxOptions Object ................................................................................................................... 83 Properties ................................................................................................................................... 83 Example ..................................................................................................................................... 85 See Also ..................................................................................................................................... 87 KeyEventArgs Object .................................................................................................................... 87 Properties ................................................................................................................................... 87 Example ..................................................................................................................................... 87 LabelOverlay Enumeration ............................................................................................................ 89 Constants ................................................................................................................................... 89 Methods ...................................................................................................................................... 89 Example ..................................................................................................................................... 89 Location Class (AJAX) ................................................................................................................... 91
Constructor ................................................................................................................................. 91 Properties ................................................................................................................................... 91 Static Methods............................................................................................................................ 91 Methods ...................................................................................................................................... 92 Example ..................................................................................................................................... 92 LocationRect Class ........................................................................................................................ 93 Constructor ................................................................................................................................. 94 Properties ................................................................................................................................... 94 Static Methods............................................................................................................................ 94 Methods ...................................................................................................................................... 95 Example ..................................................................................................................................... 96 Map Class ...................................................................................................................................... 97 Constructor ................................................................................................................................. 97 Properties ................................................................................................................................... 98 Static Methods............................................................................................................................ 98 Methods ...................................................................................................................................... 98 Events ...................................................................................................................................... 102 Example ................................................................................................................................... 104 MapMode Class (AJAX) .............................................................................................................. 105 Mercator Map Mode Methods .................................................................................................. 105 MapOptions Object ...................................................................................................................... 106 Properties ................................................................................................................................. 106 Example ................................................................................................................................... 110 MapTypeId Enumeration ............................................................................................................. 111 Constants ................................................................................................................................. 111 Example ................................................................................................................................... 112 See Also ................................................................................................................................... 113 Module Loading Methods ............................................................................................................ 113 Methods .................................................................................................................................... 113 Example ................................................................................................................................... 114 See Also ................................................................................................................................... 116 MouseEventArgs Object .............................................................................................................. 116 Properties ................................................................................................................................. 116 Methods .................................................................................................................................... 117 Example ................................................................................................................................... 118 PixelReference Enumeration ....................................................................................................... 119 Constants ................................................................................................................................. 119 Methods .................................................................................................................................... 120
Example ................................................................................................................................... 120 Point Class ................................................................................................................................... 122 Constructor ............................................................................................................................... 122 Properties ................................................................................................................................. 122 Static Methods.......................................................................................................................... 122 Methods .................................................................................................................................... 122 Example ................................................................................................................................... 123 Polygon Class (AJAX) ................................................................................................................. 124 Constructor ............................................................................................................................... 124 Methods .................................................................................................................................... 125 Events ...................................................................................................................................... 126 Example ................................................................................................................................... 127 PolygonOptions Object ................................................................................................................ 128 Properties ................................................................................................................................. 128 Example ................................................................................................................................... 129 Polyline Class .............................................................................................................................. 131 Constructor ............................................................................................................................... 131 Methods .................................................................................................................................... 131 Events ...................................................................................................................................... 132 Example ................................................................................................................................... 133 PolylineOptions Object ................................................................................................................ 134 Properties ................................................................................................................................. 135 Example ................................................................................................................................... 135 Position Class .............................................................................................................................. 137 Properties ................................................................................................................................. 137 See Also ................................................................................................................................... 137 PositionCircleOptions Object ....................................................................................................... 137 Properties ................................................................................................................................. 137 Example ................................................................................................................................... 138 PositionError Class ...................................................................................................................... 139 Properties ................................................................................................................................. 139 See Also ................................................................................................................................... 140 PositionOptions Object ................................................................................................................ 140 Properties ................................................................................................................................. 140 Example ................................................................................................................................... 142 Pushpin Class (AJAX) ................................................................................................................. 144
Constructor ............................................................................................................................... 144 Methods .................................................................................................................................... 144 Events ...................................................................................................................................... 145 Example ................................................................................................................................... 147 PushpinOptions Object ................................................................................................................ 148 Properties ................................................................................................................................. 148 Example ................................................................................................................................... 149 TileLayer Class ............................................................................................................................ 151 Constructor ............................................................................................................................... 151 Methods .................................................................................................................................... 151 Events ...................................................................................................................................... 152 Example ................................................................................................................................... 152 See Also ................................................................................................................................... 154 TileLayerOptions Object .............................................................................................................. 154 Properties ................................................................................................................................. 154 Example ................................................................................................................................... 155 See Also ................................................................................................................................... 157 TileSource Class.......................................................................................................................... 157 Constructor ............................................................................................................................... 157 Methods .................................................................................................................................... 157 Example ................................................................................................................................... 158 See Also ................................................................................................................................... 159 TileSourceOptions Object ............................................................................................................ 159 Properties ................................................................................................................................. 159 Example ................................................................................................................................... 160 See Also ................................................................................................................................... 162 ViewOptions Object ..................................................................................................................... 162 Properties ................................................................................................................................. 162 Remarks ................................................................................................................................... 163 Example ................................................................................................................................... 164 Microsoft.Maps.Directions API Reference ................................................................................... 165 In This Section.......................................................................................................................... 165 BusinessDetails Class ................................................................................................................. 166 Properties ................................................................................................................................. 167 See Also ................................................................................................................................... 167 BusinessDisambiguationSuggestion Class ................................................................................. 167 Properties ................................................................................................................................. 167
Example ................................................................................................................................... 168 See Also ................................................................................................................................... 172 DirectionsErrorEventArgs Object................................................................................................. 172 Properties ................................................................................................................................. 172 Example ................................................................................................................................... 172 DirectionsEventArgs Object ......................................................................................................... 174 Properties ................................................................................................................................. 174 Example ................................................................................................................................... 175 DirectionsManager Class ............................................................................................................ 177 Constructor ............................................................................................................................... 177 Methods .................................................................................................................................... 177 Events ...................................................................................................................................... 182 Example ................................................................................................................................... 183 DirectionsRenderOptions Object ................................................................................................. 185 Properties ................................................................................................................................. 185 Example ................................................................................................................................... 188 DirectionsRequestOptions Object ............................................................................................... 190 Properties ................................................................................................................................. 190 Example ................................................................................................................................... 192 DirectionsStep Class ................................................................................................................... 194 Properties ................................................................................................................................. 194 Example ................................................................................................................................... 195 DirectionsStepEventArgs Object ................................................................................................. 198 Properties ................................................................................................................................. 198 Example ................................................................................................................................... 199 DirectionsStepRenderEventArgs Object ..................................................................................... 202 Properties ................................................................................................................................. 202 Example ................................................................................................................................... 203 DirectionsStepWarning Class ...................................................................................................... 205 Properties ................................................................................................................................. 205 Example ................................................................................................................................... 205 Disambiguation Class .................................................................................................................. 208 Properties ................................................................................................................................. 208 Example ................................................................................................................................... 209 See Also ................................................................................................................................... 213 DistanceUnit Enumeration (AJAX) .............................................................................................. 213
Constants ................................................................................................................................. 213 Example ................................................................................................................................... 213 IconType Enumeration ................................................................................................................ 215 Constants ................................................................................................................................. 215 Example ................................................................................................................................... 216 LocationDisambiguationSuggestion Class .................................................................................. 219 Properties ................................................................................................................................. 219 Example ................................................................................................................................... 219 See Also ................................................................................................................................... 223 Maneuver Enumeration ............................................................................................................... 223 Constants ................................................................................................................................. 223 Example ................................................................................................................................... 227 ResetDirectionsOptions Object ................................................................................................... 230 Properties ................................................................................................................................. 230 Route Class (AJAX) ..................................................................................................................... 231 Properties ................................................................................................................................. 231 RouteAvoidance Enumeration ..................................................................................................... 231 Constants ................................................................................................................................. 231 RouteLeg Class (AJAX) ............................................................................................................... 232 Properties ................................................................................................................................. 232 Example ................................................................................................................................... 233 RouteMode Enumeration ............................................................................................................. 235 Constants ................................................................................................................................. 235 RouteOptimization Enumeration (AJAX) ..................................................................................... 236 Constants ................................................................................................................................. 236 RoutePath Class (AJAX) ............................................................................................................. 236 Properties ................................................................................................................................. 237 RouteResponseCode Enumeration ............................................................................................. 237 Constants ................................................................................................................................. 237 Example ................................................................................................................................... 239 RouteSelectorEventArgs Object .................................................................................................. 241 Properties ................................................................................................................................. 241 RouteSelectorRenderEventArgs Object ...................................................................................... 242 Properties ................................................................................................................................. 242
RouteSubLeg Class ..................................................................................................................... 242 Properties ................................................................................................................................. 243 RouteSummary Class (AJAX) ..................................................................................................... 243 Properties ................................................................................................................................. 243 Example ................................................................................................................................... 244 RouteSummaryRenderEventArgs Object .................................................................................... 246 Properties ................................................................................................................................. 246 StepWarningStyle Enumeration .................................................................................................. 247 Constants ................................................................................................................................. 247 Example ................................................................................................................................... 248 TimeType Enumeration ............................................................................................................... 251 Constants ................................................................................................................................. 251 Example ................................................................................................................................... 251 See Also ................................................................................................................................... 254 TransitLine Class ......................................................................................................................... 254 Properties ................................................................................................................................. 254 Example ................................................................................................................................... 254 TransitOptions Object .................................................................................................................. 257 Properties ................................................................................................................................. 257 Example ................................................................................................................................... 258 Waypoint Class (AJAX) ............................................................................................................... 260 Constructor ............................................................................................................................... 260 Methods .................................................................................................................................... 260 Events ...................................................................................................................................... 262 Example ................................................................................................................................... 263 WaypointEventArgs Object .......................................................................................................... 266 Properties ................................................................................................................................. 267 WaypointOptions Object .............................................................................................................. 267 Properties ................................................................................................................................. 267 Example ................................................................................................................................... 268 WaypointRenderEventArgs Object .............................................................................................. 270 Properties ................................................................................................................................. 270 Microsoft.Maps.Overlays.Style Reference .................................................................................. 271 Navigation Bar Style ................................................................................................................. 271 Microsoft.Maps.Traffic API Reference ......................................................................................... 272
In This Section.......................................................................................................................... 272 TrafficLayer Class ........................................................................................................................ 272 Constructor ............................................................................................................................... 272 Methods .................................................................................................................................... 273 Example ................................................................................................................................... 273 Microsoft.Maps.VenueMaps API Reference ............................................................................... 274 In This Section.......................................................................................................................... 274 Floor Class ................................................................................................................................... 275 Properties ................................................................................................................................. 275 Example ................................................................................................................................... 275 Footprint Class............................................................................................................................. 278 Properties ................................................................................................................................. 278 Example ................................................................................................................................... 278 Metadata Class ............................................................................................................................ 280 Properties ................................................................................................................................. 280 Example ................................................................................................................................... 281 NearbyVenue Class ..................................................................................................................... 283 Properties ................................................................................................................................. 283 Example ................................................................................................................................... 283 NearbyVenueOptions Object ....................................................................................................... 285 Properties ................................................................................................................................. 285 Example ................................................................................................................................... 285 Polygon Class (Venue Map) ........................................................................................................ 287 Properties ................................................................................................................................. 287 Primitive Class ............................................................................................................................. 287 Properties ................................................................................................................................. 288 Methods .................................................................................................................................... 288 Example ................................................................................................................................... 289 VenueMap Class ......................................................................................................................... 291 Properties ................................................................................................................................. 291 Methods .................................................................................................................................... 292 Events ...................................................................................................................................... 292 Example ................................................................................................................................... 293 VenueMapCreationOptions Object .............................................................................................. 295 Properties ................................................................................................................................. 295 Example ................................................................................................................................... 296
VenueMapFactory Class ............................................................................................................. 297 Constructor ............................................................................................................................... 297 Methods .................................................................................................................................... 298 Example ................................................................................................................................... 298 Bing Maps AJAX Control 7.0 Supported Browsers ..................................................................... 300 Supported Browsers ................................................................................................................. 300 Bing Maps AJAX Control 7.0 Developer Resources ................................................................... 301 Developer Resources ............................................................................................................... 301 Account Issues ......................................................................................................................... 301 Licensing Questions ................................................................................................................. 301 Bing Maps AJAX Control, Version 7.0 Bing Maps is an online mapping service that enables users to search, discover, explore, plan, and share information about specific locations. By using enhanced road maps, labeled aerial photo views, and low-angle high-resolution aerial photos, Bing Maps AJAX Control 7.0, in conjunction with the Bing Maps REST Services, provides unique opportunities for developers to incorporate both location and local search features into their Web applications. The Bing Maps AJAX Control 7.0 software development kit (SDK) consists of a complete set of reference topics that cover the Bing Maps AJAX Control 7.0 application programming interface (API). For extra code snippets and feature samples, the Bing Maps AJAX Control 7.0 Interactive SDK is also available. If you are reading this help file online, you can download either the CHM or PDF version of this SDK for offline viewing. If you are looking for documentation for the legacy AJAX Map Control, see Bing Maps AJAX Control, Version 6.3 SDK.
In This Section
Getting Started with the 7.0 Map Control What's New in the AJAX Map Control Developing with the 7.0 Map Control Microsoft.Maps API Reference Microsoft.Maps.Directions API Reference Microsoft.Maps.Overlays.Style Reference Microsoft.Maps.Traffic API Reference Microsoft.Maps.VenueMaps API Reference Supported Browsers Developer Resources
See Also
Terms and Conditions
When the Bing Maps AJAX Control 7.0 is loaded with a valid Bing Maps Key, Bing Maps counts sessions. A session begins with the load of the Bing Maps AJAX Control 7.0 into a users browser and includes all Bing Maps AJAX Control 7.0 interactions until the browser is closed or the user moves to a different page. Detailed information about Bing Maps usage reports is found in Viewing Bing Maps Usage Reports.
New Features
This release of the map control includes the following new features: Calculate driving directions Use the new Microsoft.Maps.Directions module to easily calculate directions and display a route on your map. Display a venue map Discover and display maps for nearby venues such as malls and shopping centers using the Microsoft.Maps.VenueMaps module. Show current traffic Show or hide current traffic on the map using the Microsoft.Maps.Traffic module.
Use the new Bing Maps navigation control Load the Microsoft.Maps.Overlay.Styles module and then set the customizeOverlays map option to use the new Bing Maps navigation control on your map. Set polyline and polygon stroke dash To further customize your shapes, use the new property strokeDashArray of the PolylineOptions Object and PolygonOptions Object. New tile layer property and event Ensure the best performance of your tile layer during animation by modifying the new animationDisplay property of the TileLayerOptions Object. Also, determine when your tile layer is fully downloaded using the new tiledownloadcomplete event. New map options For increased flexibility, new options showBreadcrumb, disableBirdseye, disablePanning, and disableZooming have been added to the MapOptions Object.
In This Section
Loading the AJAX Map Control Setting Map Control Parameters Changing the Map View Adding Entities to the Map Customizing Your Pushpins Displaying Location Search Results Using the REST Services Calculating Directions Using the Directions Module Working with Tile Layers Using Events in the AJAX Control Returning a Localized Map Building Your Own Module
1. At the top of the HTML page add the following DOCTYPE declaration. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2. In the header section of an HTML page, add a META element with the charset attribute set to "utf-8", as follows. <meta http-equiv="Content-Type" content="text/html; charset=utf8"/>
It is recommended that you use UTF-8 encoding in your web page. 3. Also in the header section, add a reference to the map control, as follows. <script charset="UTF-8" type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx? v=7.0"> </script> To use SSL, add the s parameter to the reference as shown below. <script charset="UTF-8" type="text/javascript" src="https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx ?v=7.0&s=1"> </script> 4. In the body of the page, add a DIV element to the page to contain the map. The size of the map is defined by the height and width of the DIV element. The position of the map is set by using the "position", "top", and "left" properties. You can set these values either inline or by defining the values in a style class and then referencing that class, as follows. <div id='mapDiv' style="position:absolute; width:400px; height:400px;"></div> or .map { position: absolute; top: 20; left: 10; width: 400px; height: 400px; border:#555555 2px solid; } ... <div id="mapDiv" class="map"></div>
If you do not specify a width/height, the width/height of the div is used. For crossbrowser compatibility, you should always specify the position attribute (both "absolute" and "relative" are valid values). If you use a percentage width and or height in the map DIV, it is the percentage of the parent width or height, respectively.
The navigation control, map type selector, and breadcrumb may not work properly if you use margin to position the map. Use CSS absolute or relative positioning instead. 5. Next, within a new script tag, create a function that can be called when your web page loads. <script type="text/javascript"> function GetMap() { } </script> Modify the body tag so that the GetMap function is called onload. <body onload="GetMap();"> 6. Finally, create an instance of the Map Class in the GetMap function. You also need to include a map options object to contain your credentials, which is your Bing Maps Key. See the Getting a Bing Maps Key topic. <script type="text/javascript"> var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:"Your Bing Maps Key"}); </script> The full code is below.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:"Your Bing Maps Key"}); }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:absolute; width:400px; height:400px;"></div> </body> </html>
Example
The following code shows a complete Web page that loads a map. Valid map types are found in the MapTypeId Enumeration topic.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title>
var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials: "Your Bing Maps Key", center: new Microsoft.Maps.Location(45.5, -122.5), mapTypeId: Microsoft.Maps.MapTypeId.road, zoom: 7}); } </script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> </body> </html>
Parameters
The following table contains available parameters for the map control reference.
Parameter Values Description
7.0
Specifies a major API version. The default value is the latest version, which is 7.0. Specifies whether to use SSL.
0, 1
Parameter
Values
Description
Set this value equal to 1 to use SSL. The default value is 0. mkt See the Returning a Localized Map topic for a list of values. Specifies the market to use, which defines the language Bing Maps AJAX Control 7.0 uses. The default value is "en-US" (English). Specifies the name of a JavaScript function to call when the map control script is loaded. The name must contain only alphanumeric characters. The CSS and tiles will not be loaded when this function is called. This parameter is useful for loading the map control asynchronously, which can improve your site performance by allowing the map control script to load in parallel with other content.
onscriptload
Setting Parameters
To add a parameter to the map control src URL, add a "?", the parameter, and set it "=" to one of the allowable values. Use "&" to separate parameters. The following example sets the map control version to 7.0 and the market to Italian.
<script charset="UTF-8" type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0&mkt=it-IT"> </script>
See Also
Loading the AJAX Map Control Returning a Localized Map
<script type="text/javascript"> function GetMap() { var mapOptions = { credentials: "Your Bing Maps Key", center: new Microsoft.Maps.Location(47.592, -122.332), mapTypeId: Microsoft.Maps.MapTypeId.birdseye, zoom: 17, showScalebar: false }
<script type="text/javascript">
function GetMap() { map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials: "Your Bing Maps Key", mapTypeId: Microsoft.Maps.MapTypeId.road}); }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:500px; height:500px;"></div> Zoom Level: <input id="txtZoom" type="text" value="1"/> <input id="btnZoom" type="button" value="Click to set the zoom level" onclick="SetZoom();"/>
</body> </html>
To set the boundaries of the view instead of centering on a point, use the bounds option as shown in the code below.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() {
var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(47.618594, -122.347618), new Microsoft.Maps.Location(47.620700, 122.347584), new Microsoft.Maps.Location(47.622052, -122.345869));
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:500px; height:500px;"></div> </body> </html>
Adding a Pushpin
The following code adds a pushpin to the center of the map with the label 1.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:"Your Bing Maps Key"});
// Add a pin to the center of the map var pin = new Microsoft.Maps.Pushpin(center, {text: '1'}); map.entities.push(pin); }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> </body> </html>
To add a pushpin to a custom latitude and longitude coordinate, pass the Location object to the Pushpin constructor, then set the view based on the location as shown below.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("myMap"), {credentials:"Bing Maps Key"});
</script> </head> <body onload="GetMap();"> <div id='myMap' style="position:relative; width:400px; height:400px;"></div> </body> </html>
Adding a Shape
To add a polyline or a polygon, use the same method used to add a pushpin. First, create your shape then add it to the entities property of the map. The following code adds a purple polygon to the map.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Your Bing Maps Key"});
// Create a polygon var vertices = new Array(new Microsoft.Maps.Location(20,-20), new Microsoft.Maps.Location(20,20), new Microsoft.Maps.Location(-20,20), new Microsoft.Maps.Location(-20,-20), new Microsoft.Maps.Location(20,-20)); var polygoncolor = new Microsoft.Maps.Color(100,100,0,100); var polygon = new Microsoft.Maps.Polygon(vertices,{fillColor: polygoncolor, strokeColor: polygoncolor});
</script>
</head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> </body> </html>
<script type="text/javascript">
function GetMap() { // Initialize the map var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:"Your Bing Maps Key"});
// Create the locations var location1 = new Microsoft.Maps.Location(20,-20); var location2 = new Microsoft.Maps.Location(20,20); var location3 = new Microsoft.Maps.Location(-20,20); var location4 = new Microsoft.Maps.Location(-20,-20);
// Create a polygon
var vertices = new Array(location1, location2, location3, location4, location1); var polygoncolor = new Microsoft.Maps.Color(100,100,0,100); var polygon = new Microsoft.Maps.Polygon(vertices,{fillColor: polygoncolor, strokeColor: polygoncolor});
// Create the entity collection with the polygon and pushpins at each corner var polygonWithPins = new Microsoft.Maps.EntityCollection(); polygonWithPins.push(polygon); polygonWithPins.push(new Microsoft.Maps.Pushpin(location1)); polygonWithPins.push(new Microsoft.Maps.Pushpin(location2)); polygonWithPins.push(new Microsoft.Maps.Pushpin(location3)); polygonWithPins.push(new Microsoft.Maps.Pushpin(location4));
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> </body> </html>
<script type="text/javascript">
// Define colors var blue = new Microsoft.Maps.Color(100, 0, 0, 200); var green = new Microsoft.Maps.Color(100, 0, 100, 100); var purple = new Microsoft.Maps.Color(100, 100, 0, 100);
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Your Bing Maps Key"});
// Create the locations var location1 = new Microsoft.Maps.Location(20,-20); var location2 = new Microsoft.Maps.Location(20,20); var location3 = new Microsoft.Maps.Location(-20,20); var location4 = new Microsoft.Maps.Location(-20, -20); var location5 = new Microsoft.Maps.Location(40, 0);
// Create some shapes var triangleVertices = new Array(location1, location2, location5, location1); var triangle = new Microsoft.Maps.Polygon(triangleVertices, { fillColor: blue, strokeColor: blue });
var squareVertices = new Array(location1, location2, location3, location4, location1); var square = new Microsoft.Maps.Polygon(squareVertices,{fillColor: purple, strokeColor:purple});
function ChangePolygonColor() { // Get the map square entity. We know square was the last entity added, // so we can calculate the index.
if((currentColor.toString()) == (purple.toString())) { // Change it to green mapSquare.setOptions({fillColor: green, strokeColor:green}); } else { // Change it back to purple mapSquare.setOptions({fillColor:purple, strokeColor:purple}); } } </script> </head> <body onload="GetMap();">
<div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <input id="btnChangeColor" type="button" value="Change Polygon Color" onclick="ChangePolygonColor();"/> </body> </html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("myMap"), {credentials:"Bing Maps Key"});
// Add a pin to the center of the map, using a custom icon var pin = new Microsoft.Maps.Pushpin(center, {icon: 'BluePushpin.png', width: 50, height: 50, draggable: true});
map.entities.push(pin); }
</script> </head> <body onload="GetMap();"> <div id='myMap' style="position:relative; width:400px; height:400px;"></div> </body> </html>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("myMap"), {credentials:"Bing Maps Key"});
// Add a pin to the center of the map var pin = new Microsoft.Maps.Pushpin(center, {text: '1'});
// Create the infobox for the pushpin pinInfobox = new Microsoft.Maps.Infobox(pin.getLocation(), {title: 'My Pushpin', description: 'This pushpin is located at (0,0).', visible: false, offset: new Microsoft.Maps.Point(0,15)});
// Add handler for the pushpin click event. Microsoft.Maps.Events.addHandler(pin, 'click', displayInfobox);
// Hide the infobox when the map is moved. Microsoft.Maps.Events.addHandler(map, 'viewchange', hideInfobox);
function hideInfobox(e) { pinInfobox.setOptions({ visible: false }); } </script> </head> <body onload="GetMap();"> <div id='myMap' style="position:relative; width:500px; height:500px;"></div> </body> </html>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Your Bing Maps Key", mapTypeId:Microsoft.Maps.MapTypeId.road});
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> </body> </html>
Add Controls
For this sample, add a text box and a Geocode button. In your script, create a ClickGeocode function that is called when the button is clicked.
<input id="txtQuery" type="text" value="Portland"/> <input type="button" value="Geocode" onclick="ClickGeocode()"/>
Since the Bing Maps REST Services also require a Bing Maps Key, you need to first retrieve the key from the map object to ensure the session is valid. Use the getCredentials method of the Map Class to do this. The getCredentials method takes a function to call when the credentials are retrieved.
function ClickGeocode(credentials) { map.getCredentials(MakeGeocodeRequest); }
CallRestService(geocodeRequest); }
function CallRestService(request) { var script = document.createElement("script"); script.setAttribute("type", "text/javascript"); script.setAttribute("src", request); document.body.appendChild(script); } function GeocodeCallback(result) { // Do something with the result }
<script type="text/javascript">
function MakeGeocodeRequest(credentials) {
CallRestService(geocodeRequest); }
if (result && result.resourceSets && result.resourceSets.length > 0 && result.resourceSets[0].resources && result.resourceSets[0].resources.length > 0) { // Set the map view using the returned bounding box var bbox = result.resourceSets[0].resources[0].bbox;
var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3])); map.setView({ bounds: viewBoundaries});
// Add a pushpin at the found location var location = new Microsoft.Maps.Location(result.resourceSets[0].resources[0].point.coordinates[0], result.resourceSets[0].resources[0].point.coordinates[1]); var pushpin = new Microsoft.Maps.Pushpin(location); map.entities.push(pushpin); } }
function CallRestService(request) { var script = document.createElement("script"); script.setAttribute("type", "text/javascript"); script.setAttribute("src", request); document.body.appendChild(script); }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <input id="txtQuery" type="text" value="Portland"/> <input type="button" value="Geocode" onclick="ClickGeocode()"/> </body> </html>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Your Bing Maps Key", mapTypeId: Microsoft.Maps.MapTypeId.road });
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> </body> </html>
Then, construct the REST route request using the input values.
var routeRequest = "http://dev.virtualearth.net/REST/v1/Routes?wp.0=" + document.getElementById('txtStart').value + "&wp.1=" + document.getElementById('txtEnd').value + "&routePathOutput=Points&output=json&jsonp=RouteCallback&key=" + credentials;
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Your Bing Maps Key", mapTypeId: Microsoft.Maps.MapTypeId.road });
function ClickRoute(credentials) {
map.getCredentials(MakeRouteRequest); }
function MakeRouteRequest(credentials) { var routeRequest = "http://dev.virtualearth.net/REST/v1/Routes?wp.0=" + document.getElementById('txtStart').value + "&wp.1=" + document.getElementById('txtEnd').value + "&routePathOutput=Points&output=json&jsonp=RouteCallback&key=" + credentials;
CallRestService(routeRequest);
function RouteCallback(result) {
if (result && result.resourceSets && result.resourceSets.length > 0 && result.resourceSets[0].resources && result.resourceSets[0].resources.length > 0) {
// Set the map view var bbox = result.resourceSets[0].resources[0].bbox; var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3])); map.setView({ bounds: viewBoundaries});
// Draw the route var routeline = result.resourceSets[0].resources[0].routePath.line; var routepoints = new Array();
// Draw the route on the map var routeshape = new Microsoft.Maps.Polyline(routepoints, {strokeColor:new Microsoft.Maps.Color(200,0,0,200)}); map.entities.push(routeshape);
} }
function CallRestService(request) { var script = document.createElement("script"); script.setAttribute("type", "text/javascript"); script.setAttribute("src", request); document.body.appendChild(script); }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <input id="txtStart" type="text" value="Seattle"/> <input id="txtEnd" type="text" value="Portland"/> <input type="button" value="Calculate Route" onclick="ClickRoute()"/> </body> </html>
<script type="text/javascript">
function GetMap() { // Initialize the map var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Your Bing Maps Key", center:new Microsoft.Maps.Location(48.03,-122.4), zoom:12, mapTypeId: Microsoft.Maps.MapTypeId.road });
try { // Create the tile layer source var tileSource = new Microsoft.Maps.TileSource({uriConstructor: 'http://www.microsoft.com/maps/isdk/ajax/layers/lidar/{quadkey}.png'});
// Construct the layer using the tile source var tilelayer= new Microsoft.Maps.TileLayer({ mercator: tileSource, opacity: .7 });
} }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> </body> </html>
Example
The example below shows how to use the Map click event to display the coordinate values of the clicked point in a text box.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("myMap"), {credentials:"Bing Maps Key"});
//Add handler for the map click event. Microsoft.Maps.Events.addHandler(map, 'click', displayLatLong);
function displayLatLong(e) { if (e.targetType == "map") { var point = new Microsoft.Maps.Point(e.getX(), e.getY()); var loc = e.target.tryPixelToLocation(point); document.getElementById("textBox").value= loc.latitude + ", " + loc.longitude;
} }
</script> </head> <body onload="GetMap();"> <div id='myMap' style="position:relative; width:400px; height:400px;"></div><br> <b>Click the map to display the coordinate values at that point.</b><br> Latitude, Longitude: <input id='textBox' type="text" style="width:250px;"/> </body> </html>
You can expand the example above and add a pushpin wherever the user clicks. The code below also greys out the other pushpins in the entities collection when a new one is added.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("myMap"), {credentials:"Bing Maps Key"});
// Add a handler for the map click event. Microsoft.Maps.Events.addHandler(map, 'click', addPin);
// Add a handler to function that will grey out // other pins in the collection when a new one is added
map.entities.push(pin); } }
function shadePins(e) {
if (noPins) {
// If there aren't yet any pins on the map, do not grey the pin out. noPins = false;
// Loop through the collection of pushpins on the map and grey out // all but the last one added (which is at the end of the array).
var i = 0; for (i = 0; i < e.collection.getLength() - 1; i++) { pin = e.collection.get(i); pin.setOptions({ icon: "GreyPin.png" }); } } }
</script> </head>
<body onload="GetMap();"> <div id='myMap' style="position:relative; width:400px; height:400px;"></div><br> <b>Click the map to add a pushpin at that point.</b><br> </body> </html>
Supported Cultures
The following table lists supported cultures for the map control imagery and Microsoft.Maps.Directions module. The Culture column lists the valid values for the mkt parameter.
Language Country/Region Culture Map Control Microsoft.Maps.Directions module
Czech Czech Republic Danish Denmark Dutch - Belgium Dutch Netherlands English - Australia English Canada
X X
X X X
Language Country/Region
Culture
Map Control
Microsoft.Maps.Directions module
English - India English - United Kingdom English - United States Finnish Finland French Canada French France German Germany Italian Italy Japanese - Japan Norwegian (Bokmal) Norway Portuguese - Brazil Portuguese - Portugal Spanish - Mexico Spanish - Spain Spanish United States Swedish - Sweden
en-IN en-GB en-US fi-FI fr-CA fr-FR de-DE it-IT ja-JP nb-NO pt-BR pt-PT es-MX es-ES es-US sv-SE
X X X X X X X X X X X X X X X X X X X X X X X X X X
Remarks
Error messages are always displayed in English - United States.
function ArrowModule(map) { // Use the given location to draw an arrow pointing to that spot this.drawRedArrow = function(location) { // Initialize the polygon locations var points = new Array(8); points[0] = location; points[1] = new Microsoft.Maps.Location(location.latitude+10, location.longitude); points[2] = new Microsoft.Maps.Location(location.latitude+5, location.longitude-5); points[3] = new Microsoft.Maps.Location(location.latitude+30, location.longitude-25); points[4] = new Microsoft.Maps.Location(location.latitude+25, location.longitude-30); points[5] = new Microsoft.Maps.Location(location.latitude+5, location.longitude-5); points[6] = new Microsoft.Maps.Location(location.latitude, location.longitude10); points[7] = location;
// Create the arrow var red = new Microsoft.Maps.Color(200, 200, 0, 0); var arrow = new Microsoft.Maps.Polygon(points, {strokeColor:red, fillColor:red});
map.entities.push(arrow);
} Microsoft.Maps.moduleLoaded('ArrowModule');
Note that the last line of the module calls the Microsoft.Maps.moduleLoaded method, which calls the main code callback function. After you have finished implementing your module, host your module script file on a web server.
Next, load your module using the Microsoft.Maps.loadModule method, specifying the function to call when the module is loaded.
Microsoft.Maps.loadModule("ArrowModule", { callback: myModuleLoaded });
<script type="text/javascript">
var map;
function myModuleLoaded() { // When the module is fully loaded, then this function is called. // Now you can initialize a module object and use the module function to // draw an arrow pointing to the center of the map.
function GetMap() { // Initialize the map var options = {credentials: "Bing Maps Key"}; map = new Microsoft.Maps.Map(document.getElementById('mapDiv'), options);
// Register and load the arrow module Microsoft.Maps.registerModule("ArrowModule", "http://example.com/arrowmodule.js"); Microsoft.Maps.loadModule("ArrowModule", { callback: myModuleLoaded });
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> </body> </html>
See Also
Module Loading Methods
In This Section
Data Structures
AltitudeReference Enumeration Location Class LocationRect Class Point Class
Mapping
Events Object KeyEventArgs Object LabelOverlay Enumeration Map Class MapMode Class MapOptions Object MapTypeId Enumeration MouseEventArgs Object PixelReference Enumeration ViewOptions Object
Entities
Color Class EntityCollection Class EntityCollectionOptions Object Events Object Infobox Class InfoboxOptions Object MouseEventArgs Object
Polyline Class PolylineOptions Object Polygon Class PolygonOptions Object Pushpin Class PushpinOptions Object TileLayer Class TileLayerOptions Object TileSource Class TileSourceOptions Object
User Location
Coordinates Class GeoLocationProvider Class Position Class PositionCircleOptions Object PositionError Class PositionOptions Object
AltitudeReference Enumeration
Defines the reference point from which the altitude is measured.
Constants
Name Description
ground ellipsoid
The altitude is measured from the ground level. The altitude is measured from the WGS 84 ellipsoid of the Earth.
Methods
Name
Definition
isValid(reference:AltitudeReference)
Return Value
Description
isValid
boolean
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript"> function GetMap() { // Create two locations with different altitude references. var groundLoc = new Microsoft.Maps.Location(47, -122, 100, Microsoft.Maps.AltitudeReference.ground); var ellipsoidLoc = new Microsoft.Maps.Location(47, -122, 100, Microsoft.Maps.AltitudeReference.ellipsoid);
// Set the map view var mapOptions = {credentials: "Bing Maps Key", center: groundLoc, mapTypeId: Microsoft.Maps.MapTypeId.birdseye, zoom:16};
// Add two pushpins to demonstrate the difference when using different altitude references map.entities.push(new Microsoft.Maps.Pushpin(groundLoc, {text: "G"})); map.entities.push(new Microsoft.Maps.Pushpin(ellipsoidLoc, {text: "E"}));
} </script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:600px; height:600px;"></div> </body> </html>
AnimationVisibility Enumeration
Defines a tile layers visibility during animation.
Constants
Name Description
auto
The map control determines whether or not to show a tile layer based on system capability. If a browser can render a tile layer with acceptable performance, it is displayed during animations. The tile layer is not displayed during animation. The tile layer is displayed during animations. This option may impact performance on older browsers.
hide show
Color Class
Represents a color.
Constructor
Name Definition
Color(a:number, r:number, g:number, b:number)
Description
Color
Initializes a new instance of the Color class. The a parameter represents opacity. The range of valid values for all parameters is 0 to 255.
Properties
Name Type Description
a r g
The opacity of the color. The range of valid values is 0 to 255. The red value of the color. The range of valid values is 0 to 255. The green value of the color. The range of valid values is 0 to 255. The blue value of the color. The range of valid values is 0 to 255.
number
Static Methods
Name Definition
clone(color:Color)
Return Value
Description
clone fromHex
Color Color
Creates a copy of the Color object. Converts the specified hex string to a Color.
fromHex(hex:string)
Methods
Name
Definition
clone()
Return Value
Description
clone getOpacity
Color number
Returns a copy of the Color object. Returns the opacity of the Color as a value between 0 (a=0) and 1 (a=255). Converts the Color into a 6-digit hex string. Opacity is ignored. For example, a Color with values (255,0,0,0) is returned as hex string #000000. Converts the Color object to a string.
getOpacity()
toHex
toHex()
string
toString
toString()
string
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() {
// Create the locations var location1 = new Microsoft.Maps.Location(-20,-20); var location2 = new Microsoft.Maps.Location(20,-20); var location3 = new Microsoft.Maps.Location(20,20); var location4 = new Microsoft.Maps.Location(60, 20); var location5 = new Microsoft.Maps.Location(60, 60);
// Create a shape var lineVertices = new Array(location1, location2, location3, location4, location5); var line = new Microsoft.Maps.Polyline(lineVertices,{strokeColor:new Microsoft.Maps.Color(100, 100, 0, 100)});
// Set the option values var opacity = document.getElementById('txtA').value; var rValue = document.getElementById('txtR').value; var gValue = document.getElementById('txtG').value; var bValue = document.getElementById('txtB').value; var lineWidth = document.getElementById('txtWidth').value;
// Verify input values and set the opacity, color, // and width of the line.
if (((opacity < 0) || (opacity > 255)) || ((rValue < 0) || (rValue > 255)) || ((gValue < 0) || (gValue > 255)) || ((bValue < 0) || (bValue > 255)) ) { alert("Opacity and all color values must be between 0 and 255."); } else { mapLine.setOptions({strokeColor:new Microsoft.Maps.Color(opacity, rValue, gValue, bValue), strokeThickness:lineWidth}); }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> Line Opacity: <input id="txtA" type="text" value="100"/><br/> Red Color Value: <input id="txtR" type="text" value="100"/><br/> Green Color Value: <input id="txtG" type="text" value="100"/><br/> Blue Color Value: <input id="txtB" type="text" value="100"/><br/> Line Width: <input id="txtWidth" type="text" value="5"/><br/> <input id="btnChangeColor" type="button" value="Set Polygon Color" onclick="SetPolygonColor();"/> </body> </html>
Coordinates Class
Represents the coordinates of the position of the user.
Properties
Name Type Description
accuracy
number
The accuracy, in meters, of the latitude and longitude values. The altitude of the location. The accuracy, in meters, of the altitude value. The direction of travel of the hosting device. The latitude of the location. The longitude of the location. The ground speed of the hosting device, in meters per second.
See Also
GeoLocationProvider Class
EntityCollection Class
Contains a collection of entities. An Entity can be any one of the following types: Infobox, Polygon, Polyline, Pushpin, TileLayer, or EntityCollection.
Constructor
Name Definition
EntityCollection(options?:EntityCollectionOptions)
Description
EntityCollection
Initializes a new
Name
Definition
Description
Methods
Name Definition Return Value Description
clear
clear()
None
Removes all entities from the collection. Returns the entity at the specified index in the collection. Returns the number of entities in the collection. Returns whether the entity collection is visible on the map. Gets the z-index of the entity collection with respect to other items on the map. Returns the index of the specified entity in the collection. If the entity is not found in the collection, -1 is returned. Inserts the specified entity
get
get(index:number)
Entity*
getLength
getLength()
number
getVisible
getVisible()
boolean
getZIndex
getZIndex()
number
indexOf
indexOf(entity:Entity*)
number
insert
insert(entity:Entity*, index:number)
None
Name
Definition
Return Value
Description
Entity*
Removes the last entity from the collection and returns it. Adds the specified entity to the last position in the collection. Removes the specified entity from the collection and returns it. Removes the entity at the specified index from the collection and returns it. Sets the options for the entity collection. Converts the EntityCollection object to a string.
push
push(entity:Entity*)
None
remove
remove(entity:Entity*)
Entity*
removeAt
removeAt(index:number)
Entity*
setOptions
setOptions(options:EntityCollectionOptions)
None
toString
toString()
string
* An Entity can be any one of the following types: Infobox, Polygon, Polyline, Pushpin, TileLayer, or EntityCollection.
Events
Name Arguments Description
entityadded
Name
Arguments
Description
collection.
One of the entities of the collection (such as another entity collection) fires the entityadded event.
For example, if collection #1 contains an entity, which is another collection #2, then when an entity is added to collection #2, two entityadded events are fired. entitychanged object: {collection: EntityCollection, entity:Entity*} Occurs when one of the following happens: The collection changes. An entity of the collection changes. One of the entities of the collection (such as another entity collection) fires the entitychanged event.
For example, if collection #1 contains an entity, which is another collection #2, then when an entity of collection #2 changes, two entitychanged events are fired. entityremoved object: {collection: EntityCollection, entity:Entity*} Occurs when one of the following happens: An entity of the collection is removed. One of the entities of the collection (such as another entity collection) fires the entityremoved event.
For example, if collection #1 contains an entity, which is another collection #2, then when an entity of collection #2 is removed, two entityremoved events are
Name
Arguments
Description
fired. * An Entity can be any one of the following types: Infobox, Polygon, Polyline, Pushpin, TileLayer, or EntityCollection.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:"Bing Maps Key"});
// Add handler for the map click event - add a pin to the click location. Microsoft.Maps.Events.addHandler(map, 'click', addPin);
function addPin(e) {
if (e.targetType == "map") {
// Return the location where the map was clicked and create the pin. var point = new Microsoft.Maps.Point(e.getX(), e.getY()); var loc = e.target.tryPixelToLocation(point); var pin = new Microsoft.Maps.Pushpin(loc);
// Attach a handler to the pin so that it is removed when it is clicked Microsoft.Maps.Events.addHandler(pin, 'click', removePin);
} }
map.entities.removeAt(indexOfPinToRemove);
<div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <b>Click the map to add a pin, or click a pin to remove it.<b/> </body> </html>
EntityCollectionOptions Object
Contains options for an entity collection.
Properties
Name Type Description
visible
boolean
A Boolean indicating whether the entity collection is visible on the map. The z-index of the entity collection with respect to other items on the map.
zIndex
number
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"});
// Add handler for the map click event - add a pin to the click location. Microsoft.Maps.Events.addHandler(map, 'click', addPin);
// Return the location where the map was clicked and create the pin. var point = new Microsoft.Maps.Point(e.getX(), e.getY()); var loc = e.target.tryPixelToLocation(point); var pin = new Microsoft.Maps.Pushpin(loc);
} }
function showAllPins(){
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <input type="button" value="Hide all pins" onclick="hideAllPins();"/> <input type="button" value="Show all pins" onclick="showAllPins();"/> </body> </html>
Events Object
Provides event handling functionality for map and entity events.
The Events object does not need to be initialized. Call the Events methods directly.
Methods
Name Definition Return Value Description
addHandler
object
Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method.
Microsoft.Maps.Events.addHandle r(map, 'viewchangedend, function(e){ event }); //Handle the
addThrottledHan dler
addThrottledHandler(target:o
object
bject, eventName:string,
Attaches the handler for the event that is thrown by the target, where
Name
Definition
handler:function, throttleInterval:number)
Return Value
Description
the minimum interval between events (in milliseconds) is specified in the throttleInterval parameter. The last occurrence of the event is called after the specified throttleInterval. boolea Checks if the target has any n attached event handler. None Invokes an event on the target. This causes all handlers for the specified eventName to be called. Detaches the specified handler from the event. The handlerId is returned by the addHandler and addThrottledHandler methods.
hasHandler invoke
removeHandler
removeHandler(handlerId:
None
object)
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap()
// Create a pin at the center of the map and its corresponding infobox var pin = new Microsoft.Maps.Pushpin(center); infobox = new Microsoft.Maps.Infobox(center, {title: 'Pushpin infobox', visible:false, offset:new Microsoft.Maps.Point(0,35)});
// Add event handlers for hovering over the pushpin Microsoft.Maps.Events.addHandler(pin, 'mouseover', showInfobox); Microsoft.Maps.Events.addHandler(pin, 'mouseout', hideInfobox);
// Add the pushpin and hidden infobox to the map map.entities.push(pin); map.entities.push(infobox);
</script> </head> <body onload="GetMap();"> <div id='myMap' style="position:relative; width:500px; height:500px;"></div> </body> </html>
GeoLocationProvider Class
Contains methods for obtaining and displaying the users current location.
This functionality is only available on browsers that support the W3C GeoLocation API.
Constructor
Name Definition
GeoLocationProvider(map:Map)
Description
GeoLocationProvider
Methods
Name Definition Retur n Value Description
addAccuracyCircle
None
Renders a geo location accuracy circle on the map. The accuracy circle is created with the center at the specified location, using the
Name
Definition
Retur n Value
Description
given radiusInMeters, and with the specified number of segments for the accuracy circle polygon. Additional options are also available to adjust the style of the polygon. cancelRequest
cancelRequest()
None
Cancels the processing of the current getCurrentPositio n request. This method prevents the response from being processed. Obtains the users current location and displays it on the map.
getCurrentPosition
getCurrentPosition(options:PositionOptio
None
ns)
The accuracy of the user location obtained using this method varies widely dependin g on the desktop browser
Name
Definition
Retur n Value
Description
or mobile device of the requestin g client. Desktop users may experienc e low user location accuracy (accuracy circles with large radiuses), while mobile user location accuracy may be much greater (a few meters). removeAccuracyCircl removeAccuracyCircle() e None Removes the current geo location accuracy circle.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html>
<script type="text/javascript">
function GetMap() {
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> </body> </html>
See Also
PositionOptions Object
Infobox Class
Represents an info box on the map. You can use this class to create pop-up balloons for pushpins.
Constructor
Name Definition
Infobox(location:Location, options?:InfoboxOptions)
Description
Infobox
Methods
Name Definition Return Value Description
getActions
getActions()
Object
Returns a list of actions, where each item is a name-value pair indicating an action link name and the event name for the action that corresponds to that action link. Returns the point on the infobox which is anchored to the map. An anchor of (0,0) is the top left corner of the infobox. Returns the string that is printed inside the infobox. Returns the height of the infobox. Returns the infobox as HTML. Returns the ID of the infobox.
getAnchor
getAnchor()
Point
getDescription()
getHeight()
getHtmlContent() getId()
Name
Definition
Return Value
Description
getLocation
getLocation()
Location
Returns the location on the map where the infoboxs anchor is attached. Returns the amount the infobox pointer is shifted from the location of the infobox, or if showPointer is false, then it is the amount the infobox bottom left edge is shifted from the location of the infobox. The default value is (0,0), which means there is no offset. Returns the info box options. Returns a boolean indicating whether the infobox close button is shown. Returns a boolean indicating whether the infobox is drawn with a pointer. Returns a string that is the title of the info box. Returns an object containing a name-value pair indicating the link text to the right of an info box title and the event name for the action that corresponds to that link. Returns the name of the function to call when the title of the info box is clicked. Returns whether the infobox is visible. A value of false indicates that the infobox is hidden, although it is still an entity on the map.
getOffset
getOffset()
number
getOptions()
getShowCloseButton()
getShowPointer()
boolean
getTitle getTitleAction
getTitle()
string Object
getTitleAction()
string
getVisible()
boolean
Name
Definition
Return Value
Description
getWidth getZIndex
getWidth() getZIndex()
number number
Returns the width of the infobox. Returns the z-index of the infobox with respect to other items on the map. Sets the HTML content of the infobox. You can use this method to change the look of the infobox. When custom HTML is used to represent the info box, the info box is anchored at the top-left corner.
var infoboxOptions = {width :200, height :100, showCloseButton: true, zIndex: 0, offset:new Microsoft.Maps.Point(10,0), showPointer: true}; var defInfobox = new Microsoft.Maps.Infobox(map.get Center(), infoboxOptions ); map.entities.push(defInfobox); defInfobox.setHtmlContent('<di v id="infoboxText" style="background-color:White; border-style:solid;borderwidth:medium; bordercolor:DarkOrange; minheight:100px; position:absolute;top:0px; left:23px; width:240px;"><b id="infoboxTitle" style="position:absolute; top:10px; left:10px; width:220px;">myTitle</b><a id="infoboxDescription" style="position:absolute; top:30px; left:10px; width:220px;">lkjsl lkjdkl lkajdlkj
setHtmlContent
setHtmlContent(content:stri
None
ng)
Name
Definition
Return Value
Description
klasdjfkl</a></div>');
setLocation
setLocation(location:Locati
None
Sets the location on the map where the anchor of the infobox is attached. Sets options for the infobox. Converts the Infobox object to a string.
None string
Options)
toString()
Events
Name Arguments Description
click entitychanged
Occurs when the mouse is used to click the infobox. Occurs when the location of the infobox or any of the infobox options change. Occurs when the mouse cursor enters the area covered by the infobox. Occurs when the mouse cursor leaves the area covered by the infobox.
mouseenter
eventArgs:MouseEventArgs
mouseleave
eventArgs:MouseEventArgs
Remarks
The Bing Maps AJAX Control default info box is designed for desktop browsers and may not function properly on all mobile browsers. For the best performance, it is recommended that you have only one info box on the map at a time.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("myMap"), {credentials:"Bing Maps Key"});
// Add a pin to the center of the map var pin = new Microsoft.Maps.Pushpin(center, {text: '1'});
// Create the info box for the pushpin pinInfobox = new Microsoft.Maps.Infobox(new Microsoft.Maps.Location(0,0), {title: 'My Pushpin', visible: true});
// Add a handler for the pushpin click event. Microsoft.Maps.Events.addHandler(pin, 'click', displayInfobox);
// Hide the info box when the map is moved. Microsoft.Maps.Events.addHandler(map, 'viewchange', hideInfobox);
// Add the pushpin and info box to the map map.entities.push(pin); map.entities.push(pinInfobox);
</script> </head> <body onload="GetMap();"> <div id='myMap' style="position:relative; width:500px; height:500px;"></div> </html>
InfoboxOptions Object
Represents the options for an infobox.
Properties
Name Type Description
actions
Object
A list of the info box actions, where each item is a label (the link text) or icon (the URL of the image to use as the icon link) and eventHandler (name of the function handling a click of the action link).
var infoboxOptions = {title:'My Infobox', description:'Testing actions', actions:[{label: 'test1', eventHandler: testEvent1}, {label: 'test2', eventHandler: testEvent2},{label: 'test3', eventHandler: testEvent3}] };
The string displayed inside the info box. The height of the info box. The default value is 126. The HTML that represents the info box. If custom HTML is used to represent the info box, the info box is anchored at the top-left corner.
var infoboxOptions = {width :200, height :100, showCloseButton: true, zIndex: 0, offset:new Microsoft.Maps.Point(10,0), showPointer: true, htmlContent:'<b>Custom HTML</b>'};
id location
string Location
The ID associated with the info box. The location on the map where the info boxs anchor is attached.
Name
Type
Description
offset
Point
The amount the info box pointer is shifted from the location of the info box, or if showPointer is false, then it is the amount the info box bottom left edge is shifted from the location of the info box. If custom HTML is set, it is the amount the top-left corner of the info box is shifted from its location. The default offset value is (0,0), which means there is no offset. A boolean indicating whether to show the close dialog button on the info box. The default value is true. By default the close button is displayed as an X in the top right corner of the info box. This property is ignored if custom HTML is used to represent the info box.
showCloseButton
boolean
showPointer
boolean
A boolean indicating whether to display the info box with a pointer. The default value is true. In this case the info box is anchored at the bottom point of the pointer. If this property is set to false, the info box is anchored at the bottom left corner. This property is ignored if custom HTML is used to represent the info box.
title titleAction
string Object
The title of the info box. An action to take when the link to the right of an info box title is clicked. The specified object contains a label (the link text) and an eventHandler (the name of the function handling a click of the link). The name of the function to call
titleClickHandler
string
Name
Type
Description
when the title of the info box is clicked. If this property is set, the title of the info box is displayed as a link. visible boolean A boolean indicating whether to show or hide the info box. The default value is true. A value of false indicates that the info box is hidden, although it is still an entity on the map. The width of the info box. The default value is 256. The z-index of the info box with respect to other items on the map.
width zIndex
number number
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() {
// Create an info box var infoboxOptions = {width:300, height: 100, title: "Information Box Title", description: "This is the map.", showPointer: false, titleClickHandler: InfoboxHandler, offset: new Microsoft.Maps.Point(-100,0)}; var myInfobox = new Microsoft.Maps.Infobox(center, infoboxOptions);
</html>
See Also
Infobox Class
KeyEventArgs Object
Contains the arguments for keyboard events.
Properties
Name Type Description
A boolean indicating if the ALT key was pressed. A boolean indicating if the CTRL key was pressed. The event that occurred. A boolean indicating whether the event is handled. If this property is set to true, the default map control behavior for the event is cancelled. The ASCII character code that identifies the keyboard key that was pressed. The original browser event. A boolean indicating if the SHIFT key was pressed.
keyCode
string
originalEvent shiftKey
object boolean
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("myMap"), {credentials:"Bing Maps Key"});
//Add handler for the map click event. Microsoft.Maps.Events.addHandler(map, 'keypress', addPin);
function addPin(e) {
if (e.keyCode == "112") {
// If the 'p' key is pressed, add a pushpin to the center of the // current map view.
} }
</script> </head> <body onload="GetMap();"> <div id='myMap' style="position:relative; width:400px; height:400px;"></div><br> <b>Click the 'p' key to add a pushpin to the map.</b> </body> </html>
LabelOverlay Enumeration
Defines how map labels are displayed.
Constants
Name Description
hidden visible
Map labels are not shown on top of imagery. Map labels are shown on top of imagery.
Methods
Name Definition
isValid(labelOverlay:LabelOverlay)
Return Value
Description
isValid
boolean
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head>
<script type="text/javascript">
var mapOptions = { credentials:"Your Bing Maps Key", mapTypeId: Microsoft.Maps.MapTypeId.birdseye, center: new Microsoft.Maps.Location(37.794973,-122.393542), zoom: 17, labelOverlay: Microsoft.Maps.LabelOverlay.hidden }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> </body> </html>
Constructor
Name Definition
Location(latitude:number, longitude:number, altitude?:number, altitudeReference?:AltitudeReference)
Description
Location
Properties
Name Type Description
The altitude of the location. The reference from which the altitude is measured. The latitude of the location. The longitude of the location.
Static Methods
Name Definition Return Value Description
areEqual
areEqual(location1:Location, location2:Location)
boolean
normalizeLongitude
normalizeLongitude(longitude:number)
number
Name
Definition
Return Value
Description
Methods
Name Definition
clone()
Return Value
Description
clone toString
Location string
Returns a copy of the Location object. Converts the Location object to a string.
toString()
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() {
// Retrieve the latitude and longitude values- normalize the longitude value var latVal = parseInt(latLongArray[0]); var longVal = Microsoft.Maps.Location.normalizeLongitude(parseInt(latLongArray[1]));
} </script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:600px; height:600px;"></div> Latitude, Longitude: <input id="txtlatlong" type="text" value="40, -120"/> <input type="button" value="Set center location" onclick="SetLocation();"/> </body> </html>
LocationRect Class
Represents a rectangle on the map.
Constructor
Name Definition
LocationRect(center:Location, width:number, height:number)
Description
LocationRect
Properties
Name Type Description
The location that defines the center of the rectangle. The height, in degrees, of the rectangle. The width, in degrees, of the rectangle.
Static Methods
Name Definition Return Value Description
fromCorners(northwest:Loc
ation, southeast:Location)
fromEdges(north:number, west:number, south:number, east:number, altitude:number, altitudeReference:Altitude
Returns a LocationRect using the specified locations for the northwest and southeast corners. Returns a LocationRect using the specified northern and southern latitudes and western and eastern longitudes for the rectangle boundaries.
Location Rect
Returns a LocationRect using a list of locations or an array of locations. To provide a list of locations:
Microsoft.Maps.LocationRect.fromLocati
Name
Definition
Return Value
Description
fromStrin g
fromString(string:string)
Location Rect
Creates a LocationRect from a string with the following format: "north,west,south,east". North, west, south and east specify the coordinate number values.
Methods
Name Definition
clone()
Return Value
Description
clone
LocationRect
Returns a copy of the LocationRect object. Returns whether the specified Location is within the LocationRect. Returns the longitude that defines the eastern edge of the LocationRect. Returns the latitude that defines the northern edge of the LocationRect. Returns the Location that defines the
contains
contains(location:Location)
boolean
getEast
getEast()
number
getNorth
getNorth()
number
getNorthwest
getNorthwest()
Location
Name
Definition
Return Value
Description
number
Returns the latitude that defines the southern edge of the LocationRect. Returns the Location that defines the southeast corner of the LocationRect. Returns the latitude that defines the western edge of the LocationRect. Returns whether the specified LocationRect intersects with this LocationRect. Converts the LocationRect object to a string.
getSoutheast
getSoutheast()
Location
getWest
getWest()
number
intersects
intersects(rect:LocationRect)
boolean
toString
toString()
string
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() {
map.setView({bounds: viewRect});
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:500px; height:500px;"></div> </body> </html>
Map Class
Represents a map.
Constructor
Name
Definition
Map(containerElement:node, options?:MapOptions
Description
Map
or
ViewOptions)
Properties
Name Type Description
entities
EntityCollection
The maps entities. Use this property to add or remove entities from the map.
Static Methods
Name Definition
getVersion()
Return Value
Description
getVersion
string
Methods
Name Definition
blur()
Return Value
Description
blur
None
Removes focus from the map control so that it does not respond to keyboard events. Deletes the Map object and releases any associated resources. Applies focus to the map control so that it responds to keyboard events. Returns the location rectangle that defines the boundaries of the current map view.
dispose
dispose()
None
focus
focus()
None
getBounds
getBounds()
LocationRect
Name
Definition
getCenter()
Return Value
Description
getCenter
Location
Returns the location of the center of the current map view. Returns to the specified callback an array of strings representing the attributions of the imagery currently displayed on the map. Gets the session ID. This method calls the callback function with the session ID as the first parameter.
map.getCredentials(function( credentials) { if(credentials !== null) { service }); /* Valid session */ } Id. Use it to call REST
getCopyrights
getCopyrights(callback:fu
string[]
nction)
getCredentials
getCredentials(callback:f
None
unction)
getHeading()
Returns the heading of the current map view. Returns the height of the map control. Returns the string that represents the imagery currently displayed on the map. Returns a string that represents the current map type displayed on the map. Valid map types are listed in the MapTypeId Enumeration topic. Returns the current scale in meters per pixel of the center of the map.
getHeight()
getImageryId()
getMapTypeId
getMapTypeId()
string
getMetersPerPix el
getMetersPerPixel()
number
Name
Definition
getMode()
Return Value
Description
Returns the current map mode. Returns the maps mode node. Returns the map options that have been set. Note that if an option is not set, then the default value for that option is assumed and getOptions returns undefined for that option. Returns the x coordinate of the top left corner of the map control, relative to the page. Returns the y coordinate of the top left corner of the map control, relative to the page. Returns the maps root node. Returns the location rectangle that defines the boundaries of the view to which the map is navigating. Returns the center location of the view to which the map is navigating. Returns the heading of the view to which the map is navigating. Returns the scale in meters per pixel of the center of the view to which the map is navigating. Returns the zoom level of the view to which the map is navigating. Returns the maps user node.
getModeLayer() getOptions()
getPageX
getPageX()
number
getPageY
getPageY()
number
getRootElement
getRootElement()
Node LocationRect
getTargetBounds getTargetBounds()
getTargetCenter
getTargetCenter()
Location
getTargetHeading()
number
getTargetMetersPerPixel()
number
getTargetZoom
getTargetZoom()
number
getUserLayer
getUserLayer()
Node
Name
Definition
getViewportX()
Return Value
Description
getViewportX
number
Returns the x coordinate of the viewport origin (the center of the map), relative to the page. Returns the y coordinate of the viewport origin (the center of the map), relative to the page. Returns the width of the map control. Returns the zoom level of the current map view.
getViewportY
getViewportY()
number
getWidth()
number number
getZoom()
getZoomRange()
object:{min:nu Returns the range of valid mber, max: zoom levels for the current number} map view. boolean Returns whether the map is in a regular Mercator nadir mode. Returns true if the current map type allows the heading to change; false if the display heading is fixed. Sets the current map type. The specified mapTypeId must be a valid map type ID or a registered map type ID. Valid map type IDs are listed in the MapTypeId Enumeration topic. Sets the height and width of the map. Sets the map view based on the specified options. Converts a specified Location to a Point on the map relative to the specified PixelReference. If reference is not specified, PixelReference.viewport is
isMercator
isMercator()
isRotationEnable d
isRotationEnabled()
boolean
setMapType
setMapType(mapTypeId:strin
None
g)
setOptions({height:numbe
r, width: number})
setView(options:ViewOptio
ns)
tryLocationToPixel(locati on:Location |Location[], reference?:PixelReference )
Name
Definition
Return Value
Description
used. If the map is not able to convert the Location, null is returned. Alternatively, converts an array of Locations and returns an array of Points if all locations were converted. If any of the conversions fail, null is returned. tryPixelToLocati on
tryPixelToLocation(point:
Converts a specified Point to a Location on the map relative to the specified PixelReference. If reference is not specified, PixelReference.viewport is used. If the map is not able to convert the Point, null is returned. Alternatively, converts an array of Points and returns an array of Locations if all points were converted. If any of the conversions fail, null is returned.
Events
Name Arguments Description
Occurs when the mouse is used to click the map. Occurs when the copyright of the map changes. Occurs when the mouse is used to double click the map. Occurs when the underlying imagery used by the map
imagerychanged
None
Name
Arguments
Description
changes. This is different from the maptypechanged event, which occurs when the map type being used is changed. keydown keypress keyup eventArgs:KeyEventArgs eventArgs:KeyEventArgs eventArgs:KeyEventArgs Occurs when a keyboard key is pressed down. Occurs when a keyboard key is pressed. Occurs when a keyboard key that is pressed down is released. Occurs when the map type changes. Occurs when the left mouse button is pressed when the mouse cursor is over the map. Occurs when the mouse cursor moves over the map. Occurs when the mouse cursor moves out of the area covered by the map. Occurs when the mouse is over the map. Occurs when the left mouse button is lifted up when the mouse cursor is over the map. Occurs when the mouse wheel is used when the mouse cursor is over the map. Occurs when the right mouse button is used to click the map.
maptypechanged mousedown
None eventArgs:MouseEventArgs
mousemove mouseout
eventArgs:MouseEventArgs eventArgs:MouseEventArgs
mouseover mouseup
eventArgs:MouseEventArgs eventArgs:MouseEventArgs
mousewheel
eventArgs:MouseEventArgs
rightclick
eventArgs:MouseEventArgs
Name
Arguments
Description
targetviewchanged
None
Occurs when the view towards which the map is navigating changes. Occurs when all the map tiles of a map view have loaded. Occurs for every frame of a map view change. Occurs when the map view is done changing. This event occurs when a view is the same for one frame of a map view change. For example, if the mouse is used to drag the map to change the view, but pauses during the drag (without releasing the mouse button), viewchangeend occurs twice. You can use the addThrottledHandler method to customize the number of events that occur.
tiledownloadcomplete
None
viewchange viewchangeend
None None
viewchangestart
None
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("myMap"), {credentials:"Bing Maps Key"});
</script> </head> <body onload="GetMap();"> <div id='myMap' style="position:relative; width:400px; height:400px;"></div> </body> </html>
Name
Definition
Retu rn Valu e
Description
setViewChangeEn dDelay
setViewChangeEndDelay(delay :number)
Non e
Sets the specified number of milliseconds after the last viewchange event before viewchangeend event is fired. This allows you to control how often the viewchangeend event is fired when the map is panned. For example, to set a 1 second delay before the viewchangeend event fires, do the following:
map.getMode().setViewChangeEndDe lay(1000);
MapOptions Object
Represents options to customize the map that is displayed.
Properties
Name Type Description
backgroundColor
Color Class
The color to use for the map control background. The default color is #F4F2EE. This property can only be set when using the Map constructor.
credentials
string
The Bing Maps Key used to authenticate the application. This property can only be set when using the Map constructor.
customizeOverlays
boolean
A boolean indicating whether to load the new Bing Maps overlay styles. The default value is false.
Name
Type
Description
This property setting only takes effect if the Microsoft.Maps.Overlays.Style module is loaded. disableBirdseye boolean A boolean indicating whether to disable the birds eye map type. The default value is false. If this property is set to true, birds eye will be removed from the map navigation control and the birdseye MapTypeId is disabled. Additionally, the auto map type will only display road or aerial. This property can only be set when using the Map constructor. disableKeyboardInput boolean A boolean value indicating whether to disable the maps response to keyboard input. The default value is false. A boolean value indicating whether to disable the maps response to mouse input. The default value is false. A boolean value indicating whether to disable the users ability to pan the map. The default value is false. A boolean value indicating whether to disable the maps response to touch input. The default value is false. A boolean value indicating whether to disable the maps response to any user input. The default value is false. A boolean value indicating whether to disable the users ability to zoom in or out. The default value is false.
disableMouseInput
boolean
disablePanning
boolean
disableTouchInput
boolean
disableUserInput
boolean
disableZooming
boolean
Name
Type
Description
enableClickableLogo
boolean
A boolean value indicating whether TM the Bing logo on the map is clickable. The default value is true. This property can only be set when using the Map constructor.
enableSearchLogo
boolean
A boolean value indicating whether TM to enable the Bing hovering search logo on the map. The default value is true. This property can only be set when using the Map constructor.
fixedMapPosition
boolean
A boolean indicating whether the div containing the map control is fixed on the page and the browser will not be resized. The default value is false. In this case the map control redraws if necessary based on any div or window resize. If this property is set to true, the map control does not check the size of the div containing it every time the map view changes, thus increasing the performance of the control. This property can only be set when using the Map constructor.
height
number
The height of the map. The default value is null. If no height is specified, the height of the div is used. If height is specified, then width must be specified as well. A number between 0 and 1 specifying the intensity of the inertia animation effect. The inertia effect increases as the intensity value gets larger. The default value is .85. Setting this property to 0 indicates no inertia effect. The useInertia property must be set
inertiaIntensity
number
Name
Type
Description
to true for the inertiaIntensity value to have an effect. showBreadcrumb boolean A boolean value indicating whether to display the breadcrumb control. The breadcrumb control shows the current center locations geography hierarchy. For example, if the location center is Seattle, the breadcrumb control displays World . United States . WA. The default value is false. The breadcrumb control displays best when the width of the map is at least 300 pixels. This property can only be set when using the Map constructor. showCopyright boolean A boolean value indicating whether or not to show the map copyright. The default value is true. This property can only be set when using the Map constructor.
Bing Maps Platform API Terms of Use requires copyright information to be displayed. Only set this option to false when copyright information is displayed through alternate means. showDashboard boolean A boolean value indicating whether to show the map navigation control. The default value is true. This property can only be set when using the Map constructor. showMapTypeSelector boolean A boolean value indicating whether to show the map type selector in the map navigation control. The default
Name
Type
Description
value is true. This property can only be set when using the Map constructor. showScalebar boolean A boolean value indicating whether to show the scale bar. The default value is true. This property can only be set when using the Map constructor. tileBuffer number A number between 0 and 4 specifying how many tiles to use as a buffer around the map view. The default value is 0. A boolean value indicating whether to use the inertia animation effect during map navigation. The default value is true. The width of the map. The default value is null. If no width is specified, the width of the div is used. If width is specified, then height must be specified as well.
useInertia
boolean
width
number
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() {
// Set the map and view options, setting the map style to Road and // removing the user's ability to change the map style
var mapOptions = {credentials:"Bing Maps Key", height: 400, width: 400, mapTypeId: Microsoft.Maps.MapTypeId.road, showMapTypeSelector: false};
MapTypeId Enumeration
Contains identifiers for the imagery displayed on the map.
Constants
Name Description
aerial
Name
Description
The map is set to choose the best imagery for the current view. The birds eye map type is being used. Collins Bart (mkt=en-gb) map type is being used. The Mercator style is being used. Ordnance Survey (mkt=en-gb) map type is being used. The road map style is being used.
Example
This code sample sets the map imagery to Collins Bart (collinsBart). Since this imagery is only supported for the en-gb culture, the mkt parameter of the control is set to this culture.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:"Bing Maps Key", center: new Microsoft.Maps.Location(51.5, -.1), zoom: 10, mapTypeId:Microsoft.Maps.MapTypeId.collinsBart}); }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:600px; height:600px;"></div> </body> </html>
See Also
Changing the Map View Returning a Localized Map
Methods
Name Definition Return Value Description
loadModule
loadModule(moduleKey:string, options:function)
None
Loads the specified registered module, making its functionality available. An optional function can be specified that is called when the module is loaded. To register a module, use the registerModule method. The following Bing Maps modules are available: Microsoft.Maps.Venue Maps Microsoft.Maps.Directions Microsoft.Maps.Traffic
moduleLoaded
moduleLoaded(moduleKey:string)
None
Name
Definition
Return Value
Description
module has been loaded and if specified, calls the callback function in loadModule. Call this method at the end of your module script. registerModule
registerModule(moduleKey:string, scriptUrl:string, options:{styleURLs})
None
Registers a module with the map control. The name of the module is specified in moduleKey, the module script is defined in scriptUrl, and the options provides the location of a *.css file to load with the module.
To minimize possible conflicts with other custom modules, choose a unique module name (defined in moduleKey). For example, you can use your company name in the name of the module. Once you have registered a module, you can make its functionality available by loading it using loadModule.
Example
The code below shows how to register and load a module, named MyModule1. The code for MyModule1 is found in the next code section.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head>
<script type="text/javascript">
var map;
// Use the function provided by the newly loaded module var myModule = new MyModule(map); myModule.HelloWorld();
function GetMap() { // Initialize the map var options = {credentials: "Bing Maps Key"}; map = new Microsoft.Maps.Map(document.getElementById('mapDiv'), options);
// Register and load a new module Microsoft.Maps.registerModule("MyModule1", "http://example.com/mymodule.js"); Microsoft.Maps.loadModule("MyModule1", { callback: myModuleLoaded });
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> </body> </html>
// mymodule.js function MyModule(map) { this.HelloWorld = function() { alert("Hello World - map Center is " + map.getCenter().toString()); } } Microsoft.Maps.moduleLoaded('MyModule1');
See Also
Building Your Own Module
MouseEventArgs Object
Contains the arguments for mouse events.
Properties
Name Type Description
eventName handled
string boolean
The event that occurred. A boolean indicating whether the event is handled. If this property is set to true, the default map control behavior for the event is cancelled.
Name
Type
Description
isPrimary
boolean
A boolean indicating if the primary button (such as the left mouse button or a tap on a touch screen) was used. A boolean indicating if the secondary mouse button (such as the right mouse button) was used. A boolean indicating whether the event that occurred was a touch event. The original browser event. The x-value of the pixel coordinate on the page of the mouse cursor. The y-value of the pixel coordinate on the page of the mouse cursor. The object that fired the event. The type of the object that fired the event. Valid values include the following: map, polygon, polyline, or pushpin The number of units that the mouse wheel has changed.
isSecondary
boolean
isTouchEvent
boolean
originalEvent pageX
object number
pageY
number
target targetType
object string
wheelDelta
number
Methods
Name Definition
getX()
Return Value
Description
getX
number
Returns the x-value of the pixel coordinate, relative to the map, of the mouse. Returns the y-value of
getY
getY()
number
Name
Definition
Return Value
Description
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("myMap"), {credentials:"Bing Maps Key"});
//Add handler for the map click event. Microsoft.Maps.Events.addHandler(map, 'click', displayEventInfo);
var point = new Microsoft.Maps.Point(e.getX(), e.getY()); var loc = e.target.tryPixelToLocation(point); document.getElementById("textBox").value = loc.latitude + ", " + loc.longitude;
} }
</script> </head> <body onload="GetMap();"> <div id='myMap' style="position:relative; width:400px; height:400px;"></div><br> <b>Click the map to display the coordinate values at that point.</b><br> Latitude, Longitude: <input id='textBox' type="text" style="width:250px;"/> </body> </html>
PixelReference Enumeration
Contains constants used to show how pixels are defined.
Constants
Name Description
control
The pixel is defined relative to the map controls root element, where the top left corner of the map control is (0, 0). Using this option might cause a page reflow which may negatively impact performance. The pixel is defined relative to the page, where the top left corner of the HTML page is (0, 0). This option is best used when working with mouse or touch events. Using this option might cause a page reflow which may negatively
page
Name
Description
impact performance. viewport The pixel is defined in viewport coordinates, relative to the center of the map, where the center of the map is (0, 0). This option is best used for positioning geo-aligned entities added to the user layer.
Methods
Name Definition
isValid(reference:PixelReference)
Return Value
Description
isValid
boolean
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() {
// Add handler for the map click event. Microsoft.Maps.Events.addHandler(map, 'click', displayEventInfo);
var point = new Microsoft.Maps.Point(e.pageX, e.pageY, Microsoft.Maps.PixelReference.page); var loc = e.target.tryPixelToLocation(point, Microsoft.Maps.PixelReference.page);
if (loc!=null) { alert("The location " + loc.latitude + ", " + loc.longitude + " was clicked."); }
} }
</script> </head> <body onload="GetMap();"> <div id='myMap' style="position:relative; width:400px; height:400px;"></div><br> <b>Click the map to display the coordinate values at that point.</b><br>
</body> </html>
Point Class
Represents a point on the map.
Constructor
Name Definition
Point(x:number, y:number)
Description
Point
Properties
Name Type Description
x y
number number
Static Methods
Name Definition
areEqual(point1:Point, point2:Point)
Return Value
Description
areEqual
boolean
Determines if the specified points are equal. Returns a copy of the Point object.
clone
clone(Point)
Point
Methods
Name
Definition
clone()
Return Value
Description
clone toString
Point string
Returns a copy of the Point object. Converts the Point object into a string.
toString()
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("myMap"), {credentials:"Bing Maps Key "});
// Add handler for the map click event. Microsoft.Maps.Events.addHandler(map, 'click', displayEventInfo);
if (loc!=null) { alert("The location " + loc.latitude + ", " + loc.longitude + " was clicked."); }
} }
</script> </head> <body onload="GetMap();"> <div id='myMap' style="position:relative; width:400px; height:400px;"></div><br> <b>Click the map to display the coordinate values at that point.</b><br> </body> </html>
Constructor
Name Definition
Polygon(locations:Location[], options?:PolygonOptions)
Description
Polygon
Methods
Name Definition
getFillColor()
Return Value
Description
getFillColor
Color
Returns the color of the inside of the polygon. Returns the locations that define the corners of the polygon. Returns the color of the outline of the polygon. Returns the string that represents the stroke/gap sequence used to draw the outline of the polygon. Returns the thickness of the outline of the polygon. Returns whether the polygon is visible. A value of false indicates that the polygon is hidden, although it is still an entity on the map.
getLocations
getLocations()
Location[]
getStrokeColor
getStrokeColor()
Color
getStrokeDashArray
getStrokeDashArray()
string
getStrokeThickness
getStrokeThickness()
number
getVisible
getVisible()
boolean
Name
Definition
setLocations(locations:Location[])
Return Value
Description
setLocations
None
Sets the locations that define the corners of the polygon. Sets options for the polygon. Converts the Polygon object to a string.
setOptions
setOptions(options:PolygonOptions)
None
toString
toString()
string
Events
Name Arguments Description
click dblclick
eventArgs:MouseEventArgs eventArgs:MouseEventArgs
Occurs when the mouse is used to click the polygon. Occurs when the mouse is used to double click the polygon. Occurs when the location of the polygon or any of the polygons options change. Occurs when the left mouse button is pressed when the mouse is over the polygon. Occurs when the mouse cursor moves out of the area covered by the polygon. Occurs when the mouse is over the polygon. Occurs when the left
entitychanged
object: {entity:Entity}
mousedown
eventArgs:MouseEventArgs
mouseout
eventArgs:MouseEventArgs
mouseover mouseup
eventArgs:MouseEventArgs eventArgs:MouseEventArgs
Name
Arguments
Description
mouse button is lifted up when the mouse is over the polygon. rightclick eventArgs:MouseEventArgs Occurs when the right mouse button is used to click the polygon.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:"Bing Maps Key"});
// Create the locations var location1 = new Microsoft.Maps.Location(20,-20); var location2 = new Microsoft.Maps.Location(20,20); var location3 = new Microsoft.Maps.Location(-20,20); var location4 = new Microsoft.Maps.Location(-20,-20);
// Create a polygon var vertices = new Array(location1, location2, location3, location4, location1); var polygoncolor = new Microsoft.Maps.Color(100,100,0,100); var polygon = new Microsoft.Maps.Polygon(vertices,{fillColor: polygoncolor, strokeColor: polygoncolor});
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> </body> </html>
PolygonOptions Object
Represents the options for a polygon.
Properties
Name Type Description
fillColor strokeColor
Color Color
The color of the inside of the polygon. The color of the outline of the polygon.
Name
Type
Description
strokeDashArray
string
A string representing the stroke/gap sequence to use to draw the outline of the polygon. The string must be in the format S, G, S*, G*, where S represents the stroke length and G represents gap length. Stroke lengths and gap lengths can be separated by commas or spaces. For example, a stroke dash string of 1 4 2 1 would draw the polygon outline with a dash, four spaces, two dashes, one space, and then repeated. The thickness of the outline of the polygon. A boolean indicating whether to show or hide the polygon. A value of false indicates that the polygon is hidden, although it is still an entity on the map.
strokeThickness visible
number boolean
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:"Bing Maps Key"});
// Create the locations var location1 = new Microsoft.Maps.Location(20,-20); var location2 = new Microsoft.Maps.Location(20,20); var location3 = new Microsoft.Maps.Location(-20,20); var location4 = new Microsoft.Maps.Location(-20,-20);
// Create a polygon var vertices = new Array(location1, location2, location3, location4, location1); var polygon = new Microsoft.Maps.Polygon(vertices, {fillColor: new Microsoft.Maps.Color(100,100,0,100), strokeColor: new Microsoft.Maps.Color(200,0,100,100), strokeThickness: 5});
</script> </head>
Polyline Class
Represents a polyline on the map.
Constructor
Name Definition
Polyline(locations:Location[], options?:PolylineOptions)
Description
Polyline
Methods
Name Definition
getLocations()
Return Value
Description
getLocations
Location[]
Returns the locations that define the polyline. Returns the color of the polyline. Returns the string that represents the stroke/gap sequence used to draw the polyline. Returns the thickness of the polyline.
getStrokeColor
getStrokeColor()
Color
getStrokeDashArray
getStrokeDashArray()
string
getStrokeThickness
getStrokeThickness()
number
Name
Definition
getVisible()
Return Value
Description
getVisible
boolean
Returns whether the polyline is visible. A value of false indicates that the polyline is hidden, although it is still an entity on the map. Sets the locations that define the polyline. Sets options for the polyline. Converts the Polyline object to a string.
setLocations
setLocations(locations:Location[])
None
setOptions
setOptions(options:PolylineOptions)
None
toString
toString()
string
Events
Name Arguments Description
click dblclick
eventArgs:MouseEventArgs eventArgs:MouseEventArgs
Occurs when the mouse is used to click the polyline. Occurs when the mouse is used to double click the polyline. Occurs when the location of the polyline or any of the polylines options change. Occurs when the left mouse button is pressed when the mouse is over
entitychanged
object: {entity:Entity}
mousedown
eventArgs:MouseEventArgs
Name
Arguments
Description
the polyline. mouseout eventArgs:MouseEventArgs Occurs when the mouse cursor moves out of the area covered by the polyline. Occurs when the mouse is over the polyline. Occurs when the left mouse button is lifted up when the mouse is over the polyline. Occurs when the right mouse button is used to click the polyline.
mouseover mouseup
eventArgs:MouseEventArgs eventArgs:MouseEventArgs
rightclick
eventArgs:MouseEventArgs
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() {
// Create the locations var location1 = new Microsoft.Maps.Location(-20,-20); var location2 = new Microsoft.Maps.Location(20,-20); var location3 = new Microsoft.Maps.Location(20,20); var location4 = new Microsoft.Maps.Location(60, 20); var location5 = new Microsoft.Maps.Location(60, 60);
// Create a polyline var lineVertices = new Array(location1, location2, location3, location4, location5); var line = new Microsoft.Maps.Polyline(lineVertices);
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> </body> </html>
PolylineOptions Object
Represents the options for a polyline.
Properties
Name Type Description
strokeColor strokeDashArray
Color string
The color of the polyline. A string representing the stroke/gap sequence to use to draw the polyline. The string must be in the format S, G, S*, G*, where S represents the stroke length and G represents gap length. Stroke lengths and gap lengths can be separated by commas or spaces. For example, a stroke dash string of 1 4 2 1 would draw the polyline with a dash, four spaces, two dashes, one space, and then repeated. The thickness of the polyline. A boolean indicating whether to show or hide the polyline. A value of false indicates that the polyline is hidden, although it is still an entity on the map.
strokeThickness visible
number boolean
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Your Bing Maps Key"});
// Create the locations var location1 = new Microsoft.Maps.Location(-20,-20); var location2 = new Microsoft.Maps.Location(20,-20); var location3 = new Microsoft.Maps.Location(20,20); var location4 = new Microsoft.Maps.Location(60, 20); var location5 = new Microsoft.Maps.Location(60, 60);
// Create a polyline var lineVertices = new Array(location1, location2, location3, location4, location5); var line = new Microsoft.Maps.Polyline(lineVertices,{strokeColor:new Microsoft.Maps.Color(200, 100, 0, 100), strokeThickness:5, strokeDashArray:"5 2"});
Position Class
Represents the position of a user on a map.
Properties
Name Type Description
coords timestamp
Coordinates string
The position as a W3C Coordinates object. The time when the position was determined, in the form of a DOMTimeStamp.
See Also
GeoLocationProvider Class
PositionCircleOptions Object
Contains options for the addAccuracyCircle method of the GeoLocationProvider class.
Properties
Name Type Description
polygonOptions showOnMap
PolygonOptions boolean
The polygon options for the geo location accuracy circle. A boolean indicating whether to display the geo location accuracy circle. The default value is true. If this property is set to false, a geo location
Name
Type
Description
accuracy circle is not drawn and any existing accuracy circles are removed.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() {
function drawCircle(args) { // Draw the accuracy circle using a different color geoLocationProvider.addAccuracyCircle(args.center, 50000, 50000, {polygonOptions:{fillColor:new Microsoft.Maps.Color(100,100,0,100), strokeColor:new Microsoft.Maps.Color(100,100,0,100)}}); }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> </body> </html>
PositionError Class
Represents the error when a user position request does not succeed.
Properties
Name Type Description
code
number
Name
Type
Description
codes may be returned: 0 An error occurred that is not covered by other error codes. 1 The application does not have permission to use the GeoLocation API. 2 The position of the host device could not be determined. 3 The specified timeout was exceeded.
message string
The error message. This message is for the developer and is not intended to be displayed to the end user.
See Also
GeoLocationProvider Class
PositionOptions Object
Contains options for the getCurrentPosition method of the GeoLocationProvider class.
Properties
Name Type Description
enableHighAccuracy
boolean
A boolean indicating whether only a high accuracy result should be retrieved. The default value is false. Setting this property to true may result in a slower response time. The function to call when an error occurs during the user
errorCallback
function
Name
Type
Description
location request. The callback function must accept one argument. The argument object contains two properties, internalError, a PositionError type, and errorCode, a number. Any one of the following errorCode values may be returned: 1 The application origin does not have permission to use the GeoLocation API. 2 The position of the user could not be determined because of a device failure. 3 The time specified in timeout has been exceeded. 4 A request is already in process. 5 The users browser does not support geo location.
maximumAge
number
A number indicating the acceptable age, in milliseconds, of a cached geo location result to return. The default value is 0, which indicates a new (not cached) result will be retrieved. A boolean indicating whether to display the polygon on the map that shows the accuracy of the returned geo location. The default value is true. The function to call when the users location was
showAccuracyCircle
boolean
successCallback
function
Name
Type
Description
successfully retrieved. The callback function must accept one argument. The argument object contains two properties, center, a Location type, and position, a Position type. timeout number The length of time, in milliseconds, to allow for the geo location request to return. By default there is no timeout. A boolean indicating whether to update the map view with the best view of the users location (if the request is successful). The default value is true.
updateMapView
boolean
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
var map;
function GetMap() {
function displayCenter(args) { // Display the user location when the geo location request returns alert("The user's location is " + args.center); }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> </body> </html>
Constructor
Name Definition
Pushpin(location:Location, options?:PushpinOptions)
Description
Pushpin
Methods
Name Definition
getAnchor()
Return Value
Description
getAnchor
Point
Returns the point on the pushpin icon which is anchored to the pushpin location. An anchor of (0,0) is the top left corner of the icon. Returns the pushpin icon. Returns the height of the pushpin, which is the height of the pushpin icon. Returns the location of the pushpin. Returns the text associated with the pushpin.
getIcon getHeight
getIcon()
string number
getHeight()
getLocation
getLocation()
Location
getText
getText()
string
Name
Definition
getTextOffset()
Return Value
Description
getTextOffset
Point
Returns the amount the text is shifted from the pushpin icon. Returns the type of the pushpin. Returns whether the pushpin is visible. A value of false indicates that the pushpin is hidden, although it is still an entity on the map. Returns the width of the pushpin, which is the width of the pushpin icon. Returns the zindex of the pushpin with respect to other items on the map. Sets the location of the pushpin. Sets options for the pushpin. Converts the Pushpin object to a string.
getTypeName getVisible
getTypeName()
string boolean
getVisible()
getWidth
getWidth()
number
getZIndex
getZIndex()
number
setLocation(location:Location)
setOptions(options:PushpinOptions)
toString()
Events
Name
Arguments
Description
click dblclick
eventArgs:MouseEventArgs eventArgs:MouseEventArgs
Occurs when the mouse is used to click the pushpin. Occurs when the mouse is used to double click the pushpin. Occurs when the pushpin is being dragged. Occurs when the pushpin stops being dragged. Occurs when the pushpin starts being dragged. Occurs when the location of the pushpin or any of the pushpins options change. Occurs when the left mouse button is pressed when the mouse is over the pushpin. Occurs when the mouse cursor moves out of the area covered by the pushpin. Occurs when the mouse is over the pushpin. Occurs when the left mouse button is lifted up when the mouse is over the pushpin. Occurs when the right mouse button is used to click the pushpin.
mousedown
eventArgs:MouseEventArgs
mouseout
eventArgs:MouseEventArgs
mouseover mouseup
eventArgs:MouseEventArgs eventArgs:MouseEventArgs
rightclick
eventArgs:MouseEventArgs
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("myMap"), {credentials:"Bing Maps Key"});
// Add a pin to the center of the map var pin = new Microsoft.Maps.Pushpin(center, {draggable: true});
map.entities.push(pin); }
var pinLoc = e.target.getLocation(); alert("The location of the pushpin is now " + pinLoc.latitude + ", " + pinLoc.longitude);
} }
</script> </head> <body onload="GetMap();"> <div id='myMap' style="position:relative; width:400px; height:400px;"></div> <b>Drag the pushpin to a new location.</b> </body> </html>
PushpinOptions Object
Represents the options for a pushpin.
Properties
Name Type Description
anchor
Point
The point on the pushpin icon which is anchored to the pushpin location. An anchor of (0,0) is the top left corner of the icon. The default anchor is the bottom center of the icon. A boolean indicating whether the pushpin can be dragged to a new position with the mouse.
draggable
boolean
Name
Type
Description
icon height
string number
The path of the image to use as the pushpin icon. The height of the pushpin, which is the height of the pushpin icon. The default value is 39. The text associated with the pushpin. The amount the text is shifted from the pushpin icon. The default value is (0,5). The type of the pushpin, as a string. The pushpin DOM (document object model) node created for the pushpin will have the specified typeName. A boolean indicating whether to show or hide the pushpin. The default value is true. A value of false indicates that the pushpin is hidden, although it is still an entity on the map. The width of the pushpin, which is the width of the pushpin icon. The default value is 25. The z-index of the pushpin with respect to other items on the map.
text textOffset
string Point
typeName
string
visible
boolean
width
number
zIndex
number
Example
This example uses the image below, named BluePushpin.png, as the pushpin icon.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("myMap"), {credentials:"Bing Maps Key"});
// Add a pin to the center of the map var pin = new Microsoft.Maps.Pushpin(center, {icon:"BluePushpin.png", height:50, width:50, anchor:new Microsoft.Maps.Point(0,50), draggable: true});
map.entities.push(pin); }
</script> </head>
</body> </html>
TileLayer Class
Represents a tile layer.
Constructor
Name Definition
TileLayer(options:TileLayerOptions)
Description
TileLayer
Methods
Name Definition Return Type Description
getOpacity
getOpacty()
number
Returns the opacity of the tile layer, defined as a double between 0 (not visible) and 1. Returns the tile source of the tile layer. The projection parameter accepts the following values: mercator, enhancedBirdseyeNorthUp, enhancedBirdseyeSouthUp , enhancedBirdseyeEastUp, enhancedBirdseyeWestUp
getTileSourc e
getTileSource(projection:string)
TileSourc e
getZIndex
getZIndex()
number
Name
Definition
Return Type
Description
tile layer with respect to other items on the map. setOptions toString
setOptions(options:TileLayerOptions ) toString()
None string
Sets options for the tile layer. Converts the TileLayer object to a string.
Events
Name Arguments Description
tiledownloadcomplete
None
Occurs when all the tiles of the tile layer have loaded.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:"Bing Maps Key", center:new Microsoft.Maps.Location(48.03,-
try { // Create the tile layer source var tileSource = new Microsoft.Maps.TileSource({uriConstructor: 'http://www.microsoft.com/maps/isdk/ajax/layers/lidar/{quadkey}.png'});
// Construct the layer using the tile source var tilelayer= new Microsoft.Maps.TileLayer({ mercator: tileSource, opacity: .7 });
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> </body> </html>
See Also
Working with Tile Layers
TileLayerOptions Object
Defines the options for a tile layer.
Properties
Name Type Description
animationDisplay
AnimationVisibility
The tile layers visibility during animation. You can use this property to prevent overlays from displaying during animations, which can impact performance. The default value is auto. The tile source for the tile layer. The opacity of the tile layer, defined by a number between 0 (not visible) and 1. A boolean indicating whether to show or hide the tile layer. The default value is true. A value of false indicates that the tile layer is hidden, although it is still an entity on the map. The z-index of the tile layer, with respect to other items on the map.
mercator opacity
TileSource number
visible
boolean
zIndex
number
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:"Bing Maps Key", center:new Microsoft.Maps.Location(48.03,-122.4), zoom:12, mapTypeId: Microsoft.Maps.MapTypeId.road });
try { // Create the tile layer source var tileSource = new Microsoft.Maps.TileSource({uriConstructor: 'http://www.microsoft.com/maps/isdk/ajax/layers/lidar/{quadkey}.png'});
// Construct the layer using the tile source tilelayer= new Microsoft.Maps.TileLayer({ mercator: tileSource, opacity: .7 });
map.entities.push(tilelayer);
function SetOpacity() {
if ((opacityVal > 1) || (opacityVal < 0)) { alert("The opacity value must be between 0 and 1."); } else { tilelayer.setOptions({opacity: opacityVal}); }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <input id="txtOpacity" type="text" value=".1" style="width:25px;"/>
See Also
Working with Tile Layers
TileSource Class
Defines a tile source for a tile layer.
Constructor
Name Definition
TileSource(options:TileSourceOptions)
Description
TileSource
Methods
Name Definition
getHeight()
Return Type
Description
getHeight
Number
Returns the pixel height of each tile in the tile source. Returns a string that constructs tile URLs used to retrieve tiles for the tile layer. Returns the pixel width of each tile in the tile source. Converts the TileSource object to a string.
getUriConstructor
getUriConstructor()
string
getWidth
getWidth()
number
toString
toString()
string
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key", center:new Microsoft.Maps.Location(48.03,-122.4), zoom:12, mapTypeId: Microsoft.Maps.MapTypeId.road });
try { // Create the tile layer source var tileSource = new Microsoft.Maps.TileSource({uriConstructor: 'http://www.microsoft.com/maps/isdk/ajax/layers/lidar/{quadkey}.png'});
// Construct the layer using the tile source var tilelayer= new Microsoft.Maps.TileLayer({ mercator: tileSource, opacity: .7 });
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> </body> </html>
See Also
Working with Tile Layers
TileSourceOptions Object
Defines options for a tile source.
Properties
Name Type Description
height
number
The pixel height of each tile in the tile source. The default value is 256. The specified height needs to be a multiplier of 2 of the current projections tile height for the tiles to be shown. For example, since Mercator tile
Name
Type
Description
source tiles are 256x256, this projection supports tiles that are 64x64, 128x128, 256x256, 512x512, or any combination of these. uriConstructor string The string that constructs the URLs used to retrieve tiles from the tile source. This property is required. The uriConstructor will replace {subdomain} and {quadkey}. width number The pixel width of each tile in the tile source. The default value is 256. The specified width needs to be a multiplier of 2 of the current projections tile width for the tiles to be shown. For example, since Mercator tile source tiles are 256x256, this projection supports tiles that are 64x64, 128x128, 256x256, 512x512, or any combination of these.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key", center:new Microsoft.Maps.Location(48.03,-122.4), zoom:12, mapTypeId: Microsoft.Maps.MapTypeId.road });
try { // Create the tile layer source var tileSource = new Microsoft.Maps.TileSource({uriConstructor: 'http://www.microsoft.com/maps/isdk/ajax/layers/lidar/{quadkey}.png'});
// Construct the layer using the tile source var tilelayer= new Microsoft.Maps.TileLayer({ mercator: tileSource, opacity: .7 });
See Also
Working with Tile Layers
ViewOptions Object
Contains options for the map view.
Properties
Name Type Description
animate
boolean
A boolean that specifies whether to animate map navigation. Note that this option is associated with each setView call and defaults to true if not specified. The bounding rectangle of the map view. If both are specified, bounds takes precedence over center. The location of the center of the map view. If both are specified, bounds takes precedence over center. The amount the center is shifted. This property is ignored if center is not specified. The directional heading of the map. The heading is represented in geometric degrees with 0 or 360 = North, 90 = East, 180 = South, and
bounds
LocationRect
center
Location
centerOffset
Point
heading
number
Name
Type
Description
270 = West. labelOverlay mapTypeId LabelOverlay string A constant indicating how map labels are displayed. The map type of the view. Valid map types are found in the MapTypeId Enumeration topic. The amount of padding to be added to each side of the bounds of the map view. The zoom level of the map view. For information about map scale and resolution with respect to zoom level, see Understanding Scale and Resolution.
padding
number
zoom
number
Remarks
To 'lock' the map in a certain position, disable mouse and keyboard events during the application session. The following code disables mouse events.
// Attach an event handler for a mousemove event. Microsoft.Maps.Events.addHandler(map, "mousemove", cancelEvent);
// When the mouse is used, the cancelEvent function will // // get called. Setting the handled property to true will disable the mousemove event, which disables panning.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
var initialViewBounds = Microsoft.Maps.LocationRect.fromCorners(new Microsoft.Maps.Location(43,-123), new Microsoft.Maps.Location(33,-113)); var options = {credentials:"Bing Maps Key", width: 500, height: 500, bounds: initialViewBounds, mapTypeId:Microsoft.Maps.MapTypeId.aerial, animate: false};
function SetZoom() { // Retrieve the zoom level set by the user - converting it to a number. var zoomLevel = parseInt(document.getElementById("txtZoom").value);
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative;"></div> <input id="txtZoom" type="text" value="1"/> <input type="button" value="Set Zoom" onclick="SetZoom();"/> </body> </html>
Before you can access the types found in the Microsoft.Maps.Directions API, you must first load this module using the loadModule method. Information about loading modules is in the Module Loading Methods topic.
In This Section
BusinessDetails Class BusinessDisambiguationSuggestion Class DirectionsErrorEventArgs Object DirectionsEventArgs Object
DirectionsManager Class DirectionsRenderOptions Object DirectionsRequestOptions Object DirectionsStep Class DirectionsStepEventArgs Object DirectionsStepRenderEventArgs Object DirectionsStepWarning Class Disambiguation Class DistanceUnit Enumeration IconType Enumeration LocationDisambiguationSuggestion Class Maneuver Enumeration ResetDirectionsOptions Object Route Class RouteAvoidance Enumeration RouteLeg Class RouteMode Enumeration RouteOptimization Enumeration RoutePath Class RouteResponseCode Enumeration RouteSelectorEventArgs Object RouteSelectorRenderEventArgs Object RouteSubLeg Class RouteSummary Class RouteSummaryRenderEventArgs Object StepWarningStyle Enumeration TimeType Enumeration TransitLine Class TransitOptions Object Waypoint Class WaypointEventArgs Object WaypointOptions Object WaypointRenderEventArgs Object
BusinessDetails Class
Contains business details for a waypoint.
Properties
Name Type Description
The business name of the waypoint. The Bing Maps entity ID of the business. The phone number of the business. The URL of the business website.
See Also
BusinessDisambiguationSuggestion Class
Contains a possible business result returned from geocoding a specified waypoint address or location.
Properties
Name Type Description
address distance
string number
The address of the business result. The distance of the business result from the originally specified waypoint address or location. The Yellow Pages ID for the business. The index of this suggestion within the business suggestion array. A boolean indicating whether
entityId index
string number
isApproximate
boolean
Name
Type
Description
the result location is approximate. location name phoneNumber photoUrl rooftopLocation website Location string string string Location string The location of the business suggestion. The name of the business. The phone number of the business suggestion. The URL of a photo of the business suggestion. The rooftop location of the business suggestion. The URL of the business results website.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() {
// Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
// Create start and end waypoints var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: "Seattle, WA" }); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: "Microsoft" } );
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Set the id of the div to use to display the directions directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') });
// If the error is a disambiguation error, display the results. if (e.responseCode == Microsoft.Maps.Directions.RouteResponseCode.waypointDisambiguation) { DisplayDisambiguation(); } }
if (disambigResult != null) { results = results + "Address matches for " + waypoints[i].getAddress() + ":\n";
if(disambigResult.businessSuggestions.length != 0) {
var j = 0; for (j=0; j<disambigResult.businessSuggestions.length; j++) { results = results + disambigResult.businessSuggestions[j].name + ", " + disambigResult.businessSuggestions[j].address + "\n"; } } else if (disambigResult.locationSuggestions.length != 0) { var k = 0; for (k=0; k<disambigResult.locationSuggestions.length; k++) { results = results + disambigResult.locationSuggestions[k].suggestion + "\n"; } } else { results = results + disambigResult.headerText + "\n"; } } }
alert(results);
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
See Also
Disambiguation Class
DirectionsErrorEventArgs Object
Contains arguments for directions error events.
Properties
Name Type Description
responseCode message
RouteResponseCode string
The code which identifies the error that occurred. The error message.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
// Create start and end waypoints and add them to the route var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Paris, France"});
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Set directions render options - in this case, specify the div where the itinerary is displayed. directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') });
// Specify a handler for when the directions are calculated and when an error occurs Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', displayMessage ); Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayError );
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
DirectionsEventArgs Object
Contains the arguments for directions events.
Properties
Name
Type
Description
routeSummary
RouteSummary[]
The route summary (or summaries) of the route(s) defined in the route property. The calculated route (or routes, if the route mode is transit).
route
Route[]
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
// Create start and end waypoints and add them to the route var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Bellevue, WA"});
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Set directions options - in this case, calculate a transit route. directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.transit });
// Set directions render options - in this case, specify the div // where the itinerary is displayed.
// Specify a handler for when the directions are calculated Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', displayRouteNumber);
function displayRouteNumber(e)
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
DirectionsManager Class
Contains methods for calculating directions and displaying a route on a map.
Constructor
Name Definition
DirectionsManager(map:Map)
Description
DirectionsManager
Methods
Name Definition
addWaypoint(waypoint:Waypoint, index:number)
Return Value
Description
addWaypoint
None
Adds a waypoint to the route at the given index, if specified. If an index is not specified the
Name
Definition
Return Value
Description
waypoint is added as the last waypoint in the route. To recalculate the route, use calculateDirec tions. The maximum number of walking or driving waypoints is 25. The maximum number of transit waypoints is 2. Up to 10 via points are allowed between two stop waypoints. calculateDirecti ons
calculateDirections()
None
Calculates directions based on request and render options set (setRequestO ptions, setRenderOpti ons) and the waypoints added (addWaypoint) . The directionsUpd ated event fires when the
Name
Definition
Return Value
Description
calculation is complete and the route is displayed on the map. You must call this method after making any changes to the route options or waypoints. clearDisplay
clearDisplay()
None
Clears the directions displayed and removes the route line from the map. This method does not remove waypoints from the route and retains all calculated direction information and option settings. To clear the calculated directions and options, use resetDirection s. Deletes the DirectionsMan ager object and releases any associated resources.
dispose
dispose()
None
Name
Definition
getAllWaypoints()
Return Value
Description
getAllWaypoint s getMap
Waypoint[]
Returns the waypoints for the route. Returns the map object associated with the directions manager. Searches around the specified location for nearby major roads and returns them as an object to the callback function. Returns the route render options. Returns the directions request options. Returns the current calculated route(s). If the route was not successfully calculated, null is returned. Removes the given waypoint or the waypoint identified by the given index
getMap()
Map
None
getRequestOptions()
getRouteResult
getRouteResult()
Route[]
removeWaypoi nt
removeWaypoint(waypoint:Waypoint) removeWaypoints(index:number)
or
None
Name
Definition
Return Value
Description
from the route. Use calculateDirec tions to update the route once a waypoint has been removed. resetDirections
resetDirections(options:ResetDirectio
None
nsOptions)
If no options object is supplied, clears the directions request and render options and removes all waypoints. Matches the specified location to an address and returns the address to the specified callback function. Sets the map view based on the current route index. Sets the specified render options for the route. Sets the specified route calculation options.
reverseGeocod e
None
setMapView
setMapView()
None
None
setRequestOpti ons
setRequestOptions(options:Directions
None
RequestOptions)
Events
Name Arguments Description
afterRouteSelectorRender
RouteSelectorRenderEventArgs
Occurs after the route selector has fully rendered. Occurs after each step in the itinerary has fully rendered. Occurs after the route summary has fully rendered. Occurs after each route waypoint has fully rendered. Occurs just before the route selector renders. Occurs just before each step in the itinerary renders. Occurs just before the route summary renders. Occurs just before each route waypoint renders. Occurs when calculating the directions caused an error. Occurs when the directions calculation was successful and the itinerary and route on the map have been updated.
afterStepRender
DirectionsStepRenderEventArgs
afterSummaryRender
RouteSummaryRenderEventArgs
afterWaypointRender
WaypointRenderEventArgs
beforeRouteSelectorRender
RouteSelectorRenderEventArgs
beforeStepRender
DirectionsStepRenderEventArgs
beforeSummaryRender
RouteSummaryRenderEventArgs
beforeWaypointRender
WaypointRenderEventArgs
directionsError
DirectionsErrorEventArgs
directionsUpdated
DirectionsEventArgs
Name
Arguments
Description
dragDropCompleted
None
Occurs when the drag of a waypoint or route is completed. Occurs when a step in the itinerary is clicked. Occurs when the mouse cursor is over the route selector. Occurs when the mouse cursor is over a directions step. Occurs when the mouse cursor leaves the route selector. Occurs when the mouse cursor leaves a directions step. Occurs when the route selector is clicked. Occurs when a new waypoint is added to the route. Occurs when a waypoint is removed from the route.
itineraryStepClicked
DirectionsStepEventArgs
mouseEnterRouteSelector
RouteSelectorEventArgs
mouseEnterStep
DirectionsStepEventArgs
mouseLeaveRouteSelector
RouteSelectorEventArgs
mouseLeaveStep
DirectionsStepEventArgs
routeSelectorClicked
RouteSelectorEventArgs
waypointAdded
WaypointEventArgs
waypointRemoved
WaypointEventArgs
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
// Create start and end waypoints var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Portland, OR"});
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Set the id of the div to use to display the directions directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') });
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
DirectionsRenderOptions Object
Represents render options for a route.
Properties
Name
Type
Description
autoUpdateMapView
boolean
A boolean indicating whether to automatically set the map view to the best map view of the calculated route. The default value is true. A boolean indicating whether to display the disclaimer about the accuracy of the directions. The default value is false. A boolean indicating whether to display the icons for each direction maneuver. The default value is true. A boolean indicating whether to display direction hints that describe when an direction step was missed. The default value is true. A boolean indicating whether to display direction hints that describe what to look for before you come to the next direction step. The default value is true. A boolean indicating whether to display the route selector control. The default value is true. A boolean indicating whether to display direction warnings. The default value is true.
displayDisclaimer
boolean
displayManeuverIcons
boolean
displayPostItineraryItemHints
boolean
displayPreItineraryItemHints
boolean
displayRouteSelector
boolean
displayStepWarnings
boolean
Name
Type
Description
displayTrafficAvoidanceOption
boolean
A boolean indicating whether to display the control that allows the user to choose to avoid traffic. The default value is true. A boolean indicating whether to display a warning about walking directions. The default value is true. The options that define how to draw the route line on the map, if the RouteMode is driving. The DOM element inside which the directions itinerary will be rendered. The URL of the icon to use for the end waypoint. The URL of the icon to use for intermediate waypoints. The options that define the pushpin to use for each direction step. The options that define how to draw the route line on the map, if the RouteMode is transit. The options that define the pushpin to use for each via point of the route, which are any waypoints other than the start and end waypoints.
displayWalkingWarning
boolean
drivingPolylineOptions
PolylineOptions
itineraryContainer
DOMElement
lastWaypointIcon middleWaypointIcon
string string
stepPushpinOptions
PushpinOptions
transitPolylineOptions
PolylineOptions
viapointPushpinsOptions
PushpinOptions
Name
Type
Description
walkingPolylineOptions
PolylineOptions
The options that define how to draw the route line on the map, if the RouteMode is walking. The options that define the pushpin to use for the route waypoint.
waypointPushpinOptions
PushpinOptions
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
// Create start and end waypoints var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: "Green Lake" } );
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Set the render options directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv'), displayWalkingWarning: false, walkingPolylineOptions:{strokeColor: new Microsoft.Maps.Color(200, 0, 255, 0)} });
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
DirectionsRequestOptions Object
Contains options for the directions to calculate.
Properties
Name Type Description
avoidTraffic
boolean
A boolean indicating whether to return traffic info when calculating the route. The default value is false. The unit to use when displaying direction distances. The default value is based on the specified
distanceUnit
DistanceUnit
Name
Type
Description
culture. maxRoutes number The number of routes to calculate. If the routeMode is driving or walking, only 1 route is supported. If the routeMode is transit, up to 6 routes can be calculated and the default is 3. The features to avoid when calculating the route. The default value is none. A boolean indicating whether the route line on the map can be dragged with the mouse cursor. The default value is true. When a route is dragged, a via point is added to the route. To change the drag behavior of a waypoint, set the draggable property of the waypointPushpinOptions (of the DirectionsRenderOptions). routeIndex number If multiple routes are returned, the index of the route and directions to display. This property only applies to routes where the routeMode is transit, and in this case up to 6 routes are supported. The type of directions to calculate. The default value is driving. When the culture is ja-jp, only the transit route mode is supported, which is the default for that market. The optimization setting for the route calculation. The default value is shortestTime. The extra options for calculating a
routeAvoidance
RouteAvoidance[]
routeDraggable
boolean
routeMode
RouteMode
routeOptimization
RouteOptimization
transitOptions
TransitOptions
Name
Type
Description
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
function directionsModuleLoaded() {
// Create start and end waypoints var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: "Redmond, WA" } );
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
DirectionsStep Class
Represents one direction in a set of route directions.
Properties
Name Type Description
The child direction items for this directions step. The location of the start of the direction. The total distance of the step in the unit specified in the distanceUnit property of the DirectionsRequestOptions. The total time, in seconds, of the direction step. The HTML formatted route instruction associated with the step. The type of the icon associated with this step. A boolean indicating whether the maneuver image is a road
durationInSeconds formattedText
number string
iconType isImageRoadShield
IconType boolean
Name
Type
Description
shield image. maneuver maneuverImageName monetaryCost postIntersectionHints Maneuver string number string[] The maneuver type associated with this step. The name of the maneuver image. The cost of the step. An array of strings, where each string is a hint to help determine when to move to the next direction step. Not all direction steps have hints. An array of strings, where each string is a hint to help determine when you have arrived at this direction step. Not all direction steps have hints. The name of the transit stop where this step originates. The transit line associated with this step. The URL of the image to use for transit direction steps. The ID of the transit stop. The name of the transit line end. An array of strings, where each string is a route warning associated with this step.
preIntersectionHints
string[]
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
// Create start and end waypoints and add them to the route var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Bellevue, WA"});
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Set directions options directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.transit}); directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') });
// Specify a handler for when the directions are calculated Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', displayMessage ); Microsoft.Maps.Events.addHandler(directionsManager, 'itineraryStepClicked', displayStepMessage ); Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayError);
function displayMessage(e) { alert("Click a step in the itinerary to display extra transit information."); }
function displayStepMessage(e) {
if (e.step.iconType == Microsoft.Maps.Directions.IconType.bus ) { alert("The name of the transit agency for this step is: " + e.step.transitLine.agencyName + ". For information about this transit agency and transit
line, go to " + e.step.transitLine.agencyUrl + "."); } else { alert("The step that was clicked is not a transit step."); } }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
DirectionsStepEventArgs Object
Contains arguments for directions step events.
Properties
Name
Type
Description
handled
boolean
A boolean indicating whether the event is handled. Set this property to true to override the default behavior. The location along the route where the direction step occurs. A number indicating the route (if multiple routes were returned) to which the directions step belongs. A number indicating the route leg to which the directions step belongs. The directions step. A number indicating the index of the directions step within the route leg array. A number indicating the directions step number within the route.
location
Location
routeIndex
number
routeLegIndex
number
step stepIndex
DirectionsStep number
stepNumber
number
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
// Create start and end waypoints and add them to the route var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Bellevue, WA"});
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Specify a handler for when the directions are calculated Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', displayMessage ); Microsoft.Maps.Events.addHandler(directionsManager, 'itineraryStepClicked', displayStepMessage ); Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayError);
function displayMessage(e) { alert("Click a step in the itinerary to display extra step information."); }
function displayStepMessage(e) { alert("The directions step that was clicked is step number " + (e.stepIndex + 1) + ", and the location of this step is: " + e.location); }
</script> </head>
<body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
DirectionsStepRenderEventArgs Object
Contains arguments for directions step render events.
Properties
Name Type Description
containerElement
object
The DOM element which contains the directions step. You can use this property to add custom content. A boolean indicating whether the event is handled. This property is only available for the beforeStepRender event. Set this property to true to override the default behavior. A boolean indicating whether the step is the last directions step. A number indicating the index of the route to which this step belongs. A number indicating the index of the route leg to which this step belongs. The directions step. The index of this directions step within the route leg step array.
handled
boolean
lastStep
boolean
routeIndex
number
routeLegIndex
number
step stepIndex
DirectionsStep number
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
// Create start and end waypoints and add them to the route var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"});
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Set directions options directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.transit}); directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') });
// Specify a handler for when the directions are calculated Microsoft.Maps.Events.addHandler(directionsManager, 'afterStepRender', displayStepMessage ); Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayError);
if (e.lastStep) }
alert(message); }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
DirectionsStepWarning Class
Represents a route direction warning, such as a traffic congestion warning.
Properties
Name Type Description
style text
StepWarningStyle string
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
// Create start and end waypoints and add them to the route var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Bellevue, WA"});
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Set directions options directionsManager.setRequestOptions({ avoidTraffic: true }); directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') });
// Specify a handler for when the directions are calculated Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', displayMessage ); Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayError);
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
Disambiguation Class
Contains disambiguation results for a waypoint geocoding request.
Properties
Name
Type
Description
businessSuggestions
BusinessDiambiguationSuggestion[]
The possible business result matches for the originally specified waypoint address or location. A boolean indicating whether there are more result suggestions available. The disambiguation header text. The possible location result matches for the originally specified waypoint address or location.
hasMoreSuggestions
boolean
headerText locationSuggestions
string LocationDiambiguationSuggestion[]
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap()
{ // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
// Create start and end waypoints var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: "Seattle, WA" }); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: "148th Way Bellevue" } );
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Set the id of the div to use to display the directions directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') });
directionsManager.calculateDirections();
// If the error is a disambiguation error, display the results. if (e.responseCode == Microsoft.Maps.Directions.RouteResponseCode.waypointDisambiguation) { DisplayDisambiguation(); } }
if (disambigResult != null) { results = results + "Address matches for " + waypoints[i].getAddress() + ":\n";
if(disambigResult.businessSuggestions.length != 0)
{ var j = 0; for (j=0; j<disambigResult.businessSuggestions.length; j++) { results = results + disambigResult.businessSuggestions[j].name + ", " + disambigResult.businessSuggestions[j].address + "\n"; } } else if (disambigResult.locationSuggestions.length != 0) { var k = 0; for (k=0; k<disambigResult.locationSuggestions.length; k++) { results = results + disambigResult.locationSuggestions[k].suggestion + "\n"; } } else { results = results + disambigResult.headerText + "\n"; } } }
alert(results);
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body>
</html>
See Also
Waypoint Class (AJAX)
Constants
Code Name Description
0 1
kilometers miles
Kilometers are used to measure route distances. Miles are used to measure route distances.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
// Create start and end waypoints var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: "Redmond, WA" } );
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
IconType Enumeration
Contains route icon types.
Constants
Type Code
Name
Description
0 1 2 3 4 5 6 7
There is no route icon. The icon is some other type of icon. The icon is a car icon. The icon is a ferry icon. The icon is a walking icon. The icon is a bus, or transit, icon The icon is a train icon. The icon is an airline icon.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"});
// Create start and end waypoints and add them to the route var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Bellevue, WA"});
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Set directions options directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.transit}); directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') });
// Specify a handler for when the directions are calculated Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', displayMessage ); Microsoft.Maps.Events.addHandler(directionsManager, 'itineraryStepClicked', displayStepMessage ); Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayError);
function displayMessage(e) { alert("Click a step in the itinerary to display extra transit information."); }
function displayStepMessage(e) {
if (e.step.iconType == Microsoft.Maps.Directions.IconType.bus ) { alert("The name of the transit agency for this step is: " + e.step.transitLine.agencyName + ". For information about this transit agency and transit
line, go to " + e.step.transitLine.agencyUrl + "."); } else { alert("The step that was clicked is not a transit step."); } }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
LocationDisambiguationSuggestion Class
Contains a possible result returned from geocoding a specified waypoint address or location.
Properties
Name Type Description
The HTML formatted address suggestion. The location of the suggestion. The rooftop location of the suggestion. The address suggestion.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
// Create start and end waypoints var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: "Seattle, WA" }); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: "148th Way Bellevue" } );
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Set the id of the div to use to display the directions directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') });
// If the error is a disambiguation error, display the results. if (e.responseCode == Microsoft.Maps.Directions.RouteResponseCode.waypointDisambiguation) { DisplayDisambiguation(); } }
if (disambigResult != null) { results = results + "Address matches for " + waypoints[i].getAddress() + ":\n";
if(disambigResult.businessSuggestions.length != 0) { var j = 0; for (j=0; j<disambigResult.businessSuggestions.length; j++) { results = results + disambigResult.businessSuggestions[j].name + ", " + disambigResult.businessSuggestions[j].address + "\n"; } } else if (disambigResult.locationSuggestions.length != 0) { var k = 0; for (k=0; k<disambigResult.locationSuggestions.length; k++) { results = results + disambigResult.locationSuggestions[k].suggestion + "\n"; } } else { results = results + disambigResult.headerText + "\n"; } } }
alert(results);
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
See Also
Disambiguation Class
Maneuver Enumeration
Contains route maneuver types.
Constants
Type Code Name Description
0 1 2 3
The step is not a maneuver. The maneuver is unknown. Depart from the start waypoint. Depart from an intermediate stop point going in a different direction and on a different road than which you arrived. Depart from an intermediate stop point going back in the same direction and on the same road on which you
departIntermediateStopReturning
Type Code
Name
Description
arrived. 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 arriveFinish arriveIntermediateStop turnLeft turnRight turnBack uTurn turnToStayLeft turnToStayRight bearLeft bearRight keepToStayLeft keepToStayRight keepToStayStraight keepLeft keepRight keepStraight take Arrive at the end waypoint. Arrive at an intermediate stop point. Turn left. Turn right. Turn back sharply. Make a u-turn to go in the opposite direction. Turn left to stay on the same road. Turn right to stay on the same road. Bear left. Bear right. Keep left to stay on the same road. Keep right to stay on the same road. Keep straight to stay on the same road. Keep left onto a different road. Keep right onto a different road. Keep straight onto a different road. Take the road. This instruction is used when you are entering or exiting a ferry. Take the ramp to the left.
22
takeRampLeft
Type Code
Name
Description
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
takeRampRight takeRampStraight keepOnRampLeft keepOnRampRight keepOnRampStraight merge continueRoute roadNameChange enterRoundabout exitRoundabout turnRightThenTurnRight turnRightThenTurnLeft turnRightThenBearRight turnRightThenBearLeft turnLeftThenTurnLeft turnLeftThenTurnRight turnLeftThenBearLeft turnLeftThenBearRight bearRightThenTurnRight bearRightThenTurnLeft bearRightThenBearRight
Take the ramp to the right. Stay straight to take the ramp. Keep left and continue onto ramp. Keep right and continue onto ramp. Keep straight and continue onto ramp. Merge onto highway. Continue on the current road. The road name changed. Enter a roundabout. Exit a roundabout. Turn right and then turn right. Turn right and then turn left. Turn right and then bear right. Turn right and then bear left. Turn left and then turn left. Turn left and then turn right. Turn left and then bear left. Turn left and then bear right. Bear right and then turn right. Bear right and then turn left. Bear right and then bear
Type Code
Name
Description
right. 44 45 46 47 48 49 bearRightThenBearLeft bearLeftThenTurnLeft bearLeftThenTurnRight bearLeftThenBearRight bearLeftThenBearLeft rampThenHighwayRight Bear right and then bear left. Bear left and then turn left. Bear left and then turn right. Bear left and then bear right. Bear left and then bear left. Take left ramp onto highway. This is part of a combined instruction. Take right ramp onto highway. This is part of a combined instruction. Stay straight to take the ramp onto the highway. This is part of a combined instruction. Enter and exit a roundabout. Bear instruction and then a merge instruction. Turn instruction and then a merge instruction. Bear instruction and then a keep instruction. Transfer between public transit lines at a transit stop. Wait at a transit stop. Take transit. The maneuver is a walking instruction. Get on a public transit line
50
rampThenHighwayLeft
51
rampToHighwayStraight
52 53 54 55 56 57 58 59 60
Type Code
Name
Description
at a transit stop. 61 transitArrive Get off a public transit line at a transit stop.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
// Create start and end waypoints and add them to the route var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Bellevue, WA"});
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Set directions options directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.transit}); directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') });
// Specify a handler for when the directions are calculated Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', displayMessage ); Microsoft.Maps.Events.addHandler(directionsManager, 'itineraryStepClicked', displayStepMessage ); Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayError);
function displayMessage(e) { alert("Click a transit step in the itinerary to display extra maneuver information."); }
function displayStepMessage(e) {
if (e.step.maneuver == Microsoft.Maps.Directions.Maneuver.transfer ) { alert("This step is transit transfer instruction."); } else if (e.step.maneuver == Microsoft.Maps.Directions.Maneuver.takeTransit ) { alert("This step is a transit instruction."); } else if (e.step.maneuver == Microsoft.Maps.Directions.Maneuver.transitDepart ) { alert("This step is a transit departure instruction."); } else if (e.step.maneuver == Microsoft.Maps.Directions.Maneuver.transitArrive ) { alert("This step is a transit arrival instruction."); }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
ResetDirectionsOptions Object
Contains options for the resetDirections method of the DirectionsManager Class.
Properties
Name Type Description
removeAllWaypoints
boolean
A boolean indicating whether to remove all of the waypoints of the route. The default value is false. A boolean indicating whether to reset all of the render options set for the route. The default value is false. A boolean indicating whether
resetRenderOptions
boolean
resetRequestOptions
boolean
Name
Type
Description
to reset all of the request options set for the route. The default value is false.
Properties
Name Type Description
routeLegs
RouteLeg[]
The legs of the route. Each route leg represents the route between two waypoints.
RouteAvoidance Enumeration
Defines features to avoid when calculating the route.
Constants
Code Name Description
none
Calculate the best route using any travel option available. Reduce the use of limited access highways when calculating the route. Reduce the use of roads with tolls when calculating the route. Avoid using limited access
minimizeLimitedAccessHighway
minimizeToll
avoidLimitedAccessHighway
Code
Name
Description
highways when calculating the route. 8 16 avoidToll avoidExpressTrain Avoid using roads with tolls when calculating the route. Avoid using express trains when calculating the route. This option only affects routes with a transit RouteMode that have the culture set to ja-jp. Avoid using airlines when calculating the route. This option only affects routes with a transit RouteMode that have the culture set to ja-jp. Avoid using bullet trains when calculating the route. This option only affects routes with a transit RouteMode that have the culture set to ja-jp.
32
avoidAirline
64
avoidBulletTrain
Properties
Name Type Description
endTime
DateTime
The end time of the route leg. This property only applies when the routeMode of the DirectionsRequestOptions is set to transit.
Name
Type
Description
The location of the last waypoint of this leg. The directions steps associated with this route leg. The index of the route to which this route leg belongs. The start time of the route leg. This property only applies when the routeMode of the DirectionsRequestOptions is set to transit. The location of the first waypoint of this route leg. The sub legs of this route leg. A sub leg of a route is the part of the route between a stop point and a via point or between two via points. The summary which describes this route leg.
startWaypointLocation subLegs
Location RouteSubLeg[]
summary
RouteSummary
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
// Create start and end waypoints and add them to the route var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Bellevue, WA"});
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Specify a handler for when the directions are calculated Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', displayMessage); Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayError);
directionsManager.calculateDirections();
function displayMessage(e) { alert("The calculated route has " + e.route[0].routeLegs[0].itineraryItems.length + " direction steps.");
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> </body> </html>
RouteMode Enumeration
Defines the type of route to calculate.
Constants
Name Description
driving transit
Name
Description
walking
Constants
Code Name Description
0 1 3
Calculate a route the shortest time. Calculate a route with the shortest distance. Minimize the cost when calculating directions. This option only affects routes with a transit RouteMode that have the culture set to ja-jp. Minimize transit transfers when calculating directions. This option only affects routes with a transit RouteMode that have the culture set to ja-jp. Minimize the amount of walking when calculating directions. This option only affects routes with a transit RouteMode that have the culture set to ja-jp.
minimizeTransfers
minimizeWalking
Use the setRenderOptions method of the DirectionsManager Class to set DirectionsRenderOptions to customize the look of the route line on the map.
Properties
Name Type Description
decodedLatitudes
double[]
An array of latitudes, where each latitude is the latitude for one of the locations that define the route line. An array of longitudes, where each is the longitude value for one of the locations that define the route line. An array of regions that define, depending on the zoom level, how the route line should be rendered.
decodedLongitudes
double[]
decodedRegions
Object[]
RouteResponseCode Enumeration
Contains response codes for a route calculation request.
Constants
Response Code Name Description
0 1 2
The route was successfully calculated. An unknown error has occurred. A nearby road cannot be found for one or more of the route waypoints. The distance between two
tooFar
Response Code
Name
Description
route waypoints, or the total length of the route exceeds the limit of the route mode. Modify the waypoint locations so that they are closer together. 4 noSolution A route cannot be calculated for the specified waypoints. For example, this code is returned when a route between Seattle, WA and Honolulu, HI is requested. There is no route data for the specified waypoints. There are no transit options available for the specified time. The transit stops are so close that walking is always a better option. The transit stops are so close that walking is a better option. There is no transit data available for the route or for one or more of the specified waypoints, or the waypoints are in different transit areas that do not overlap. The directions calculation request has timed out. One or more waypoints need to be disambiguated. One or more waypoints do not have an address or location specified.
5 7
dataSourceNotFound noAvailableTransitTrip
transitStopsTooClose
walkingBestAlternative
10
outOfTransitBounds
11 12 13
Response Code
Name
Description
14
exceedMaxWaypointLimit
The maximum number of waypoints, which is 25, has been exceeded. At least two waypoints are required to calculate a route. The first or last waypoint is a via point, which is not allowed. The search service failed to return results. The credentials passed to the Directions module are invalid.
15 16
atleastTwoWaypointRequired firstOrLastStoppointIsVia
17 18
searchServiceFailed invalidCredentials
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
// Create start and end waypoints var waypoint1 = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var waypoint2 = new Microsoft.Maps.Directions.Waypoint({ address: "Redmond, WA"}); var waypoint3 = new Microsoft.Maps.Directions.Waypoint({ address: "Bellevue, WA", isViapoint: true } );
// Set the id of the div to use to display the directions directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') });
directionsManager.calculateDirections();
// If the error is a viapoint error, display an error if (e.responseCode == Microsoft.Maps.Directions.RouteResponseCode.firstOrLastStoppointIsVia ) { alert("Please remove the 'isViapoint' option from your first or last stop point."); } }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
RouteSelectorEventArgs Object
Contains arguments for route selector events.
Properties
Name
Type
Description
handled
boolean
A boolean indicating whether the event is handled. Set this property to true to override the default behavior. A number indicating the index of the route that was selected.
routeIndex
number
RouteSelectorRenderEventArgs Object
Contains arguments for route selector render events.
Properties
Name Type Description
containerElement
object
The DOM element which contains the route selector. You can use this property to add custom content. A boolean indicating whether the event is handled. This property is only available for the beforeRouteSelectorRender event. Set this property to true to override the default behavior. A number indicating the index of the selected route. The route leg of the selected route.
handled
boolean
routeIndex routeLeg
number RouteLeg
RouteSubLeg Class
Represents a route sub leg. A route sub leg is the part of the route between a stop point and a via point or between two via points. One or more sub legs make up a route leg.
Properties
Name Type Description
The location of the last waypoint of the sub leg. The location of the first waypoint of the sub leg. The description of the last waypoint of the sub leg. The properties that define the route line of this sub leg on the map. The description of the first waypoint of the sub leg. The summary of this route sub leg.
startDescription summary
string RouteSummary
Properties
Name Type Description
distance
double
The total travel distance of the route, specified in the units set in the distanceUnit property of the DirectionsRequestOptions. The cost of the route. This property is only returned if the routeMode of the DirectionsRequestOptions is set to transit and the map culture is set to ja-jp. The location of the northeast corner of bounding box that defines the
monetaryCost
double
northEast
Location
Name
Type
Description
best map view of the route. southWest Location The location of the southwest corner of bounding box that defines the best map view of the route. The total travel time, in seconds, for the route. The total travel time, in seconds, taking into account traffic delays, for the route. This property is 0 if the avoidTraffic property of the DirectionsRequestOptions is set to false.
time timeWithTraffic
number number
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"});
// Create start and end waypoints and add them to the route var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Bellevue, WA"});
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Set directions render options - in this case, specify the div where the itinerary is displayed. directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') });
// Specify a handler for when the directions are calculated Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', displayDistanceAndTime );
function displayDistanceAndTime(e) { alert("Total Distance: " + e.routeSummary[0].distance + " miles\n" + "Total Time: " + e.routeSummary[0].time/60 + " minutes" );
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
RouteSummaryRenderEventArgs Object
Contains arguments for route summary render events.
Properties
Name Type Description
containerElement
object
The DOM element which contains the summary. You can use this property to add custom content. A boolean indicating whether the event is handled. This property is only available for the beforeSummaryRender event. Set this property to true to
handled
boolean
Name
Type
Description
override the default behavior. routeLegIndex number A number indicating the index of the route leg which this summary describes. The summary that was rendered.
summary
RouteSummary
StepWarningStyle Enumeration
Contains types of route direction warnings.
Constants
Code Name Description
0 1
info minor
The warning is just information about the route direction. The warning is a minor warning, and may affect the route direction. The warning is a moderate warning and is likely to affect the route direction. The warning is a major warning, and is highly likely to affect the route direction. The warning indicates a congestion zone is being entered. The warning indicates a congestion zone is being exited.
moderate
major
ccZoneEnter
ccZoneExit
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
// Create start and end waypoints and add them to the route
var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Bellevue, WA"});
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Set directions options directionsManager.setRequestOptions({ avoidTraffic: true }); directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') });
// Specify a handler for when the directions are calculated Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', displayMessage ); Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayError);
var i = 0; for (i=0; i < e.route[0].routeLegs[j].itineraryItems.length; i++) { if (e.route[0].routeLegs[j].itineraryItems[i].warnings.length != 0 ) { warningCount = warningCount + e.route[0].routeLegs[j].itineraryItems[i].warnings.length;
for (k=0; k< e.route[0].routeLegs[j].itineraryItems[i].warnings.length; k++) { if (e.route[0].routeLegs[j].itineraryItems[i].warnings[k].style == Microsoft.Maps.Directions.StepWarningStyle.major) { alert("Alert! There is a major warning in this route."); } } } } }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
TimeType Enumeration
Defines the transit time type.
Constants
Name Description
The time specified is an arrival time. The time specified is a departure time. The time specified is the last available time. This time type is only returned for routes with a transit RouteMode that have the culture set to ja-jp.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
// Create start and end waypoints and add them to the route var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Bellevue, WA"});
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Set arrival time to be 4 hours from now var timeToDepart = new Date(); timeToDepart.setTime(timeToDepart.getTime() + 14400000);
// Set directions options directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.transit, transitOptions:{ transitTime: timeToDepart, timeType: Microsoft.Maps.Directions.TimeType.arrival } }); directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') });
// Specify a handler for when the directions are calculated Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayError);
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
See Also
TransitOptions Object
TransitLine Class
Contains information about a transit line.
Properties
Name Type Description
The short name for the transit line. The ID of the agency that owns the transit line. The name of the agency that owns the transit line. The URL of the website of the agency that owns the transit line. The color to use when rendering this transit line on the map. The color to use when rendering text associated with this transit line. Information about the provider of this transit line data. The full name of this transit line.
lineColor
Color
lineTextColor
Color
providerInfo verboseName
string string
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
// Create start and end waypoints and add them to the route var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Bellevue, WA"});
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Set directions options directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.transit}); directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') });
// Specify a handler for when the directions are calculated Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', displayMessage ); Microsoft.Maps.Events.addHandler(directionsManager, 'itineraryStepClicked', displayStepMessage ); Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayError);
function displayMessage(e) { alert("Click a step in the itinerary to display extra transit information.");
function displayStepMessage(e) {
if (e.step.iconType == Microsoft.Maps.Directions.IconType.bus ) { alert("The name of the transit agency for this step is: " + e.step.transitLine.agencyName + ". For information about this transit agency and transit
line, go to " + e.step.transitLine.agencyUrl + "."); } else { alert("The step that was clicked is not a transit step."); } }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
TransitOptions Object
Contains extra options for transit routes.
Properties
Name
Type
Description
timeType
TimeType
The type of the time specified in transitTime. The default value is departure. The transit time to use when calculating the route. If this property is set to null, the current time is used.
transitTime
Date
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
// Create start and end waypoints and add them to the route var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Bellevue, WA"});
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Set departure time to be 4 hours from now var timeToDepart = new Date(); timeToDepart.setTime(timeToDepart.getTime() + 14400000);
// Set directions options directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.transit, transitOptions:{ transitTime: timeToDepart } }); directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') });
// Specify a handler for when the directions are calculated Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayError);
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
Constructor
Name Definition
Waypoint(options:WaypointOptions)
Description
Waypoint
Methods
Name Definition
clear()
Return Value
Description
clear
None
Name
Definition
Return Value
Description
None
Releases any resources associated with the waypoint. Returns the address associated with the waypoint.
getAddress
getAddress()
string
getBusinessDetails
getBusinessDetails()
BusinessDetail Returns the s business details associated with the waypoint. Disambiguatio n Returns the result of the waypoint geocoding disambiguatio n. Returns the location of the waypoint. Returns the custom pushpin associated with this waypoint, if one has been specified. Returns the short address
getDisambiguationRes ult
getDisambiguationResult()
getLocation
getLocation()
Location
getPushpin
getPushpin()
Pushpin
getShortAddress
getShortAddress()
string
Name
Definition
Return Value
Description
boolean
Returns a boolean indicating whether the waypoint location is the exact location. Returns a boolean value indicating whether the waypoint is a via point. A via point is a location that your route is guaranteed to pass through. There can be multiple via points between two stop points. Sets options for the waypoint. For these options to take effect, you must recalculate the route.
isViapoint
isViapoint()
boolean
setOptions
setOptions(options:WaypointOptio
None
ns)
Events
Name
Arguments
Description
changed
WaypointEventArgs
Occurs when the any properties of the waypoint change or are updated. Occurs when a geocoding request for the waypoints address is made. Occurs when a reverse geocoding request for the waypoints location is made. This happens when no address is provided for the waypoint, or if the waypoint is dragged (in which case its location is changed).
geocoded
WaypointEventArgs
reverseGeocoded
WaypointEventArgs
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
// Create start and end waypoints var startWaypoint = new Microsoft.Maps.Directions.Waypoint({address:"Seattle, WA"}); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: "Microsoft" } );
directionsManager.addWaypoint(startWaypoint); directionsManager.addWaypoint(endWaypoint);
// Set the id of the div to use to display the directions directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') });
// If the error is a disambiguation error, display the results. if (e.responseCode == Microsoft.Maps.Directions.RouteResponseCode.waypointDisambiguation) { SelectFirstDisambiguationResult(); }
if (disambigResult != null) { // Reset the address to the first business or location suggestion var firstAddress = disambigResult.businessSuggestions.length > 0 ? disambigResult.businessSuggestions[0].address : disambigResult.locationSuggestions[0].suggestion; waypoints[i].setOptions({ address: firstAddress });
// Set the recalculate flag since the waypoint address was changed recalculate = true; } }
if (recalculate) { directionsManager.calculateDirections(); } }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
WaypointEventArgs Object
Contains the arguments for route waypoint events.
Properties
Name Type Description
waypoint
Waypoint
WaypointOptions Object
Contains waypoint options.
Properties
Name Type Description
address
string
The address string, business name, or search string of the waypoint. For example, the following strings are valid for this parameter: Seattle, Microsoft, pizza, or pizza Seattle. Either the address or location property must be specified. The business details of the waypoint, if it is a business. A boolean indicating whether the waypoint location is the exact location. The default value is false. A boolean indicating whether the waypoint is a via point. A via point is a point along the route that is not a stop point. Set this property to true if you just want the route to pass through this location. The default value is false. The location of the waypoint. Either the address or location
businessDetails exactLocation
BusinessDetails boolean
isViapoint
boolean
location
Location
Name
Type
Description
property must be specified. pushpin Pushpin The custom pushpin to use to represent this waypoint. This property overrides any pushpin options that apply to this waypoint that have been set in the DirectionsRenderOptions Object. The short address of the waypoint.
shortAddress
string
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
// Create start and end waypoints var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ location: new Microsoft.Maps.Location(47.5, -121.9) }); var viaWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: "1 Microsoft Way, Redmond, WA" , isViapoint: true }); var endWaypoint = new Microsoft.Maps.Directions.Waypoint({ address:"Space Needle" } );
// Set the id of the div to use to display the directions directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('itineraryDiv') });
// Specify a handler for when an error and success occurs Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayError);
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div> <div id='itineraryDiv' style="position:relative; width:400px;"></div> </body> </html>
WaypointRenderEventArgs Object
Contains arguments for waypoint render events.
Properties
Name Type Description
containerElement
object
The DOM element which contains the waypoint. You can use this property to add custom content. A boolean indicating whether the event is handled. This property is only available for the beforeWaypointRender event. Set this property to true to override the default behavior. The waypoint for which the event occurred.
handled
boolean
waypoint
Waypoint
Microsoft.Maps.Overlays.Style Reference
This section contains reference documentation for the Microsoft.Maps.Overlays.Style module, which allows you to access Bing Maps overlay styles.
Before you can access Microsoft.Maps.Overlays.Style styles, you must first load this module using the loadModule method. Information about loading modules is in the Module Loading Methods topic.
<script type="text/javascript">
function GetMap() {
var options = {credentials: "Bing Maps Key", center: new Microsoft.Maps.Location(47.5, -122.3), zoom: 9, customizeOverlays: true }
</script> </head> <body> <div id='mapDiv' style="position:relative; width:600px; height:600px;"></div> </body> </html>
Before you can access the types found in the Microsoft.Maps.Traffic API, you must first load this module using the loadModule method. Information about loading modules is in the Module Loading Methods topic.
In This Section
TrafficLayer Class
TrafficLayer Class
Represents a traffic layer on the map.
Constructor
Name Definition
TrafficLayer(map:Map)
Description
TrafficLayer
Methods
Name Definition
getTileLayer()
Return Value
Description
Returns the traffic layer. Hides the traffic layer. Displays the traffic layer.
hide() show()
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() {
map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials: "Bing Maps Key", center: new Microsoft.Maps.Location(47.5, -122.3), zoom: 9 });
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:600px; height:600px;"></div> </body> </html>
Before you can access the types found in the Microsoft.Maps.VenueMaps API, you must first load this module using the loadModule method. Information about loading modules is in the Module Loading Methods topic.
In This Section
Floor Class Footprint Class Metadata Class NearbyVenue Class NearbyVenueOptions Object Polygon Class Primitive Class
Floor Class
Represents one floor map of a venue map.
Properties
Name Type Description
name primitives
string Primitive[]
The name of the floor. An array of Primitive objects that represent the points of interest (for example, stores) on this venue floor. An array of doubles indicating the minimum and maximum zoom levels where imagery is available for this venue map floor.
zoomRange
double[]
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"});
function venuemapsModuleLoaded() {
DisplayVenueFloorInfo(venue);
function ShowError() { // Show an error alert("An error occurred trying to create the venue map.");
function DisplayVenueFloorInfo(venue) {
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:500px; height:500px;"></div> </body> </html>
Footprint Class
Represents the footprint of the venue map.
Properties
Name Type Description
polygons zoomRange
Polygon[] double[]
The shapes that make up the footprint of this venue. An array of doubles indicating the minimum and maximum zoom levels where imagery is available for this venue map.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:"Bing Maps Key"});
function venuemapsModuleLoaded() { // Create the venue map var vmaps = new Microsoft.Maps.VenueMaps.VenueMapFactory(map); vmaps.create({venueMapId: 'bingmapsteam-bellevuesquare', success:ShowVenue, error:ShowError});
DisplayVenueInfo(venue);
function ShowError() { // Show an error alert("An error occurred trying to create the venue map.");
function DisplayVenueInfo(venue) {
var venueinfo = "Venue: " + venue.name +"\n" + "Venue Map ID: " + venue.id + "\n" + "Venue Map Type: " + venue.type + "\n" + "Default Floor: " + venue.defaultFloor + "\n" + "Detail Level Range for Default Floor: " + venue.footprint.zoomRange + "\n";
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:500px; height:500px;"></div> </body> </html>
Metadata Class
Contains information about a venue map.
Properties
Name Type Description
The latitude of the center location of the venue map. The longitude of the center location of the venue map. The ID of the default floor of the venue map. A string used in the floor bar of the venue map. An array containing the floors of the venue map. The footprint of the venue
Name
Type
Description
map. MapId MapType Name YpId string string string string The unique ID of the venue map. A string describing the venue map type (for example, mall). The name of the venue map. The Yellow Pages ID of the venue.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map and set the view to a specific location map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key", center: new Microsoft.Maps.Location(47.6,-122.3), zoom:11});
function venuemapsModuleLoaded() { // Create the venue map var vmaps = new Microsoft.Maps.VenueMaps.VenueMapFactory(map);
// Search for nearby venues vmaps.getNearbyVenues({map: map, location: map.getCenter(), radius:10000, callback:DisplayNearbyVenueCount});
function DisplayNearbyVenueCount(venues) { var displayResults = "Nearby venues with available venue maps:\n";
for (var i=0; i<venues.length; i++) { displayResults = displayResults + venues[i].metadata.Name + "\t" + venues[i].distance/1000 + " km\n";
alert(displayResults); }
</script>
</head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:500px; height:500px;"></div> </body> </html>
NearbyVenue Class
Defines a nearby venue map.
Properties
Name Type Description
distance metadata
double Metadata
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap()
{ // Initialize the map and set the view to a specific location map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key", center: new Microsoft.Maps.Location(47.6,-122.3), zoom:11});
function venuemapsModuleLoaded() { // Create the venue map var vmaps = new Microsoft.Maps.VenueMaps.VenueMapFactory(map);
// Search for nearby venues vmaps.getNearbyVenues({map: map, location: map.getCenter(), radius:10000, callback:DisplayNearbyVenueCount});
function DisplayNearbyVenueCount(venues) { var displayResults = "Nearby venues with available venue maps:\n";
for (var i=0; i<venues.length; i++) { displayResults = displayResults + venues[i].metadata.Name + "\t" + venues[i].distance/1000 + " km\n";
alert(displayResults); }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:500px; height:500px;"></div> </body> </html>
NearbyVenueOptions Object
Contains search options for retrieving nearby venue maps.
Properties
Name Type Description
callback
function
The function to call when the search is completed. The function must accept an array of VenueMap objects. The center of the circle in which to search for nearby venue maps. The base map. The radius, in meters, of the circle in which to search for nearby venue maps.
location
Location
map radius
Map double
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script type="text/javascript">
function GetMap() { // Initialize the map and set the view to a specific location map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key", center: new Microsoft.Maps.Location(47.6,-122.3), zoom:11});
function venuemapsModuleLoaded() { // Create the venue map var vmaps = new Microsoft.Maps.VenueMaps.VenueMapFactory(map);
// Search for nearby venues vmaps.getNearbyVenues({map: map, location: map.getCenter(), radius:10000, callback:DisplayNearbyVenueCount});
function DisplayNearbyVenueCount(venues) { alert("There are " + venues.length + " venue maps nearby."); }
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:500px; height:500px;"></div> </body> </html>
Properties
Name Type Description
The rectangle that defines the bounding box for the polygon. The center of the polygon. The locations that define the vertices of the polygon.
Primitive Class
Represents a venue map primitive, which represents a venue map entity.
Properties
Name Type Description
bounds
LocationRect
The rectangle that defines the bounding box for the primitive. The Yellow Pages ID for the entity. The Yellow Pages business category ID for the entity. The Yellow Pages business category name for the entity. The location of the center of the primitive. The floor to which this primitive belongs. The unique ID of the entity. An array of locations that represent the vertices of the primitive. The name of the entity.
name
string
Methods
Name Definition
highlight()
Return Type
Description
highlight unhighlight
None None
unhighlight()
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"});
function venuemapsModuleLoaded() {
function DisplayVenueEntity(e) { alert("The name of the store that was clicked is " + e.name + ".");
</script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:500px; height:500px;"></div> </body> </html>
VenueMap Class
Represents a venue map. An example of a venue map is a mall.
Properties
Name Type Description
The full address of the venue. The best map view of the venue map. The Yellow Pages ID for the venue map. The location of the center of the venue map. The floor that is displayed if no floor is specified. The header for floors for this venue map. For example, for a mall the floor header would be Level. An array, where each element represents a floor of the venue. The shapes that make up the venue map. The unique venue map ID. The name of the venue represented by the venue map. The phone number for the venue represented by the venue map. The venue map type, such as Mall.
floors
Floor[]
footprint id name
phoneNumber
string
type
string
Methods
Name Definition
dispose()
Return Type
Description
dispose
None
Disposes the venue map object. Returns the venue floor map that is currently displayed. Hides the venue map. Displays the specified floor map for the venue map identified by the given ID. Displays the venue map.
getActiveFloor
getActiveFloor()
string
hide setActiveFloor
hide()
None None
setActiveFloor(venueMapId:string, floor:string)
show
show()
None
Events
Name Arguments Description
click close
eventArgs:Primitive None
Occurs when the mouse is used to click the venue map. Occurs when the close button on the venue map is clicked. Occurs when the detailed map of the venue is clicked. Occurs when the mouse cursor moves out of the area covered by the venue map. Occurs when the mouse
footprintclick mouseout
eventArgs:Primitive eventArgs:Primitive
mouseover
eventArgs:Primitive
Name
Arguments
Description
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"});
function venuemapsModuleLoaded() {
<div id='mapDiv' style="position:relative; width:500px; height:500px;"></div> <input type="button" value="Show Venue Map" onclick="ShowVenue()"/><input type="button" value="Hide Venue Map" onclick="HideVenue()"/> </body> </html>
VenueMapCreationOptions Object
Contains options for creating a venue map.
Properties
Name Type Description
error
function
The function to call if the venue map was not successfully created. The function must accept two parameters: an integer which is an error code and an object that contains the arguments passed to the create method of the VenueMapFactory. The error codes are: 1 The metadata needed to create the venue map was not found because of a 404 or other web exception, or because the metadata was found but was empty. 2 The venue map metadata is invalid. 3 A timeout has occurred trying to retrieve the venue map metadata.
success
function
The function to call if the venue map was successfully created. The function must accept two parameters: a VenueMap and an object that contains the arguments passed to the create
Name
Type
Description
method of the VenueMapFactory. venueMapId string A string that identifies the venue map to display.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), credentials:"Bing Maps Key"});
function venuemapsModuleLoaded() {
// Create the venue map var vmaps = new Microsoft.Maps.VenueMaps.VenueMapFactory(map); vmaps.create({venueMapId: 'bingmapsteam-bellevuesquare', success:ShowVenue, error:ShowError});
function ShowError() { // Show an error alert("An error occurred trying to create the venue map.");
} </script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:500px; height:500px;"></div> </body> </html>
VenueMapFactory Class
Contains methods for creating a venue map.
Constructor
Name
Definition
VenueMapFactory(map:Map)
Description
VenueMapFactory
Methods
Name Definition Retur n Type Description
create
create(options:VenueMapCreationOptions)
None Creates a venue map. If the venue map is created successfully, a VenueMap is returned to the function specified in the success property of the VenueMapCreationOpti ons. You can display a venue map using the show method of the VenueMap Class.
getNearbyVen ues
getNearbyVenues(options:NearbyVenueMap
Options)
None Searches for venue maps within a specified distance. The callback function must accept a NearbyVenue array.
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function GetMap() { // Initialize the map map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:"Bing Maps Key"}); Microsoft.Maps.loadModule('Microsoft.Maps.VenueMaps', { callback: venuemapsModuleLoaded });
function venuemapsModuleLoaded() { // Create the venue map var vmaps = new Microsoft.Maps.VenueMaps.VenueMapFactory(map); vmaps.create({venueMapId: 'bingmapsteam-bellevuesquare', success:DisplayInfobox}); }
var venueinfobox = new Microsoft.Maps.Infobox(mapCenter, {title: venue.name, showPointer: false, showCloseButton:false, height: 50, width: 180, offset:new Microsoft.Maps.Point(-220, 150)});
map.entities.push(venueinfobox);
} </script> </head> <body onload="GetMap();"> <div id='mapDiv' style="position:relative; width:500px; height:500px;"></div> </body> </html>
The Bing Maps AJAX Control 7.0 uses features of HTML5 if it detects that the client browser supports HTML5. If this is the case, map performance will be faster, and map animations and transitions will be smoother.
Supported Browsers
The Bing Maps AJAX Control 7.0 is supported on the following Web browsers. If you are not using a supported Web browser, certain features of the map control may not work.
Desktop Browser Description
Internet Explorer 7.0 Internet Explorer 8.0 Internet Explorer 9.0 Firefox 3.6 Firefox 4.0
Supported on the PC Supported on the PC Supported on the PC Supported on the PC and the Mac Supported on the PC and the Mac
Desktop Browser
Description
Mobile Browser
Apple 3GS/4.0 iPhone Browser Google Android 2.X Browser Research in Motion (RIM) BlackBerry 6.0 Browser
Developer Resources
The following resources are available for Bing Maps developers: Check out the Bing Maps AJAX Control 7.0 Interactive SDK, which allows you to test out your own map control code. Connect with other Bing Maps developers on the Bing Maps AJAX Control Forum. Visit the http://www.microsoft.com/maps website. Read the Bing Maps Developer blog
Account Issues
If you are having issues creating a Bing Maps Developer Account, getting a Bing Maps Key, or have an account access question, contact mpnet@microsoft.com.
Licensing Questions
If you are interested in finding out more about Bing Maps or have questions about licensing Bing Maps, email maplic@microsoft.com or go to http://www.microsoft.com/maps/resources/default.aspx. From North, Central, and South America, you can also contact Bing Maps by calling (800) 426-9400, ext. 11315.