+ All Categories
Home > Documents > Bing Maps Ajax Controls Dk 70

Bing Maps Ajax Controls Dk 70

Date post: 28-Oct-2014
Category:
Upload: jose-orellana
View: 842 times
Download: 8 times
Share this document with a friend
Popular Tags:
354
Contents Bing Maps AJAX Control, Version 7.0 ........................................................................................... 14 In This Section............................................................................................................................ 14 See Also ..................................................................................................................................... 14 Getting Started with the 7.0 Map Control ...................................................................................... 15 Create a Bing Maps Account and Get a Key ............................................................................. 15 Get Familiar with the Bing Maps AJAX 7.0 Control ................................................................... 15 What's New in the AJAX Map Control ........................................................................................... 15 New Features ............................................................................................................................. 15 Developing with the 7.0 Map Control............................................................................................. 16 In This Section............................................................................................................................ 16 Loading the AJAX Map Control ..................................................................................................... 16 Displaying the Default Map ........................................................................................................ 16 Customizing the Map When Loading ......................................................................................... 19 Example ..................................................................................................................................... 19 Setting Map Control Parameters ................................................................................................... 20 Parameters ................................................................................................................................. 20 Setting Parameters..................................................................................................................... 21 See Also ..................................................................................................................................... 21 Changing the Map View ................................................................................................................ 21 Setting the Initial Map View ........................................................................................................ 22 Changing the Map View ............................................................................................................. 23 Adding Entities to the Map ............................................................................................................. 25 Adding Single Entities to the Map .............................................................................................. 25 Adding a Pushpin .................................................................................................................... 25 Adding a Shape ...................................................................................................................... 27 Adding Multiple Entities to the Map ............................................................................................ 29 Changing Entities on the Map .................................................................................................... 30 Customizing Your Pushpins .......................................................................................................... 33 Customizing Your Pushpin Icon ................................................................................................. 33 Creating a Pushpin Infobox ........................................................................................................ 34 Displaying Location Search Results Using the REST Services .................................................... 36 Initialize the Map ........................................................................................................................ 36 Add Controls............................................................................................................................... 37
Transcript
Page 1: Bing Maps Ajax Controls Dk 70

Contents

Bing Maps AJAX Control, Version 7.0 ........................................................................................... 14

In This Section ............................................................................................................................ 14

See Also ..................................................................................................................................... 14

Getting Started with the 7.0 Map Control ...................................................................................... 15

Create a Bing Maps Account and Get a Key ............................................................................. 15

Get Familiar with the Bing Maps AJAX 7.0 Control ................................................................... 15

What's New in the AJAX Map Control ........................................................................................... 15

New Features ............................................................................................................................. 15

Developing with the 7.0 Map Control............................................................................................. 16

In This Section ............................................................................................................................ 16

Loading the AJAX Map Control ..................................................................................................... 16

Displaying the Default Map ........................................................................................................ 16

Customizing the Map When Loading ......................................................................................... 19

Example ..................................................................................................................................... 19

Setting Map Control Parameters ................................................................................................... 20

Parameters ................................................................................................................................. 20

Setting Parameters..................................................................................................................... 21

See Also ..................................................................................................................................... 21

Changing the Map View ................................................................................................................ 21

Setting the Initial Map View ........................................................................................................ 22

Changing the Map View ............................................................................................................. 23

Adding Entities to the Map ............................................................................................................. 25

Adding Single Entities to the Map .............................................................................................. 25

Adding a Pushpin .................................................................................................................... 25

Adding a Shape ...................................................................................................................... 27

Adding Multiple Entities to the Map ............................................................................................ 29

Changing Entities on the Map .................................................................................................... 30

Customizing Your Pushpins .......................................................................................................... 33

Customizing Your Pushpin Icon ................................................................................................. 33

Creating a Pushpin Infobox ........................................................................................................ 34

Displaying Location Search Results Using the REST Services .................................................... 36

Initialize the Map ........................................................................................................................ 36

Add Controls ............................................................................................................................... 37

Page 2: Bing Maps Ajax Controls Dk 70

Make a Geocode REST Request ............................................................................................... 38

Display the Results..................................................................................................................... 39

Getting Route Directions Using the REST Services ...................................................................... 41

Initialize the Map ........................................................................................................................ 41

Construct the Route Request ..................................................................................................... 42

Display the Results..................................................................................................................... 43

Working with Tile Layers ............................................................................................................... 46

Adding a Tile Layer .................................................................................................................... 46

Using Events in the AJAX Control ................................................................................................. 47

Example ..................................................................................................................................... 47

Returning a Localized Map ............................................................................................................ 51

Setting the Culture...................................................................................................................... 51

Supported Cultures .................................................................................................................... 52

Remarks ..................................................................................................................................... 53

Building Your Own Module ............................................................................................................ 53

Develop Your Module ................................................................................................................. 53

Register and Load Your Module ................................................................................................ 54

Use Your Module........................................................................................................................ 54

See Also ..................................................................................................................................... 56

Developing a Metro Style App ....................................................................................................... 56

Requirements ............................................................................................................................. 56

Getting Started ........................................................................................................................... 56

Remarks ..................................................................................................................................... 57

Example ..................................................................................................................................... 58

See Also ..................................................................................................................................... 65

Microsoft.Maps API Reference ...................................................................................................... 65

In This Section ............................................................................................................................ 65

Data Structures ....................................................................................................................... 65

Mapping .................................................................................................................................. 66

Entities .................................................................................................................................... 66

User Location .......................................................................................................................... 66

Dynamic Module Loading ....................................................................................................... 67

AltitudeReference Enumeration ..................................................................................................... 67

Constants ................................................................................................................................... 67

Methods ...................................................................................................................................... 67

Example ..................................................................................................................................... 67

AnimationVisibility Enumeration .................................................................................................... 69

Page 3: Bing Maps Ajax Controls Dk 70

Constants ................................................................................................................................... 69

Color Class .................................................................................................................................... 69

Constructor ................................................................................................................................. 69

Properties ................................................................................................................................... 69

Static Methods ............................................................................................................................ 70

Methods ...................................................................................................................................... 70

Example ..................................................................................................................................... 71

Coordinates Class ......................................................................................................................... 73

Properties ................................................................................................................................... 73

See Also ..................................................................................................................................... 74

EntityCollection Class .................................................................................................................... 74

Constructor ................................................................................................................................. 74

Methods ...................................................................................................................................... 74

Events ........................................................................................................................................ 76

Example ..................................................................................................................................... 77

EntityCollectionOptions Object ...................................................................................................... 79

Properties ................................................................................................................................... 79

Example ..................................................................................................................................... 80

Events Object ................................................................................................................................ 82

Methods ...................................................................................................................................... 82

Example ..................................................................................................................................... 83

GeoLocationProvider Class ........................................................................................................... 85

Constructor ................................................................................................................................. 85

Methods ...................................................................................................................................... 85

Example ..................................................................................................................................... 87

See Also ..................................................................................................................................... 88

Infobox Class ................................................................................................................................. 89

Constructor ................................................................................................................................. 89

Methods ...................................................................................................................................... 89

Events ........................................................................................................................................ 92

Remarks ..................................................................................................................................... 92

Example ..................................................................................................................................... 92

InfoboxOptions Object ................................................................................................................... 94

Properties ................................................................................................................................... 94

Example ..................................................................................................................................... 97

See Also ..................................................................................................................................... 99

InfoboxType Enumeration ............................................................................................................. 99

Page 4: Bing Maps Ajax Controls Dk 70

Constants ................................................................................................................................... 99

Example ..................................................................................................................................... 99

KeyEventArgs Object .................................................................................................................. 101

Properties ................................................................................................................................. 101

Example ................................................................................................................................... 101

LabelOverlay Enumeration .......................................................................................................... 103

Constants ................................................................................................................................. 103

Methods .................................................................................................................................... 103

Example ................................................................................................................................... 103

Location Class (AJAX) ................................................................................................................. 105

Constructor ............................................................................................................................... 105

Properties ................................................................................................................................. 105

Static Methods .......................................................................................................................... 105

Methods .................................................................................................................................... 106

Example ................................................................................................................................... 106

LocationRect Class ...................................................................................................................... 107

Constructor ............................................................................................................................... 108

Properties ................................................................................................................................. 108

Static Methods .......................................................................................................................... 108

Methods .................................................................................................................................... 109

Example ................................................................................................................................... 110

Map Class .................................................................................................................................... 111

Constructor ............................................................................................................................... 111

Properties ................................................................................................................................. 112

Static Methods .......................................................................................................................... 112

Methods .................................................................................................................................... 112

Events ...................................................................................................................................... 116

Example ................................................................................................................................... 118

MapMode Class (AJAX) .............................................................................................................. 119

Mercator Map Mode Methods .................................................................................................. 119

MapOptions Object ...................................................................................................................... 121

Properties ................................................................................................................................. 121

Example ................................................................................................................................... 125

MapTypeId Enumeration ............................................................................................................. 126

Constants ................................................................................................................................. 126

Example ................................................................................................................................... 126

See Also ................................................................................................................................... 127

Page 5: Bing Maps Ajax Controls Dk 70

Module Loading Methods ............................................................................................................ 127

Methods .................................................................................................................................... 127

Example ................................................................................................................................... 129

See Also ................................................................................................................................... 131

MouseEventArgs Object .............................................................................................................. 131

Properties ................................................................................................................................. 131

Methods .................................................................................................................................... 132

Example ................................................................................................................................... 132

PixelReference Enumeration ....................................................................................................... 134

Constants ................................................................................................................................. 134

Methods .................................................................................................................................... 134

Example ................................................................................................................................... 134

Point Class ................................................................................................................................... 136

Constructor ............................................................................................................................... 136

Properties ................................................................................................................................. 136

Static Methods .......................................................................................................................... 137

Methods .................................................................................................................................... 137

Example ................................................................................................................................... 137

Polygon Class (AJAX) ................................................................................................................. 139

Constructor ............................................................................................................................... 139

Methods .................................................................................................................................... 139

Events ...................................................................................................................................... 140

Example ................................................................................................................................... 141

PolygonOptions Object ................................................................................................................ 143

Properties ................................................................................................................................. 143

Example ................................................................................................................................... 143

Polyline Class .............................................................................................................................. 145

Constructor ............................................................................................................................... 145

Methods .................................................................................................................................... 145

Events ...................................................................................................................................... 146

Example ................................................................................................................................... 147

PolylineOptions Object ................................................................................................................ 149

Properties ................................................................................................................................. 149

Example ................................................................................................................................... 149

Position Class .............................................................................................................................. 151

Properties ................................................................................................................................. 151

See Also ................................................................................................................................... 151

Page 6: Bing Maps Ajax Controls Dk 70

PositionCircleOptions Object ....................................................................................................... 151

Properties ................................................................................................................................. 151

Example ................................................................................................................................... 152

PositionError Class ...................................................................................................................... 153

Properties ................................................................................................................................. 154

See Also ................................................................................................................................... 154

PositionOptions Object ................................................................................................................ 154

Properties ................................................................................................................................. 154

Example ................................................................................................................................... 156

Pushpin Class (AJAX) ................................................................................................................. 158

Constructor ............................................................................................................................... 158

Methods .................................................................................................................................... 158

Events ...................................................................................................................................... 159

Example ................................................................................................................................... 161

PushpinOptions Object ................................................................................................................ 162

Properties ................................................................................................................................. 162

Example ................................................................................................................................... 163

TileLayer Class ............................................................................................................................ 165

Constructor ............................................................................................................................... 165

Methods .................................................................................................................................... 165

Events ...................................................................................................................................... 166

Example ................................................................................................................................... 166

See Also ................................................................................................................................... 168

TileLayerOptions Object .............................................................................................................. 168

Properties ................................................................................................................................. 168

Example ................................................................................................................................... 169

See Also ................................................................................................................................... 171

TileSource Class.......................................................................................................................... 171

Constructor ............................................................................................................................... 171

Methods .................................................................................................................................... 171

Example ................................................................................................................................... 172

See Also ................................................................................................................................... 173

TileSourceOptions Object ............................................................................................................ 173

Properties ................................................................................................................................. 173

Example ................................................................................................................................... 174

See Also ................................................................................................................................... 176

ViewOptions Object ..................................................................................................................... 176

Page 7: Bing Maps Ajax Controls Dk 70

Properties ................................................................................................................................. 176

Remarks ................................................................................................................................... 177

Example ................................................................................................................................... 177

Microsoft.Maps.AdvancedShapes API Reference ...................................................................... 179

In This Section .......................................................................................................................... 179

EntityCollection Class (AdvancedShapes) .................................................................................. 179

Constructor ............................................................................................................................... 180

Methods .................................................................................................................................... 180

Events ...................................................................................................................................... 181

Remarks ................................................................................................................................... 183

Polygon Class (AdvancedShapes) .............................................................................................. 183

Constructor ............................................................................................................................... 183

Methods .................................................................................................................................... 184

Events ...................................................................................................................................... 185

Example ................................................................................................................................... 186

Microsoft.Maps.Directions API Reference ................................................................................... 188

In This Section .......................................................................................................................... 188

BusinessDetails Class ................................................................................................................. 189

Properties ................................................................................................................................. 189

See Also ................................................................................................................................... 190

BusinessDisambiguationSuggestion Class ................................................................................. 190

Properties ................................................................................................................................. 190

Example ................................................................................................................................... 191

See Also ................................................................................................................................... 195

DirectionsErrorEventArgs Object ................................................................................................. 195

Properties ................................................................................................................................. 195

Example ................................................................................................................................... 195

DirectionsEventArgs Object ......................................................................................................... 197

Properties ................................................................................................................................. 197

Example ................................................................................................................................... 198

DirectionsManager Class ............................................................................................................ 200

Constructor ............................................................................................................................... 200

Methods .................................................................................................................................... 200

Events ...................................................................................................................................... 204

Example ................................................................................................................................... 206

DirectionsRenderOptions Object ................................................................................................. 208

Page 8: Bing Maps Ajax Controls Dk 70

Properties ................................................................................................................................. 208

Example ................................................................................................................................... 211

DirectionsRequestOptions Object ............................................................................................... 213

Properties ................................................................................................................................. 213

Example ................................................................................................................................... 215

DirectionsStep Class ................................................................................................................... 217

Properties ................................................................................................................................. 217

Example ................................................................................................................................... 218

DirectionsStepEventArgs Object ................................................................................................. 221

Properties ................................................................................................................................. 221

Example ................................................................................................................................... 222

DirectionsStepRenderEventArgs Object ..................................................................................... 225

Properties ................................................................................................................................. 225

Example ................................................................................................................................... 225

DirectionsStepWarning Class ...................................................................................................... 228

Properties ................................................................................................................................. 228

Example ................................................................................................................................... 228

Disambiguation Class .................................................................................................................. 231

Properties ................................................................................................................................. 231

Example ................................................................................................................................... 232

See Also ................................................................................................................................... 235

DisambiguationRenderEventArgs Object .................................................................................... 235

Properties ................................................................................................................................. 236

DistanceUnit Enumeration (AJAX) .............................................................................................. 236

Constants ................................................................................................................................. 236

Example ................................................................................................................................... 236

IconType Enumeration ................................................................................................................ 239

Constants ................................................................................................................................. 239

Example ................................................................................................................................... 239

LocationDisambiguationSuggestion Class .................................................................................. 242

Properties ................................................................................................................................. 242

Example ................................................................................................................................... 243

See Also ................................................................................................................................... 246

Maneuver Enumeration ............................................................................................................... 246

Constants ................................................................................................................................. 246

Example ................................................................................................................................... 250

Page 9: Bing Maps Ajax Controls Dk 70

ResetDirectionsOptions Object ................................................................................................... 253

Properties ................................................................................................................................. 254

Route Class (AJAX) ..................................................................................................................... 254

Properties ................................................................................................................................. 254

RouteAvoidance Enumeration ..................................................................................................... 254

Constants ................................................................................................................................. 254

RouteLeg Class (AJAX) ............................................................................................................... 255

Properties ................................................................................................................................. 256

Example ................................................................................................................................... 256

RouteMode Enumeration ............................................................................................................. 258

Constants ................................................................................................................................. 258

RouteOptimization Enumeration (AJAX) ..................................................................................... 259

Constants ................................................................................................................................. 259

RoutePath Class (AJAX) ............................................................................................................. 260

Properties ................................................................................................................................. 260

RouteResponseCode Enumeration ............................................................................................. 260

Constants ................................................................................................................................. 260

Example ................................................................................................................................... 262

RouteSelectorEventArgs Object .................................................................................................. 264

Properties ................................................................................................................................. 264

RouteSelectorRenderEventArgs Object ...................................................................................... 265

Properties ................................................................................................................................. 265

RouteSubLeg Class ..................................................................................................................... 265

Properties ................................................................................................................................. 265

RouteSummary Class (AJAX) ..................................................................................................... 266

Properties ................................................................................................................................. 266

Example ................................................................................................................................... 267

RouteSummaryRenderEventArgs Object .................................................................................... 269

Properties ................................................................................................................................. 269

StepWarningStyle Enumeration .................................................................................................. 270

Constants ................................................................................................................................. 270

Example ................................................................................................................................... 270

TimeType Enumeration ............................................................................................................... 274

Constants ................................................................................................................................. 274

Page 10: Bing Maps Ajax Controls Dk 70

Example ................................................................................................................................... 274

See Also ................................................................................................................................... 276

TransitLine Class ......................................................................................................................... 276

Properties ................................................................................................................................. 277

Example ................................................................................................................................... 277

TransitOptions Object .................................................................................................................. 280

Properties ................................................................................................................................. 280

Example ................................................................................................................................... 281

Waypoint Class (AJAX) ............................................................................................................... 283

Constructor ............................................................................................................................... 283

Methods .................................................................................................................................... 283

Events ...................................................................................................................................... 285

Example ................................................................................................................................... 286

WaypointEventArgs Object .......................................................................................................... 289

Properties ................................................................................................................................. 289

WaypointOptions Object .............................................................................................................. 290

Properties ................................................................................................................................. 290

Example ................................................................................................................................... 291

WaypointRenderEventArgs Object .............................................................................................. 293

Properties ................................................................................................................................. 293

Microsoft.Maps.Overlays.Style Reference .................................................................................. 294

Navigation Bar Style ................................................................................................................. 294

Microsoft.Maps.Search API Reference ....................................................................................... 295

In This Section .......................................................................................................................... 295

Address Class (AJAX) ................................................................................................................. 296

Properties ................................................................................................................................. 296

GeocodeLocation Class (AJAX) .................................................................................................. 297

Properties ................................................................................................................................. 297

GeocodeRequestOptions Object ................................................................................................. 297

Properties ................................................................................................................................. 297

Example ................................................................................................................................... 298

See Also ................................................................................................................................... 300

GeocodeResult Class (AJAX) ..................................................................................................... 300

Properties ................................................................................................................................. 300

LocationPrecision Enum .............................................................................................................. 301

Page 11: Bing Maps Ajax Controls Dk 70

Constants ................................................................................................................................. 301

MatchCode Enum ........................................................................................................................ 301

Constants ................................................................................................................................. 301

MatchConfidence Enum .............................................................................................................. 302

Constants ................................................................................................................................. 302

PlaceResult Class........................................................................................................................ 302

Properties ................................................................................................................................. 302

ReverseGeocodeRequestOptions Object ................................................................................... 303

Properties ................................................................................................................................. 303

Example ................................................................................................................................... 303

See Also ................................................................................................................................... 305

SearchManager Class ................................................................................................................. 305

Constructor ............................................................................................................................... 305

Methods .................................................................................................................................... 305

Example ................................................................................................................................... 307

SearchParseResult Class ............................................................................................................ 308

Properties ................................................................................................................................. 309

SearchRegion Class (AJAX) ....................................................................................................... 309

Properties ................................................................................................................................. 309

SearchRequestOptions Object .................................................................................................... 310

Properties ................................................................................................................................. 310

Example ................................................................................................................................... 311

See Also ................................................................................................................................... 313

SearchResponse Class (AJAX) ................................................................................................... 313

Properties ................................................................................................................................. 313

See Also ................................................................................................................................... 313

SearchResponseSummary Class ................................................................................................ 314

Properties ................................................................................................................................. 314

SearchResult Class ..................................................................................................................... 314

Properties ................................................................................................................................. 314

Microsoft.Maps.Themes.BingTheme API Reference .................................................................. 315

BingTheme Features ................................................................................................................ 315

Example ................................................................................................................................... 316

Microsoft.Maps.Traffic API Reference ......................................................................................... 317

In This Section .......................................................................................................................... 317

Page 12: Bing Maps Ajax Controls Dk 70

TrafficLayer Class ........................................................................................................................ 317

Constructor ............................................................................................................................... 317

Methods .................................................................................................................................... 318

Example ................................................................................................................................... 318

Microsoft.Maps.VenueMaps API Reference ............................................................................... 319

In This Section .......................................................................................................................... 319

Directory Class ............................................................................................................................ 320

Methods .................................................................................................................................... 320

Events ...................................................................................................................................... 322

Example ................................................................................................................................... 323

DirectoryGrouping Enumeration .................................................................................................. 327

Constants ................................................................................................................................. 327

DirectorySortOrder Enumeration ................................................................................................. 327

Constants ................................................................................................................................. 328

Floor Class ................................................................................................................................... 328

Properties ................................................................................................................................. 328

Example ................................................................................................................................... 328

Footprint Class ............................................................................................................................. 331

Properties ................................................................................................................................. 331

Example ................................................................................................................................... 331

Metadata Class ............................................................................................................................ 333

Properties ................................................................................................................................. 333

Example ................................................................................................................................... 334

NearbyVenue Class ..................................................................................................................... 336

Properties ................................................................................................................................. 336

Example ................................................................................................................................... 336

NearbyVenueOptions Object ....................................................................................................... 338

Properties ................................................................................................................................. 338

Example ................................................................................................................................... 338

Polygon Class (Venue Map) ........................................................................................................ 340

Properties ................................................................................................................................. 340

Primitive Class ............................................................................................................................. 340

Properties ................................................................................................................................. 341

Methods .................................................................................................................................... 341

Example ................................................................................................................................... 342

Page 13: Bing Maps Ajax Controls Dk 70

VenueMap Class ......................................................................................................................... 344

Properties ................................................................................................................................. 344

Methods .................................................................................................................................... 345

Events ...................................................................................................................................... 345

Example ................................................................................................................................... 346

VenueMapCreationOptions Object .............................................................................................. 348

Properties ................................................................................................................................. 348

Example ................................................................................................................................... 349

VenueMapFactory Class ............................................................................................................. 350

Constructor ............................................................................................................................... 350

Methods .................................................................................................................................... 351

Example ................................................................................................................................... 351

Bing Maps AJAX Control 7.0 Supported Browsers ..................................................................... 353

Supported Browsers ................................................................................................................. 353

Bing Maps AJAX Control 7.0 Developer Resources ................................................................... 354

Developer Resources ............................................................................................................... 354

Account Issues ......................................................................................................................... 354

Licensing Questions ................................................................................................................. 354

Page 14: Bing Maps Ajax Controls Dk 70

14

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, as well as into

Metro style apps (see Developing a Metro Style App).

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.AdvancedShapes API Reference

Microsoft.Maps.Directions API Reference

Microsoft.Maps.Overlays.Style Reference

Microsoft.Maps.Search API Reference

Microsoft.Maps.Themes.BingTheme API Reference

Microsoft.Maps.Traffic API Reference

Microsoft.Maps.VenueMaps API Reference

Supported Browsers

Developer Resources

See Also Terms and Conditions

Page 15: Bing Maps Ajax Controls Dk 70

15

Getting Started with the 7.0 Map Control

The Bing Maps AJAX Control 7.0 is a JavaScript control that contains the objects, methods, and

events that allow you to display maps powered by Bing Maps on your Web site. The sections in

this topic describe the steps you need to take to start using the Bing Maps AJAX Control 7.0.

Create a Bing Maps Account and Get a Key Before you begin developing your application, you need to create a developer account on the

Bing Maps Account Center. A Bing Maps Developer Account allows you to create a Bing Maps

Key to use in your map application. Getting a key is described in Getting a Bing Maps Key.

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

user‟s 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.

Get Familiar with the Bing Maps AJAX 7.0 Control The Developing with the 7.0 Map Control section of this SDK contains topics that describe how to

use the features provided by the AJAX map control.

What's New in the AJAX Map Control

Welcome to the latest release of the Bing Maps AJAX Control 7.0!

New Features This release of the map control includes the following new features:

Render complex shapes Create polygons with holes using the new

Microsoft.Maps.AdvancedShapes module.

Use the latest Bing Maps design Load the Microsoft.Maps.Themes.BingTheme to provide

your customers with the latest Bing Maps site look.

Search Geocode an address, reverse geocode to match a location to an address, and

search nearby points of interest using the new Microsoft.Maps.Search module.

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.

Page 16: Bing Maps Ajax Controls Dk 70

16

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.

Developing with the 7.0 Map Control

The topics in this section will help you to start using the Bing Maps AJAX Control 7.0.

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

Developing a Metro Style App

Loading the AJAX Map Control

This topic describes how to load the Bing Maps AJAX Control 7.0 into your Web page to display a

map. This is the first step you need to take for any page that uses the map control.

Displaying the Default Map Displaying the default map, which includes all of the navigation functionality, consists of the

following steps:

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.

Page 17: Bing Maps Ajax Controls Dk 70

17

<meta http-equiv="Content-Type" content="text/html; charset=utf-

8"/>

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

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

Page 18: Bing Maps Ajax Controls Dk 70

18

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

function GetMap()

{

Page 19: Bing Maps Ajax Controls Dk 70

19

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>

Customizing the Map When Loading You can also specify other options when the map is first loaded, such as the location, zoom level,

and the imagery of the map. To do this, pass in MapOptions or ViewOptions to the Map

constructor. The code below sets the imagery to Aerial.

var mapOptions = {

credentials: "Your Bing Maps Key",

mapTypeId: Microsoft.Maps.MapTypeId.aerial

}

var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), mapOptions);

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>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

Page 20: Bing Maps Ajax Controls Dk 70

20

<script type="text/javascript">

function GetMap()

{

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>

Setting Map Control Parameters

This topic describes map control parameters.

Parameters The following table contains available parameters for the map control reference.

Parameter Values Description

v 7.0 Specifies a major API version.

The default value is the latest

version, which is 7.0.

s 0, 1 Specifies whether to use SSL.

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"

Page 21: Bing Maps Ajax Controls Dk 70

21

Parameter Values Description

(English).

onscriptload A string specifying a function

name.

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.

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

Changing the Map View

This topic describes how to change the map that is displayed.

Page 22: Bing Maps Ajax Controls Dk 70

22

Setting the Initial Map View You can set the map view when you first load the map you can use any of the options available in

the MapOptions Object or ViewOptions Object.

The code below initializes the map with a specific view. The imagery displayed is set to Bird‟s eye

using the mapTypeId option. Valid map type IDs are listed 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>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<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

}

var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), mapOptions);

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:600px; height:600px;"></div>

</body>

</html>

Page 23: Bing Maps Ajax Controls Dk 70

23

Changing the Map View If you want to change the map after it has loaded, use the setView method of the Map Class. The

ViewOptions Object contains available options that can be set.

The example below sets the map view to the specified zoom level.

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

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

function GetMap()

{

map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:

"Your Bing Maps Key", mapTypeId: Microsoft.Maps.MapTypeId.road});

}

function SetZoom()

{

var zoomLevel = parseInt(document.getElementById('txtZoom').value);

map.setView({zoom:zoomLevel});

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:500px; height:500px;"></div>

Page 24: Bing Maps Ajax Controls Dk 70

24

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

function GetMap()

{

map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:

"Your Bing Maps Key"});

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

map.setView({ bounds: viewBoundaries});

Page 25: Bing Maps Ajax Controls Dk 70

25

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:500px; height:500px;"></div>

</body>

</html>

Adding Entities to the Map

This topic describes how to add entities to the map. An Entity can be any one of the following

types: Polygon, Polyline, Pushpin, TileLayer, or EntityCollection. Information about working with

tile layers is in the Working with Tile Layers topic.

Adding Single Entities to the Map To add a pushpin, polygon, or polyline to the map, simply create your object then add the entity to

the entities property of the map.

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"

src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

function GetMap()

Page 26: Bing Maps Ajax Controls Dk 70

26

{

// Initialize the map

var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),

{credentials:"Your Bing Maps Key"});

// Retrieve the location of the map center

var center = map.getCenter();

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

src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

Page 27: Bing Maps Ajax Controls Dk 70

27

function GetMap()

{

// Initialize the map

map = new Microsoft.Maps.Map(document.getElementById("myMap"),

{credentials:"Bing Maps Key"});

// Define the pushpin location

var loc = new Microsoft.Maps.Location(47.592, -122.332);

// Add a pin to the map

var pin = new Microsoft.Maps.Pushpin(loc);

map.entities.push(pin);

// Center the map on the location

map.setView({center: loc, zoom: 10});

}

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

Page 28: Bing Maps Ajax Controls Dk 70

28

<html>

<head>

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<script type="text/javascript"

src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

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

// Add the polygon to the map

map.entities.push(polygon);

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:400px; height:400px;"></div>

</body>

</html>

Page 29: Bing Maps Ajax Controls Dk 70

29

Adding Multiple Entities to the Map If you want to add multiple entities to the map at one time, first create an EntityCollection then

add this collection to the map. The code below adds a polygon with pushpins at its corners.

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

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<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

Page 30: Bing Maps Ajax Controls Dk 70

30

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

// Add the shape to the map

map.entities.push(polygonWithPins)

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:400px; height:400px;"></div>

</body>

</html>

Changing Entities on the Map Once entities have been added to the map, you can use the methods of the map entities

collection to change and manipulate those entities. The code implements a button to change the

color of a shape on 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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

Page 31: Bing Maps Ajax Controls Dk 70

31

var map = null;

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

// Add the shapes to the map

Page 32: Bing Maps Ajax Controls Dk 70

32

map.entities.push(triangle);

map.entities.push(square);

}

function ChangePolygonColor()

{

// Get the map square entity. We know square was the last entity added,

// so we can calculate the index.

var mapSquare = map.entities.get(map.entities.getLength()-1);

// Get the current color

var currentColor = mapSquare.getFillColor();

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>

Page 33: Bing Maps Ajax Controls Dk 70

33

Customizing Your Pushpins

The Bing Maps AJAX Control, Version 7.0 provides flexible pushpin functionality. Use options

provided in the PushpinOptions Object to customize your pushpins.

This topic describes how to customize your pushpin icon as well as how to create a pushpin info

box.

Customizing Your Pushpin Icon If you do not want to use the default pushpin icon, you can set the icon property of the

PushpinOptions to the image you want to use instead.

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

function GetMap()

{

// Initialize the map

map = new Microsoft.Maps.Map(document.getElementById("myMap"),

{credentials:"Bing Maps Key"});

Page 34: Bing Maps Ajax Controls Dk 70

34

// Retrieve the location of the map center

var center = map.getCenter();

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

Creating a Pushpin Infobox The Bing Maps AJAX Control, Version 7.0 has built-in pushpin info box functionality which you

can customize to suit the needs of your application. To create an info box, use the Infobox and

InfoboxOptions types.

The example below shows how to display an info box when a pushpin is clicked.

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

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

Page 35: Bing Maps Ajax Controls Dk 70

35

var map = null;

var pinInfobox = null;

function GetMap()

{

// Initialize the map

map = new Microsoft.Maps.Map(document.getElementById("myMap"),

{credentials:"Bing Maps Key"});

// Retrieve the location of the map center

var center = map.getCenter();

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

// Add the pushpin and infobox to the map

map.entities.push(pin);

map.entities.push(pinInfobox);

Page 36: Bing Maps Ajax Controls Dk 70

36

}

function displayInfobox(e)

{

pinInfobox.setOptions({ visible:true });

}

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>

Displaying Location Search Results Using the REST Services

The Bing Maps AJAX Control, version 7.0 does not have built in functionality to return find results,

but you can easily use the Bing Maps REST Services to geocode locations that you can then

display on the map.

Initialize the Map Before you add geocoding functionality, initialize the map using the following code.

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

Page 37: Bing Maps Ajax Controls Dk 70

37

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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)

{

Page 38: Bing Maps Ajax Controls Dk 70

38

map.getCredentials(MakeGeocodeRequest);

}

Make a Geocode REST Request Next, make a geocode request to the Bing Maps REST Services using the value in the txtQuery

input box and the credentials.

The Bing Maps REST Services can return an XML or JSON response object. For JavaScript

code, JSON is more appropriate, so set output=JSON. This means that you need to also set a

jsonp callback function name. In this sample the callback function is named GeocodeCallback.

Finally, since you do not know if the text provided is a place name or an address, supply the

locationQuery parameter and set it to the value of the txtQuery text box. Your REST geocode

request looks like this:

var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations?query=" +

encodeURI(document.getElementById('txtQuery').value) +

"&output=json&jsonp=GeocodeCallback&key=" + credentials;

Now add script to make the REST request.

function MakeGeocodeRequest(credentials)

{

var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations?query=" +

encodeURI(document.getElementById('txtQuery').value) +

"&output=json&jsonp=GeocodeCallback&key=" + credentials;

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

}

Page 39: Bing Maps Ajax Controls Dk 70

39

Display the Results Finally, add code to the GeocodeCallback function to set the map view to the found location and

add a pushpin at that location. The final code is 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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

function GetMap()

{

// Initialize the map

map = new

Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Your Bing Maps Key",

mapTypeId:Microsoft.Maps.MapTypeId.road});

}

function ClickGeocode(credentials)

{

map.getCredentials(MakeGeocodeRequest);

}

function MakeGeocodeRequest(credentials)

{

Page 40: Bing Maps Ajax Controls Dk 70

40

var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations?query=" +

encodeURI(document.getElementById('txtQuery').value) +

"&output=json&jsonp=GeocodeCallback&key=" + credentials;

CallRestService(geocodeRequest);

}

function GeocodeCallback(result)

{

alert("Found location: " + result.resourceSets[0].resources[0].name);

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)

Page 41: Bing Maps Ajax Controls Dk 70

41

{

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>

Getting Route Directions Using the REST Services

The latest release of the Bing Maps AJAX Control 7.0 provides directions functionality in

the Microsoft.Maps.Directions module. This module allows you to easily customize,

calculate, and display directions and a route on your web site without needing to use

REST services. Get started by going to the DirectionsManager Class topic, which

contains information about the calculateDirections method and sample code.

This topic describes how to use the Bing Maps REST Services to calculate and display a route on

the map.

Initialize the Map Before you add route functionality, initialize the map using the following code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

<head>

Page 42: Bing Maps Ajax Controls Dk 70

42

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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>

Construct the Route Request Next, add input controls and construct the Bing Maps REST Services Route request.

In this example, a route is calculated between a specified start and end point. Add two text boxes

and a button to initiate the route calculation.

<input id="txtStart" type="text" value="Seattle"/>

<input id="txtEnd" type="text" value="Portland"/>

<input type="button" value="Calculate Route" onclick="ClickRoute()"/>

Page 43: Bing Maps Ajax Controls Dk 70

43

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;

Display the Results Finally, add code to make the route request when the button is clicked, and add code to the

RouteCallback function to set the map view and draw the route. The final code is 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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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)

Page 44: Bing Maps Ajax Controls Dk 70

44

{

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

Page 45: Bing Maps Ajax Controls Dk 70

45

// Draw the route

var routeline = result.resourceSets[0].resources[0].routePath.line;

var routepoints = new Array();

for (var i = 0; i < routeline.coordinates.length; i++) {

routepoints[i]=new

Microsoft.Maps.Location(routeline.coordinates[i][0], routeline.coordinates[i][1]);

}

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

Page 46: Bing Maps Ajax Controls Dk 70

46

<input type="button" value="Calculate Route" onclick="ClickRoute()"/>

</body>

</html>

Working with Tile Layers

This topic describes how to add a custom tile layer to the map.

Adding a Tile Layer A tile layer is a valid map entity, so after you construct your layer, you can add it to the map using

the push method of the map entities collection. The code below adds a custom tile layer 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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<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

Page 47: Bing Maps Ajax Controls Dk 70

47

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

// Push the tile layer to the map

map.entities.push(tilelayer);

}

catch(err)

{

alert( 'Error Message:' + err.message);

}

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:400px; height:400px;"></div>

</body>

</html>

Using Events in the AJAX Control

The Bing Maps AJAX Control 7.0 provides many events to allow your application to respond to

user actions. The EntityCollection, Map, Pushpin, Polyline, and Polygon classes all have event

members. The code examples in this topic show how to use the Map click event and the

EntityCollection entityadded event.

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.

Page 48: Bing Maps Ajax Controls Dk 70

48

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

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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;

}

Page 49: Bing Maps Ajax Controls Dk 70

49

}

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

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var noPins = true;

function GetMap()

{

// Initialize the map

map = new Microsoft.Maps.Map(document.getElementById("myMap"),

{credentials:"Bing Maps Key"});

Page 50: Bing Maps Ajax Controls Dk 70

50

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

Microsoft.Maps.Events.addHandler(map.entities, 'entityadded', shadePins);

}

function addPin(e) {

if (e.targetType == "map") {

var point = new Microsoft.Maps.Point(e.getX(), e.getY());

var loc = e.target.tryPixelToLocation(point);

var pin = new Microsoft.Maps.Pushpin(loc);

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;

}

else

{

var pin = null;

// Loop through the collection of pushpins on the map and grey out

Page 51: Bing Maps Ajax Controls Dk 70

51

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

Returning a Localized Map

The Bing Maps AJAX Control 7.0 provides the ability to return a localized map and route

directions.

Setting the Culture By default the map labels and the navigation control text are provided in the culture English-

United States (en-US). However, the map control culture can be changed by adding the mkt

parameter to the map control reference, as in the following example, which sets the culture to

French-France (fr-FR).

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0&mkt=fr-

fr"></script>

Page 52: Bing Maps Ajax Controls Dk 70

52

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

cs-CZ X

Danish – Denmark da-DK X

Dutch - Belgium nl-BE X

Dutch – Netherlands nl-NL X

English - Australia en-AU X

English – Canada en-CA X X

English - India en-IN X

English - United

Kingdom

en-GB X X

English - United States en-US X X

Finnish – Finland fi-FI X

French – Canada fr-CA X X

French – France fr-FR X X

German – Germany de-DE X X

Italian – Italy it-IT X X

Japanese - Japan ja-JP X X

Norwegian (Bokmal) -

Norway

nb-NO X

Portuguese - Brazil pt-BR X

Portuguese - Portugal pt-PT X

Spanish - Mexico es-MX X X

Spanish - Spain es-ES X X

Spanish – United

States

es-US X X

Page 53: Bing Maps Ajax Controls Dk 70

53

Language -

Country/Region

Culture Map Control Microsoft.Maps.Directions

module

Swedish - Sweden sv-SE X

Remarks Error messages are always displayed in English - United States.

Building Your Own Module

The Bing Maps AJAX Control 7.0 allows you to easily register and load your own script modules.

This topic describes how to create a simple module.

Develop Your Module Begin by developing your module. The sample module below takes a map object as its

constructor and exposes a method to draw a red arrow pointing to a given location.

// arrowmodule.js

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,

Page 54: Bing Maps Ajax Controls Dk 70

54

location.longitude-5);

points[6] = new Microsoft.Maps.Location(location.latitude, location.longitude-

10);

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.

Register and Load Your Module After you have created your module and hosted it, register it within your map control application

using the Microsoft.Maps.registerModule method.

Microsoft.Maps.registerModule("ArrowModule", "http://example.com/arrowmodule.js");

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

Use Your Module Finally, use the functions provided by your module in your map control code. The sample code

below uses the drawRedArrow method of the ArrowModule to draw an arrow pointing to the

center of the map.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Page 55: Bing Maps Ajax Controls Dk 70

55

<html>

<head>

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

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

var arrowModule = new ArrowModule(map);

arrowModule.drawRedArrow(map.getCenter());

}

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

}

Page 56: Bing Maps Ajax Controls Dk 70

56

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:400px;

height:400px;"></div>

</body>

</html>

See Also Module Loading Methods

Developing a Metro Style App

This topic outlines how to use the Bing Maps AJAX Control 7.0 to develop a Metro style app

using JavaScript.

If you are interested in developing a Metro style app using C#/C++/VB, see Getting

Started with Bing Maps in Metro Style Apps.

Requirements To develop a Bing Maps Metro style app for Windows, you must first do the following:

Download and install the Windows 8 Beta, which includes Microsoft Visual Studio 11 Beta

and the Windows SDK for Metro style apps.

Download and install the Bing Maps SDK for Metro style apps.

Create a developer account on the Bing Maps Account Center. This allows you to get a Bing

Maps Key for use in your map application. For more information about creating a Bing Maps

Key, see Getting a Bing Maps Key.

Getting Started The steps below will get you started developing a Bing Maps Metro style app using JavaScript.

1. Launch Microsoft Visual Studio 11.0 Beta. From the main menu, select File, New, then

Project. In the New Project dialog, choose JavaScript as the language, select Windows

Page 57: Bing Maps Ajax Controls Dk 70

57

Metro style, and then choose Blank Application. Type a name for your application, and

click OK to create the project.

2. In the Solution Explorer, right-click References for your project and choose Add Reference.

Expand Windows and then select Extensions. Select Bing Maps for JavaScript (Beta),

and then click OK to add the reference. The default installation path for the Bing Maps SDK

for Metro style apps is C:\Users\<username>\AppData\Local\Microsoft

SDKs\Windows\v8.0\ExtensionSDKs\Bing.Maps.MapControl.JavaScript\1.0.

3. Open the default.html file and insert the following references

<!-- Bing Map Control references -->

<script type="text/javascript" src="ms-

appx:///Bing.Maps.MapControl.JavaScript//js/veapicore.js"></scri

pt>

4. Finally, add JavaScript code to load a module that downloads a necessary configuration file.

Microsoft.Maps.loadModule('Microsoft.Maps.Map', { callback:

initMap });

function initMap() {

var map;

var mapOptions =

{

credentials: ‘Your Bing Maps Key’,

};

map = new

Microsoft.Maps.Map(document.getElementById("mapdiv"),

mapOptions);

}

Now you can use the Bing Maps AJAX Control 7.0 API to create your Metro style app. Refer to

the Microsoft.Maps API Reference for detailed information about available functionality.

All of the APIs available for the standard Bing Maps AJAX Control are supported for

Metro style apps. However, only custom modules and the Microsoft.Maps.VenueMaps

module are supported.

Remarks Only custom modules and the Microsoft.Maps.VenueMaps module are supported. The

Microsoft.Maps.Directions module, the Microsoft.Maps.Overlays module, and the

Microsoft.Maps.Traffic module will not work in a Metro style app.

To use a custom module, register the module before referencing the module *.js file:

Page 58: Bing Maps Ajax Controls Dk 70

58

<script>Microsoft.Maps.registerModule('myCustomModule');</script

>

<script type="text/javascript"

src="/js/myCustomModule.js"></script>

You can then load the module and invoke the callback function anywhere within your code:

Microsoft.Maps.loadModule('myCustomModule', { callback:

customModuleLoaded });

To make a REST service request, use the Windows 8 xhr handler:

// Use the Bing Maps REST Service to return driving directions

function restDirections()

{

map.getCredentials( function(credentials)

{

var start= 'Boston, MA'; var end= 'NY, NY';

var routeRequest =

'http://dev.virtualearth.net/REST/v1/Routes?wp.0=' + start +

'&wp.1=' + end + '&routePathOutput=Points&output=json&key=' +

credentials;

WinJS.xhr({ url: routeRequest }).then(routeCallback);

});

}

// Route service callback function

function routeCallback(result)

{

result = JSON.parse(result.responseText);

}

Windows 8 provides enhanced Web content security that may affect some JavaScript

functionality. For more information, see the topic HTML, CSS, JavaScript, and Windows

Runtime for Metro style apps.

Example The following code demonstrates a variety of functionality in a Metro style app.

// default.html

<!DOCTYPE html>

Page 59: Bing Maps Ajax Controls Dk 70

59

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=1024, height=768" />

<title>Bing Maps Metro style app sample</title>

<!-- WinJS references -->

<link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet">

<script src="//Microsoft.WinJS.0.6/js/base.js"></script>

<script src="//Microsoft.WinJS.0.6/js/ui.js"></script>

<!-- Bing Maps references -->

<script type="text/javascript" src="ms-

appx:///Bing.Maps.JavaScript//js/veapicore.js"></script>

<script type="text/javascript" src="ms-

appx:///Bing.Maps.JavaScript//js/veapivenuemaps.js"></script>

<link href="/css/default.css" rel="stylesheet">

<script src="/js/default.js"></script>

</head>

<body>

<div id="content">

<div id="header"> </div>

<div id="mapdiv"> </div>

<button id="setView">Bird’s eye mode</button>

<button id="panRight">Pan right</button>

<button id="pushpin">Pushpin</button>

<button id="polygon">Polygon</button>

<button id="infobox">Infobox</button>

<button id="tilelayer">Display tile layer</button>

<button id="vm">Display venue map</button>

Page 60: Bing Maps Ajax Controls Dk 70

60

<button id="clear">Clear map</button>

<button id="close">Close app</button>

</div>

</body>

</html>

// default.js

(function () {

var app = WinJS.Application;

// This function responds to all application activations.

app.onactivated = function (eventObject) {

if (eventObject.detail.kind ===

Windows.ApplicationModel.Activation.ActivationKind.launch) {

WinJS.UI.processAll();

}

};

app.start();

// Set view API to show bird’s eye view

function setView()

{

map.setView({ center: new Microsoft.Maps.Location(47.6215, -122.349329),

mapTypeId: Microsoft.Maps.MapTypeId.auto, zoom: 18 });

}

// Set view API to pan map

function pan(x, y)

{

var mapCenter = map.getCenter();

Page 61: Bing Maps Ajax Controls Dk 70

61

var win8 = (typeof WinJS !== undefined);

var pos = map.tryPixelToLocation(new Microsoft.Maps.Point(map.getWidth() / 2 + x,

map.getHeight() / 2 - (y - 1)), Microsoft.Maps.PixelReference.control);

mapCenter.latitude += pos.latitude - mapCenter.latitude;

mapCenter.longitude += pos.longitude - mapCenter.longitude;

map.setView({ center: mapCenter });

}

// Add pin to map

function addPushpin()

{

var MM = Microsoft.Maps;

var pushpin = new MM.Pushpin(map.getCenter(), null);

map.entities.push(pushpin);

}

// Add polygon to map

function addPolygon()

{

var MM = Microsoft.Maps;

// Create the locations

var location1 = new MM.Location(20,-20);

var location2 = new MM.Location(20,20);

var location3 = new MM.Location(-20,20);

var location4 = new MM.Location(-20,-20);

// Create a polygon

var vertices = new Array(location1, location2, location3, location4,

location1);

var polygoncolor = new MM.Color(100,100,0,100);

var polygon = new MM.Polygon(vertices,{fillColor: polygoncolor, strokeColor:

polygoncolor});

// Add the shape to the map

Page 62: Bing Maps Ajax Controls Dk 70

62

map.entities.push(polygon)

// Set the view

map.setView({bounds: MM.LocationRect.fromLocations(vertices)});

}

// Add infobox to map

function addInfobox()

{

var MM = Microsoft.Maps;

var infobox = new MM.Infobox(map.getCenter(), {

height: 100, title: 'Infobox Title', description: 'Description comes here',

titleClickHandler: function () { }, actions: [{ label: 'Action1', eventHandler: function

() { } }, { label: 'Action2', eventHandler: function () { } }]

});

map.entities.push(infobox);

}

// Add tile layer to map

function addtilelayer()

{

var options = { uriConstructor:

'http://www.microsoft.com/maps/isdk/ajax/layers/lidar/{quadkey}.png', width: 256, height:

256 };

var tileSource = new Microsoft.Maps.TileSource(options);

var tilelayer = new Microsoft.Maps.TileLayer({ mercator: tileSource });

map.entities.push(tilelayer);

// Center map to show tile layer

map.setView({ center: new Microsoft.Maps.Location(48.03, -122.42), zoom: 11 });

}

Page 63: Bing Maps Ajax Controls Dk 70

63

// Display venue map

function addVM()

{

Microsoft.Maps.loadModule('Microsoft.Maps.VenueMaps', { callback: vmCallback });

}

// venue map module callback

function vmCallback()

{

venueMapFactory = new Microsoft.Maps.VenueMaps.VenueMapFactory(map);

venueMapFactory.create({

venueMapId: 'hcl-timessquare',

success: successful,

error: err

});

}

// error callback for venue map

function err(errorCode, args)

{

var message = 'Error while loading venue map. Errorcode : ' + errorCode;

var md = new Windows.UI.Popups.MessageDialog(message);

md.showAsync();

}

// success callback from venue map callback

function successful(vm, args)

{

venueMap = vm;

venueMap.show();

map.setView(venueMap.bestMapView);

}

// Clear map entities

Page 64: Bing Maps Ajax Controls Dk 70

64

function clearMap()

{

map.entities.clear();

}

// Close app

function close()

{

window.close();

}

function initialize()

{

Microsoft.Maps.loadModule('Microsoft.Maps.Map', { callback: initMap });

document.getElementById("setView").addEventListener("click", setView, false);

document.getElementById("panRight").addEventListener("click", function () {

pan(16, 0) }, false);

document.getElementById("pushpin").addEventListener("click", addPushpin, false);

document.getElementById("polygon").addEventListener("click", addPolygon, false);

document.getElementById("clear").addEventListener("click", clearMap, false);

document.getElementById("close").addEventListener("click", close, false);

document.getElementById("infobox").addEventListener("click", addInfobox, false);

document.getElementById("vm").addEventListener("click", addVM, false);

document.getElementById("tilelayer").addEventListener("click", addtilelayer,

false);

}

document.addEventListener("DOMContentLoaded", initialize, false);

})();

var map;

function initMap() {

try {

var mapOptions =

Page 65: Bing Maps Ajax Controls Dk 70

65

{

credentials: 'Bing Maps Key',

center: new Microsoft.Maps.Location(40.71, -74.00),

mapTypeId: Microsoft.Maps.MapTypeId.road,

zoom: 8

};

map = new Microsoft.Maps.Map(document.getElementById("mapdiv"), mapOptions);

}

catch (e) {

var md = new Windows.UI.Popups.MessageDialog(e.message);

md.showAsync();

}

}

See Also Bing Maps SDK for Metro style apps

Developing basic Metro style apps

Microsoft.Maps API Reference

This section contains reference documentation for the Microsoft.Maps API, which contains the

core types of the Bing Maps AJAX Control 7.0.

In This Section

Data Structures

AltitudeReference Enumeration

Location Class

LocationRect Class

Point Class

Page 66: Bing Maps Ajax Controls Dk 70

66

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

InfoboxType Enumeration

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

Page 67: Bing Maps Ajax Controls Dk 70

67

PositionOptions Object

Dynamic Module Loading

Module Loading Methods

AltitudeReference Enumeration

Defines the reference point from which the altitude is measured.

Constants

Name Description

ground The altitude is measured from the ground level.

ellipsoid The altitude is measured from the WGS 84

ellipsoid of the Earth.

Methods

Name Definition Return Value Description

isValid isValid(reference:AltitudeReference) boolean Determines if the

specified reference is a

supported

AltitudeReference.

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

Page 68: Bing Maps Ajax Controls Dk 70

68

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

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

var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), mapOptions);

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

Page 69: Bing Maps Ajax Controls Dk 70

69

AnimationVisibility Enumeration

Defines a tile layer‟s 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.

hide The tile layer is not displayed during animation.

show The tile layer is displayed during animations.

This option may impact performance on older

browsers.

Color Class

Represents a color.

Constructor

Name Definition Description

Color Color(a:number, r:number,

g:number, b:number)

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 number The opacity of the color. The

Page 70: Bing Maps Ajax Controls Dk 70

70

Name Type Description

range of valid values is 0 to 255.

r number The red value of the color. The

range of valid values is 0 to 255.

g number The green value of the color.

The range of valid values is 0 to

255.

b number The blue value of the color. The

range of valid values is 0 to 255.

Static Methods

Name Definition Return Value Description

clone clone(color:Color) Color Creates a copy of the

Color object.

fromHex fromHex(hex:string) Color Converts the specified

hex string to a Color.

Methods

Name Definition Return Value Description

clone clone() Color Returns a copy of the

Color object.

getOpacity getOpacity() number Returns the opacity of

the Color as a value

between 0 (a=0) and 1

(a=255).

toHex toHex() string 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.

Page 71: Bing Maps Ajax Controls Dk 70

71

Name Definition Return Value Description

toString toString() string Converts the Color

object to a 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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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

Page 72: Bing Maps Ajax Controls Dk 70

72

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

// Add the shape to the map

map.entities.push(line);

}

function SetPolygonColor()

{

// Get the polyline entity.

var mapLine = map.entities.get(0);

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

}

Page 73: Bing Maps Ajax Controls Dk 70

73

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.

altitude number The altitude of the location.

Page 74: Bing Maps Ajax Controls Dk 70

74

Name Type Description

altitudeAccuracy number The accuracy, in meters, of

the altitude value.

heading number The direction of travel of the

hosting device.

latitude number The latitude of the location.

longitude number The longitude of the location.

speed number 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 Description

EntityCollection EntityCollection(options?:EntityCollectionOptions) Initializes a new

instance of the

EntityCollection

class.

Methods

Name Definition Return

Value

Description

clear clear() None Removes all

entities from the

Page 75: Bing Maps Ajax Controls Dk 70

75

Name Definition Return

Value

Description

collection.

get get(index:number) Entity* Returns the entity

at the specified

index in the

collection.

getLength getLength() number Returns the

number of entities

in the collection.

getVisible getVisible() boolean Returns whether

the entity

collection is visible

on the map.

getZIndex getZIndex() number Gets the z-index

of the entity

collection with

respect to other

items on the map.

indexOf indexOf(entity:Entity*) number Returns the index

of the specified

entity in the

collection. If the

entity is not found

in the collection, -1

is returned.

insert insert(entity:Entity*, index:number) None Inserts the

specified entity

into the collection

at the given index.

pop pop() Entity* Removes the last

entity from the

collection and

returns it.

push push(entity:Entity*) None Adds the specified

entity to the last

position in the

collection.

Page 76: Bing Maps Ajax Controls Dk 70

76

Name Definition Return

Value

Description

remove remove(entity:Entity*) Entity* Removes the

specified entity

from the collection

and returns it.

removeAt removeAt(index:number) Entity* Removes the

entity at the

specified index

from the collection

and returns it.

setOptions setOptions(options:EntityCollectionOptions) None Sets the options

for the entity

collection.

toString toString() string Converts the

EntityCollection

object to a string.

* An Entity can be any one of the following types: Infobox, Polygon, Polyline, Pushpin, TileLayer,

or EntityCollection.

Events

Name Arguments Description

entityadded object: {collection:

EntityCollection, entity:Entity*}

Occurs when one of the

following happens:

An entity is added to the

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.

Page 77: Bing Maps Ajax Controls Dk 70

77

Name Arguments Description

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

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>

Page 78: Bing Maps Ajax Controls Dk 70

78

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var pinTotal = 0;

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

Page 79: Bing Maps Ajax Controls Dk 70

79

// Add the pushpin

map.entities.push(pin);

}

}

function removePin(e)

{

var indexOfPinToRemove = map.entities.indexOf(e.target);

map.entities.removeAt(indexOfPinToRemove);

}

</script>

</head>

<body onload="GetMap();">

<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

Page 80: Bing Maps Ajax Controls Dk 70

80

Name Type Description

bubble boolean A boolean indicating whether to set the

options of all entities when an option of an

entity within the collection is set. The default

value is true. For example, in an entity

collection composed of multiple polygons, if

this property is set to true setting one

polygon‟s fill color to red changes the fill

color of all of the other polygons in the entity

collection to red.

This property is only available when

the

Microsoft.Maps.AdvancedShapes

module is loaded.

visible boolean A boolean indicating whether the entity

collection is visible on the map.

zIndex number The z-index of the entity collection with

respect to other items on the 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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

function GetMap()

Page 81: Bing Maps Ajax Controls Dk 70

81

{

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

// Add the pushpin

map.entities.push(pin);

}

}

function hideAllPins(){

// Hide all the entities on the map

map.entities.setOptions({visible:false});

}

function showAllPins(){

// Show all the entities on the map

Page 82: Bing Maps Ajax Controls Dk 70

82

map.entities.setOptions({visible:true});

}

</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 addHandler(target:object,

eventName:string,

handler:function)

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){ //Handle the

event });

addThrottledHan

dler

addThrottledHandler(target:o

bject, eventName:string,

handler:function,

throttleInterval:number)

object Attaches the handler for the event

that is thrown by the target, where

the minimum interval between

events (in milliseconds) is

Page 83: Bing Maps Ajax Controls Dk 70

83

Name Definition Return

Value

Description

specified in the throttleInterval

parameter. The last occurrence of

the event is called after the

specified throttleInterval.

hasHandler hasHandler(target:object,

eventName:string)

boolea

n

Checks if the target has any

attached event handler.

invoke invoke(target:object,

eventName:string, args:object)

None Invokes an event on the target.

This causes all handlers for the

specified eventName to be called.

removeHandler removeHandler(handlerId:

object)

None Detaches the specified handler

from the event. The handlerId is

returned by the addHandler and

addThrottledHandler methods.

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var infobox = null;

function GetMap()

{

// Initialize the map

Page 84: Bing Maps Ajax Controls Dk 70

84

map = new Microsoft.Maps.Map(document.getElementById("myMap"),

{credentials:"Bing Maps Key"});

// Retrieve the location of the map center

var center = map.getCenter();

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

}

function showInfobox()

{

infobox.setOptions({visible:true});

}

function hideInfobox()

{

infobox.setOptions({visible:false});

}

Page 85: Bing Maps Ajax Controls Dk 70

85

</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 user‟s current location.

This functionality is only available on browsers that support the W3C GeoLocation API.

Constructor

Name Definition Description

GeoLocationProvider GeoLocationProvider(map:Map) Initializes a new instance of

the GeoLocationProvider

class.

Methods

Name Definition Retur

n

Value

Description

addAccuracyCircle addAccuracyCircle(center:Location,

radiusInMeters:number,

segments:number,

options:PositionCircleOptions)

None Renders a geo

location accuracy

circle on the map.

The accuracy

circle is created

with the center at

the specified

location, using the

given

radiusInMeters,

and with the

Page 86: Bing Maps Ajax Controls Dk 70

86

Name Definition Retur

n

Value

Description

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.

getCurrentPosition getCurrentPosition(options:PositionOptio

ns)

None Obtains the user‟s

current location

and displays it on

the map.

The

accuracy

of the

user

location

obtained

using this

method

varies

widely

dependin

g on the

desktop

browser

or mobile

device of

the

Page 87: Bing Maps Ajax Controls Dk 70

87

Name Definition Retur

n

Value

Description

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

e

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

<head>

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

Page 88: Bing Maps Ajax Controls Dk 70

88

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

function GetMap()

{

// Set the map options

var mapOptions = {credentials:"Bing Maps Key"};

// Initialize the map

var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),

mapOptions);

// Initialize the location provider

var geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map);

// Get the user's current location

geoLocationProvider.getCurrentPosition();

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:400px; height:400px;"></div>

</body>

</html>

See Also PositionOptions Object

Page 89: Bing Maps Ajax Controls Dk 70

89

Infobox Class

Represents an info box on the map. You can use this class to create pop-up balloons for

pushpins.

Constructor

Name Definition Description

Infobox Infobox(location:Location,

options?:InfoboxOptions)

Initializes a new instance of

the Infobox class.

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.

getAnchor getAnchor() Point 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.

getDescription getDescription() string Returns the string that is printed

inside the infobox.

getHeight getHeight() number Returns the height of the info

box.

getHtmlContent getHtmlContent() string Returns the info box as HTML.

getId getId() string Returns the ID of the info box.

getLocation getLocation() Location Returns the location on the map

where the infobox‟s anchor is

attached.

getOffset getOffset() number Returns the amount the infobox

Page 90: Bing Maps Ajax Controls Dk 70

90

Name Definition Return

Value

Description

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.

getOptions getOptions() InfoboxOpti

ons

Returns the info box options.

getShowCloseB

utton

getShowCloseButton() boolean Returns a boolean indicating

whether the infobox close button

is shown.

getShowPointer getShowPointer() boolean Returns a boolean indicating

whether the infobox is drawn

with a pointer.

getTitle getTitle() string Returns a string that is the title of

the info box.

getTitleAction getTitleAction() Object 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.

getTitleClickHan

dler

getTitleClickHandler() string Returns the name of the function

to call when the title of the info

box is clicked.

getVisible getVisible() boolean 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.

getWidth getWidth() number Returns the width of the infobox.

getZIndex getZIndex() number Returns the z-index of the

infobox with respect to other

items on the map.

Page 91: Bing Maps Ajax Controls Dk 70

91

Name Definition Return

Value

Description

setHtmlContent setHtmlContent(content:stri

ng)

None Sets the HTML content of the

infobox. You can use this

method to change the look of the

infobox. Note that info box

options are ignored if custom

HTML is set. Also, 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;border-

width:medium; border-

color:DarkOrange; min-

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

klasdjfkl</a></div>');

setLocation setLocation(location:Locati None Sets the location on the map

where the anchor of the infobox

Page 92: Bing Maps Ajax Controls Dk 70

92

Name Definition Return

Value

Description

on) is attached.

setOptions setOptions(options:Infobox

Options)

None Sets options for the infobox.

toString toString() string Converts the Infobox object to a

string.

Events

Name Arguments Description

click eventArgs:MouseEventArgs Occurs when the mouse is

used to click the infobox.

entitychanged object: {entity:Entity} Occurs when the location

of the infobox or any of the

infobox options change.

mouseenter eventArgs:MouseEventArgs Occurs when the mouse

cursor enters the area

covered by the infobox.

mouseleave eventArgs:MouseEventArgs Occurs when the mouse

cursor leaves the area

covered by the infobox.

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>

Page 93: Bing Maps Ajax Controls Dk 70

93

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var pinInfobox = null;

function GetMap()

{

// Initialize the map

map = new Microsoft.Maps.Map(document.getElementById("myMap"),

{credentials:"Bing Maps Key"});

// Retrieve the location of the map center

var center = map.getCenter();

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

Page 94: Bing Maps Ajax Controls Dk 70

94

Microsoft.Maps.Events.addHandler(map, 'viewchange', hideInfobox);

// Add the pushpin and info box to the map

map.entities.push(pin);

map.entities.push(pinInfobox);

}

function displayInfobox(e)

{

pinInfobox.setOptions({ visible:true });

}

function hideInfobox(e)

{

pinInfobox.setOptions({ visible: false });

}

</script>

</head>

<body onload="GetMap();">

<div id='myMap' style="position:relative; width:500px; height:500px;"></div>

</html>

InfoboxOptions Object

Represents the options for an info box.

Properties

Page 95: Bing Maps Ajax Controls Dk 70

95

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

description string The string displayed inside the info box.

height number The height of the info box. The default

value is 126.

htmlContent string The HTML that represents the info box.

Note that info box options are ignored if

custom HTML is set. Also, 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 string The ID associated with the info box.

location Location The location on the map where the info

box‟s anchor is attached.

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

Page 96: Bing Maps Ajax Controls Dk 70

96

Name Type Description

shifted from its location. The default

offset value is (0,0), which means there

is no offset.

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

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 string The title of the info box.

titleAction Object 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).

titleClickHandler string The name of the function to call 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.

typeName InfoboxType The style of the info box. The default

value is standard.

To get the latest Bing Maps design,

load the

Microsoft.Maps.Themes.BingTheme

module before creating your info box. In

addition, when the BingTheme module

is loaded, typeName can be set to mini

Page 97: Bing Maps Ajax Controls Dk 70

97

Name Type Description

to use the mini info box type.

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.

width number The width of the info box. The default

value is 256.

zIndex number The z-index of the info box with respect

to other items on the 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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

function GetMap()

{

// Initialize the map

map = new Microsoft.Maps.Map(document.getElementById("myMap"),

{credentials:"Bing Maps Key"});

Page 98: Bing Maps Ajax Controls Dk 70

98

// Retrieve the location of the map center

var center = map.getCenter();

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

// Add the info box to the map

map.entities.push(myInfobox);

}

function InfoboxHandler()

{

alert("Infobox title was clicked!");

}

</script>

</head>

<body onload="GetMap();">

<div id='myMap' style="position:relative; width:500px; height:500px;"></div>

</html>

Page 99: Bing Maps Ajax Controls Dk 70

99

See Also Infobox Class

InfoboxType Enumeration

Contains info box styles. To get the latest Bing Maps design, load the

Microsoft.Maps.Themes.BingTheme module before creating your info box.

Constants

Name Description

mini A smaller info box with space for a title.

standard The default info box style. This standard info

box makes space for a title, title link,

description, and other links if they are specified.

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

function GetMap()

{

Page 100: Bing Maps Ajax Controls Dk 70

100

Microsoft.Maps.loadModule('Microsoft.Maps.Themes.BingTheme', { callback:

themesModuleLoaded });

}

function themesModuleLoaded()

{

var mapCenter = new Microsoft.Maps.Location(47.5, -122.3);

map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:

"Bing Maps Key", center: mapCenter, zoom: 9, theme: new Microsoft.Maps.Themes.BingTheme()

});

// Create an info box

var infoboxOptions = {width:300,

height: 100,

title: "Mini Info Box",

typeName: new Microsoft.Maps.InfoboxType.mini;

showPointer: true,

offset: new Microsoft.Maps.Point(-100,0)};

var myInfobox = new Microsoft.Maps.Infobox(center, infoboxOptions);

// Add the info box to the map

map.entities.push(myInfobox);

}

Page 101: Bing Maps Ajax Controls Dk 70

101

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:600px; height:600px;"></div>

</body>

</html>

KeyEventArgs Object

Contains the arguments for keyboard events.

Properties

Name Type Description

altKey boolean A boolean indicating if the ALT

key was pressed.

ctrlKey boolean A boolean indicating if the

CTRL key was pressed.

eventName string The event that occurred.

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

keyCode string The ASCII character code that

identifies the keyboard key that

was pressed.

originalEvent object The original browser event.

shiftKey boolean A boolean indicating if the

SHIFT key was pressed.

Example <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Page 102: Bing Maps Ajax Controls Dk 70

102

<html>

<head>

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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.

var center = map.getCenter();

var pin = new Microsoft.Maps.Pushpin(center);

map.entities.push(pin);

Page 103: Bing Maps Ajax Controls Dk 70

103

}

}

</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 Map labels are not shown on top of imagery.

visible Map labels are shown on top of imagery.

Methods

Name Definition Return Value Description

isValid isValid(labelOverlay:LabelOverlay) boolean Determines whether

the specified

labelOverlay is a

supported

LabelOverlay.

Example <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Page 104: Bing Maps Ajax Controls Dk 70

104

<html>

<head>

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

function GetMap()

{

// Initialize the map options. In this case,

// turn the label overlay on a bird's eye map off.

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

}

//Load the map

var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),

mapOptions );

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:400px; height:400px;"></div>

</body>

Page 105: Bing Maps Ajax Controls Dk 70

105

</html>

Location Class (AJAX)

Contains the altitude and coordinate values of a location on the map.

Constructor

Name Definition Description

Location Location(latitude:number,

longitude:number, altitude?:number,

altitudeReference?:AltitudeReference)

Initializes a new instance of

the Location class. The

altitude and

altitudeReference

parameters default to

undefined.

Properties

Name Type Description

altitude number The altitude of the location.

altitudeReference AltitudeReference The reference from which

the altitude is measured.

latitude number The latitude of the location.

longitude number The longitude of the

location.

Static Methods

Name Definition Return

Value

Description

areEqual areEqual(location1:Location,

location2:Location)

boolean Determines if

the specified

Location

objects are

Page 106: Bing Maps Ajax Controls Dk 70

106

Name Definition Return

Value

Description

equal.

normalizeLongitude normalizeLongitude(longitude:number) number Normalizes

the specified

longitude so

that it is

between -180

and 180.

Methods

Name Definition Return Value Description

clone clone() Location Returns a copy of the

Location object.

toString toString() string Converts the Location

object to a 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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

function GetMap()

Page 107: Bing Maps Ajax Controls Dk 70

107

{

map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:

"Bing Maps Key"});

}

function SetLocation()

{

// Parse the input string

var latLongArray = (document.getElementById("txtlatlong").value).split(",");

// Retrieve the latitude and longitude values- normalize the longitude value

var latVal = parseInt(latLongArray[0]);

var longVal =

Microsoft.Maps.Location.normalizeLongitude(parseInt(latLongArray[1]));

// Set the map center

map.setView({center:new Microsoft.Maps.Location(latVal, longVal)});

}

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

Page 108: Bing Maps Ajax Controls Dk 70

108

Constructor

Name Definition Description

LocationRect LocationRect(center:Location,

width:number, height:number)

Initializes a new instance

of the LocationRect class.

Properties

Name Type Description

center Location The location that defines the

center of the rectangle.

height number The height, in degrees, of the

rectangle.

width number The width, in degrees, of the

rectangle.

Static Methods

Name Definition Return

Value

Description

fromCorn

ers

fromCorners(northwest:Loc

ation, southeast:Location)

Location

Rect

Returns a LocationRect using the

specified locations for the northwest and

southeast corners.

fromEdge

s

fromEdges(north:number,

west:number,

south:number,

east:number,

altitude:number,

altitudeReference:Altitude

Reference)

Location

Rect

Returns a LocationRect using the

specified northern and southern latitudes

and western and eastern longitudes for

the rectangle boundaries.

fromLocat

ions

fromLocations(list of

locations/array)

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

Page 109: Bing Maps Ajax Controls Dk 70

109

Name Definition Return

Value

Description

ons(location1, location2, location3);

To provide an array of locations:

var locations = [location1, location2,

location3];

Microsoft.Maps.LocationRect.fromLocati

ons(locations);

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 Return Value Description

clone clone() LocationRect Returns a copy of

the LocationRect

object.

contains contains(location:Location) boolean Returns whether

the specified

Location is within

the LocationRect.

getEast getEast() number Returns the

longitude that

defines the

eastern edge of

the LocationRect.

getNorth getNorth() number Returns the

latitude that

defines the

northern edge of

the LocationRect.

getNorthwest getNorthwest() Location Returns the

Location that

defines the

northwest corner

Page 110: Bing Maps Ajax Controls Dk 70

110

Name Definition Return Value Description

of the

LocationRect.

getSouth getSouth() number Returns the

latitude that

defines the

southern edge of

the LocationRect.

getSoutheast getSoutheast() Location Returns the

Location that

defines the

southeast corner

of the

LocationRect.

getWest getWest() number Returns the

latitude that

defines the

western edge of

the LocationRect.

intersects intersects(rect:LocationRect) boolean Returns whether

the specified

LocationRect

intersects with this

LocationRect.

toString toString() string Converts the

LocationRect

object to a 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">

Page 111: Bing Maps Ajax Controls Dk 70

111

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

function GetMap()

{

map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:

"Bing Maps Key"});

var viewRect = Microsoft.Maps.LocationRect.fromCorners(new

Microsoft.Maps.Location(40,-120), new Microsoft.Maps.Location(35,-115));

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

Page 112: Bing Maps Ajax Controls Dk 70

112

Name Definition Description

Map Map(containerElement:node,

options?:MapOptions or

ViewOptions)

Initializes a new instance of

the Map class.

Properties

Name Type Description

entities EntityCollection The map‟s entities. Use this

property to add or remove

entities from the map.

Static Methods

Name Definition Return Value Description

getVersion getVersion() string Returns the version of

the map control.

Methods

Name Definition Return Value Description

blur blur() None Removes focus from the map

control so that it does not

respond to keyboard events.

dispose dispose() None Deletes the Map object and

releases any associated

resources.

focus focus() None Applies focus to the map

control so that it responds to

keyboard events.

getBounds getBounds() LocationRect Returns the location rectangle

that defines the boundaries of

the current map view.

Page 113: Bing Maps Ajax Controls Dk 70

113

Name Definition Return Value Description

getCenter getCenter() Location Returns the location of the

center of the current map

view.

getCopyrights getCopyrights(callback:fu

nction)

string[] Returns to the specified

callback an array of strings

representing the attributions of

the imagery currently

displayed on the map.

getCredentials getCredentials(callback:f

unction)

None 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) { /* Valid session

Id. Use it to call REST

service */ }

});

getHeading getHeading() number Returns the heading of the

current map view.

getHeight getHeight() number Returns the height of the map

control.

getImageryId getImageryId() string Returns the string that

represents the imagery

currently displayed on the

map.

getMapTypeId getMapTypeId() string Returns a string that

represents the current map

type displayed on the map.

Valid map types are listed in

the MapTypeId Enumeration

topic.

getMetersPerPix

el

getMetersPerPixel() number Returns the current scale in

meters per pixel of the center

of the map.

Page 114: Bing Maps Ajax Controls Dk 70

114

Name Definition Return Value Description

getMode getMode() MapMode Returns the current map

mode.

getModeLayer getModeLayer() Node Returns the map‟s mode node.

getOptions getOptions() MapOptions 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.

getPageX getPageX() number Returns the x coordinate of the

top left corner of the map

control, relative to the page.

getPageY getPageY() number Returns the y coordinate of the

top left corner of the map

control, relative to the page.

getRootElement getRootElement() Node Returns the map‟s root node.

getTargetBounds getTargetBounds() LocationRect Returns the location rectangle

that defines the boundaries of

the view to which the map is

navigating.

getTargetCenter getTargetCenter() Location Returns the center location of

the view to which the map is

navigating.

getTargetHeadin

g

getTargetHeading() number Returns the heading of the

view to which the map is

navigating.

getTargetMeters

PerPixel

getTargetMetersPerPixel() number Returns the scale in meters

per pixel of the center of the

view to which the map is

navigating.

getTargetZoom getTargetZoom() number Returns the zoom level of the

view to which the map is

navigating.

getUserLayer getUserLayer() Node Returns the map‟s user node.

Page 115: Bing Maps Ajax Controls Dk 70

115

Name Definition Return Value Description

getViewportX getViewportX() number Returns the x coordinate of the

viewport origin (the center of

the map), relative to the page.

getViewportY getViewportY() number Returns the y coordinate of the

viewport origin (the center of

the map), relative to the page.

getWidth getWidth() number Returns the width of the map

control.

getZoom getZoom() number Returns the zoom level of the

current map view.

getZoomRange getZoomRange() object:{min:nu

mber, max:

number}

Returns the range of valid

zoom levels for the current

map view.

isDownloadingTil

es

isDownloadingTiles() boolean Returns a boolean indicating

whether map imagery tiles are

currently being downloaded.

isMercator isMercator() boolean Returns a boolean indicating

whether the map is in a

regular Mercator nadir mode.

isRotationEnable

d

isRotationEnabled() boolean Returns true if the current map

type allows the heading to

change; false if the display

heading is fixed.

setMapType setMapType(mapTypeId:strin

g)

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

setOptions setOptions({height:numbe

r, width: number})

None Sets the height and width of

the map.

setView setView(options:ViewOptio

ns)

None Sets the map view based on

the specified options.

tryLocationToPix

el

tryLocationToPixel(locati

on:Location |Location[],

reference?:PixelReference

null, Point, or

Point[]

Converts a specified Location

to a Point on the map relative

to the specified

Page 116: Bing Maps Ajax Controls Dk 70

116

Name Definition Return Value Description

) PixelReference. If reference is

not specified,

PixelReference.viewport is

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:

Point |Point[],

reference?:PixelReference

)

null, Location,

or Location[]

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

click eventArgs:MouseEventArgs Occurs when the mouse is

used to click the map.

copyrightchanged None Occurs when the copyright

of the map changes.

dblclick eventArgs:MouseEventArgs Occurs when the mouse is

used to double click the

map.

Page 117: Bing Maps Ajax Controls Dk 70

117

Name Arguments Description

imagerychanged None Occurs when the underlying

imagery used by the map

changes. This is different

from the maptypechanged

event, which occurs when

the map type being used is

changed.

keydown eventArgs:KeyEventArgs Occurs when a keyboard

key is pressed down.

keypress eventArgs:KeyEventArgs Occurs when a keyboard

key is pressed.

keyup eventArgs:KeyEventArgs Occurs when a keyboard

key that is pressed down is

released.

maptypechanged None Occurs when the map type

changes.

mousedown eventArgs:MouseEventArgs Occurs when the left mouse

button is pressed when the

mouse cursor is over the

map.

mousemove eventArgs:MouseEventArgs Occurs when the mouse

cursor moves over the map.

mouseout eventArgs:MouseEventArgs Occurs when the mouse

cursor moves out of the area

covered by the map.

mouseover eventArgs:MouseEventArgs Occurs when the mouse is

over the map.

mouseup eventArgs:MouseEventArgs Occurs when the left mouse

button is lifted up when the

mouse cursor is over the

map.

mousewheel eventArgs:MouseEventArgs Occurs when the mouse

wheel is used when the

mouse cursor is over the

map.

rightclick eventArgs:MouseEventArgs Occurs when the right

Page 118: Bing Maps Ajax Controls Dk 70

118

Name Arguments Description

mouse button is used to

click the map.

targetviewchanged None Occurs when the view

towards which the map is

navigating changes.

tiledownloadcomplete None Occurs when all the map

tiles of a map view have

loaded.

viewchange None Occurs for every frame of a

map view change.

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

viewchangestart None Occurs when the map view

starts changing.

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

Page 119: Bing Maps Ajax Controls Dk 70

119

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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>

MapMode Class (AJAX)

Represents a map mode.

Mercator Map Mode Methods The following methods are available for the MapTypeId values aerial, auto, birdseye,

collinsBart, mercator, ordnanceSurvey, and road.

Page 120: Bing Maps Ajax Controls Dk 70

120

Name Definition Retu

rn

Valu

e

Description

getDrawShapesIn

SingleLayer

getDrawShapesInSingleLayer() bool

ean

Gets whether the mode

should draw shapes

(polygons, polylines, or

pushpins) in a single layer,

independent of the

EntityCollection order.

setDrawShapesInS

ingleLayer

setDrawShapesInSingleLayer(drawInS

ingleLayer:boolean)

Non

e

Sets whether the mode

should draw shapes

(polygons, polylines, or

pushpins) in a single layer,

independent of the

EntityCollection order. A

shape is drawn by default in

its own layer, but if one

shape covers another shape,

then the top-layered shape

event is what is thrown. You

can prevent this issue by

calling

setDrawShapesInSingleLayer

(true).

setViewChangeEn

dDelay

setViewChangeEndDelay(delay:numb

er)

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().setViewChang

eEndDelay(1000);

Page 121: Bing Maps Ajax Controls Dk 70

121

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.

This property setting only takes effect if

the Microsoft.Maps.Overlays.Style

module is loaded.

disableBirdseye boolean A boolean indicating whether to disable

the bird‟s eye map type. The default

value is false. If this property is set to

true, bird‟s 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 map‟s response to keyboard

input. The default value is false.

disableMouseInput boolean A boolean value indicating whether to

Page 122: Bing Maps Ajax Controls Dk 70

122

Name Type Description

disable the map‟s response to mouse

input. The default value is false.

disablePanning boolean A boolean value indicating whether to

disable the user‟s ability to pan the

map. The default value is false.

disableTouchInput boolean A boolean value indicating whether to

disable the map‟s response to touch

input. The default value is false.

disableUserInput boolean A boolean value indicating whether to

disable the map‟s response to any user

input. The default value is false.

disableZooming boolean A boolean value indicating whether to

disable the user‟s ability to zoom in or

out. The default value is false.

enableClickableLogo boolean A boolean value indicating whether the

BingTM

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 to

enable the BingTM

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

Page 123: Bing Maps Ajax Controls Dk 70

123

Name Type Description

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.

inertiaIntensity number 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 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 location‟s 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

Page 124: Bing Maps Ajax Controls Dk 70

124

Name Type Description

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

theme Object A theme object specifying the theme to

use for the design of the map. To get

the latest Bing Maps design, load the

Microsoft.Maps.Themes.BingTheme

module and assign a BingTheme

object to this property.

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.

useInertia boolean A boolean value indicating whether to

use the inertia animation effect during

map navigation. The default value is

true.

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

Page 125: Bing Maps Ajax Controls Dk 70

125

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

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

// Initialize the map

var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),

mapOptions);

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative;"></div>

Page 126: Bing Maps Ajax Controls Dk 70

126

</body>

</html>

MapTypeId Enumeration

Contains identifiers for the imagery displayed on the map.

Constants

Name Description

aerial The aerial map type is being used.

auto The map is set to choose the best imagery for

the current view.

birdseye The bird‟s eye map type is being used.

collinsBart Collin‟s Bart (mkt=en-gb) map type is being

used.

mercator The Mercator map type is being used. This

setting removes the base map tiles.

ordnanceSurvey Ordnance Survey (mkt=en-gb) map type is

being used.

road The road map type is being used.

Example This code sample sets the map imagery to Collin‟s 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">

Page 127: Bing Maps Ajax Controls Dk 70

127

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0&mkt=en-

gb"></script>

<script type="text/javascript">

function GetMap()

{

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

Module Loading Methods

The following methods allow you to register and load your own modules for use by the map

control. More information about building your own module is in the Building Your Own Module

topic.

Methods

Name Definition Retur

n

Value

Description

loadModule loadModule(moduleKey:string, None Loads the specified registered

Page 128: Bing Maps Ajax Controls Dk 70

128

Name Definition Retur

n

Value

Description

options:function) 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.AdvancedSh

apes

Microsoft.Maps.Directions

Microsoft.Maps.Overlays.Style

Microsoft.Maps.Search

Microsoft.Maps.Themes.Bing

Theme

Microsoft.Maps.Traffic

Microsoft.Maps.VenueMaps

moduleLoade

d

moduleLoaded(moduleKey:string) None Signals that the specified module has

been loaded and if specified, calls

the callback function in loadModule.

Call this method at the end of your

module script.

registerModul

e

registerModule(moduleKey:strin

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

Page 129: Bing Maps Ajax Controls Dk 70

129

Name Definition Retur

n

Value

Description

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>

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map;

function myModuleLoaded()

{

alert("myModule has loaded.");

// Use the function provided by the newly loaded module

var myModule = new MyModule(map);

myModule.HelloWorld();

Page 130: Bing Maps Ajax Controls Dk 70

130

}

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

Page 131: Bing Maps Ajax Controls Dk 70

131

See Also Building Your Own Module

MouseEventArgs Object

Contains the arguments for mouse events.

Properties

Name Type Description

eventName string The event that occurred.

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

isPrimary boolean A boolean indicating if the

primary button (such as the left

mouse button or a tap on a

touch screen) was used.

isSecondary boolean A boolean indicating if the

secondary mouse button (such

as the right mouse button) was

used.

isTouchEvent boolean A boolean indicating whether

the event that occurred was a

touch event.

originalEvent object The original browser event.

pageX number The x-value of the pixel

coordinate on the page of the

mouse cursor.

pageY number The y-value of the pixel

coordinate on the page of the

mouse cursor.

target object The object that fired the event.

Page 132: Bing Maps Ajax Controls Dk 70

132

Name Type Description

targetType string The type of the object that fired

the event. Valid values include

the following: „map‟, „polygon‟,

„polyline‟, or „pushpin‟

wheelDelta number The number of units that the

mouse wheel has changed.

Methods

Name Definition Return Value Description

getX getX() number Returns the x-value of

the pixel coordinate,

relative to the map, of

the mouse.

getY getY() number Returns the y-value of

the pixel coordinate,

relative to the map, of

the mouse.

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

Page 133: Bing Maps Ajax Controls Dk 70

133

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

}

function displayEventInfo(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>

Page 134: Bing Maps Ajax Controls Dk 70

134

PixelReference Enumeration

Contains constants used to show how pixels are defined.

Constants

Name Description

control The pixel is defined relative to the map control‟s

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.

page 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

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 Return Value Description

isValid isValid(reference:PixelReference) boolean Determines whether

the specified

reference is a

supported

PixelReference.

Example <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Page 135: Bing Maps Ajax Controls Dk 70

135

<html>

<head>

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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

}

function displayEventInfo(e) {

if (e.targetType == "map") {

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)

{

Page 136: Bing Maps Ajax Controls Dk 70

136

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 Description

Point Point(x:number, y:number) Initializes a new instance of

the Point class.

Properties

Name Type Description

x number The x value of the coordinate.

y number The y-value of the coordinate.

Page 137: Bing Maps Ajax Controls Dk 70

137

Static Methods

Name Definition Return Value Description

areEqual areEqual(point1:Point,

point2:Point)

boolean Determines if the

specified points are

equal.

clone clone(Point) Point Returns a copy of the

Point object.

Methods

Name Definition Return Value Description

clone clone() Point Returns a copy of the

Point object.

toString toString() string Converts the Point

object into a 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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

function GetMap()

Page 138: Bing Maps Ajax Controls Dk 70

138

{

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

}

function displayEventInfo(e) {

if (e.targetType == "map") {

var point = new Microsoft.Maps.Point(e.getX(), e.getY());

var loc = e.target.tryPixelToLocation(point);

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>

Page 139: Bing Maps Ajax Controls Dk 70

139

Polygon Class (AJAX)

Represents a polygon on the map.

Constructor

Name Definition Description

Polygon Polygon(locations:Location[],

options?:PolygonOptions)

Initializes a new instance of

the Polygon class.

Methods

Name Definition Return Value Description

getFillColor getFillColor() Color Returns the

color of the

inside of the

polygon.

getLocations getLocations() Location[] Returns the

locations that

define the

corners of the

polygon.

getStrokeColor getStrokeColor() Color Returns the

color of the

outline of the

polygon.

getStrokeDashArray getStrokeDashArray() string Returns the

string that

represents the

stroke/gap

sequence

used to draw

the outline of

the polygon.

getStrokeThickness getStrokeThickness() number Returns the

thickness of

the outline of

Page 140: Bing Maps Ajax Controls Dk 70

140

Name Definition Return Value Description

the polygon.

getVisible getVisible() boolean 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.

setLocations setLocations(locations:Location[]) None Sets the

locations that

define the

corners of the

polygon.

setOptions setOptions(options:PolygonOptions) None Sets options

for the

polygon.

toString toString() string Converts the

Polygon object

to a string.

Events

Name Arguments Description

click eventArgs:MouseEventArgs Occurs when the mouse is

used to click the polygon.

dblclick eventArgs:MouseEventArgs Occurs when the mouse is

used to double click the

polygon.

entitychanged object: {entity:Entity} Occurs when the location

of the polygon or any of

the polygon‟s options

change.

Page 141: Bing Maps Ajax Controls Dk 70

141

Name Arguments Description

mousedown eventArgs:MouseEventArgs Occurs when the left

mouse button is pressed

when the mouse is over

the polygon.

mouseout eventArgs:MouseEventArgs Occurs when the mouse

cursor moves out of the

area covered by the

polygon.

mouseover eventArgs:MouseEventArgs Occurs when the mouse is

over the polygon.

mouseup eventArgs:MouseEventArgs Occurs when the left

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

function GetMap()

{

// Initialize the map

Page 142: Bing Maps Ajax Controls Dk 70

142

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

// Add the shape to the map

map.entities.push(polygon)

// Set the view

map.setView({bounds: Microsoft.Maps.LocationRect.fromLocations(vertices)});

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:400px; height:400px;"></div>

</body>

</html>

Page 143: Bing Maps Ajax Controls Dk 70

143

PolygonOptions Object

Represents the options for a polygon.

Properties

Name Type Description

fillColor Color The color of the inside of the polygon.

infobox Infobox The info box associated with this

polygon. If an info box is assigned and

the Microsoft.Maps.Themes.BingTheme

module is loaded, then the info box

appears when the hover or click events

of the polygon occur.

strokeColor Color The color of the outline of the polygon.

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.

strokeThickness number The thickness of the outline of the

polygon.

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

Example <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

Page 144: Bing Maps Ajax Controls Dk 70

144

<head>

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

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

// Add the shape to the map

map.entities.push(polygon)

Page 145: Bing Maps Ajax Controls Dk 70

145

// Set the view

map.setView({bounds: Microsoft.Maps.LocationRect.fromLocations(vertices)});

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:400px; height:400px;"></div>

</body>

</html>

Polyline Class

Represents a polyline on the map.

Constructor

Name Definition Description

Polyline Polyline(locations:Location[],

options?:PolylineOptions)

Initializes a new instance of

the Polyline class.

Methods

Name Definition Return Value Description

getLocations getLocations() Location[] Returns the

locations that

define the

polyline.

getStrokeColor getStrokeColor() Color Returns the

color of the

polyline.

getStrokeDashArray getStrokeDashArray() string Returns the

Page 146: Bing Maps Ajax Controls Dk 70

146

Name Definition Return Value Description

string that

represents the

stroke/gap

sequence

used to draw

the polyline.

getStrokeThickness getStrokeThickness() number Returns the

thickness of

the polyline.

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

setLocations setLocations(locations:Location[]) None Sets the

locations that

define the

polyline.

setOptions setOptions(options:PolylineOptions) None Sets options

for the

polyline.

toString toString() string Converts the

Polyline object

to a string.

Events

Name Arguments Description

click eventArgs:MouseEventArgs Occurs when the mouse is

used to click the polyline.

Page 147: Bing Maps Ajax Controls Dk 70

147

Name Arguments Description

dblclick eventArgs:MouseEventArgs Occurs when the mouse is

used to double click the

polyline.

entitychanged object: {entity:Entity} Occurs when the location

of the polyline or any of the

polyline‟s options change.

mousedown eventArgs:MouseEventArgs Occurs when the left

mouse button is pressed

when the mouse is over

the polyline.

mouseout eventArgs:MouseEventArgs Occurs when the mouse

cursor moves out of the

area covered by the

polyline.

mouseover eventArgs:MouseEventArgs Occurs when the mouse is

over the polyline.

mouseup eventArgs:MouseEventArgs Occurs when the left

mouse button is lifted up

when the mouse is over

the polyline.

rightclick eventArgs:MouseEventArgs Occurs when the right

mouse button is used to

click the polyline.

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

Page 148: Bing Maps Ajax Controls Dk 70

148

<script type="text/javascript">

var map = null;

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

// Add the polyline to the map

map.entities.push(line);

}

</script>

</head>

<body onload="GetMap();">

Page 149: Bing Maps Ajax Controls Dk 70

149

<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 Color The color of the polyline.

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

strokeThickness number The thickness of the polyline.

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

Example <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Page 150: Bing Maps Ajax Controls Dk 70

150

<html>

<head>

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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

// Add the polyline to the map

Page 151: Bing Maps Ajax Controls Dk 70

151

map.entities.push(line);

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:400px; height:400px;"></div>

</body>

</html>

Position Class

Represents the position of a user on a map.

Properties

Name Type Description

coords Coordinates The position as a W3C

Coordinates object.

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

Page 152: Bing Maps Ajax Controls Dk 70

152

Name Type Description

polygonOptions PolygonOptions The polygon options for the

geo location accuracy circle.

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

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map;

var geoLocationProvider;

function GetMap()

{

// Set the map options

var mapOptions = {credentials:"Bing Maps Key"};

Page 153: Bing Maps Ajax Controls Dk 70

153

// Initialize the map

map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), mapOptions);

// Initialize the location provider

geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map);

// Get the user's current location

geoLocationProvider.getCurrentPosition({successCallback:drawCircle,

showAccuracyCircle:false});

}

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.

Page 154: Bing Maps Ajax Controls Dk 70

154

Properties

Name Type Description

code number The error code.

Any one of the following error

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

Page 155: Bing Maps Ajax Controls Dk 70

155

Name Type Description

result in a slower response

time.

errorCallback function The function to call when an

error occurs during the user

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 user‟s 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.

showAccuracyCircle boolean A boolean indicating whether

to display the polygon on the

map that shows the accuracy

Page 156: Bing Maps Ajax Controls Dk 70

156

Name Type Description

of the returned geo location.

The default value is true.

successCallback function The function to call when the

user‟s location was

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.

updateMapView boolean A boolean indicating whether

to update the map view with

the best view of the user‟s

location (if the request is

successful). The default value

is true.

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map;

Page 157: Bing Maps Ajax Controls Dk 70

157

function GetMap()

{

// Set the map options

var mapOptions = {credentials:"Bing Maps Key"};

// Initialize the map

map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), mapOptions);

// Initialize the location provider

var geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map);

// Get the user's current location

geoLocationProvider.getCurrentPosition({successCallback:displayCenter});

}

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>

Page 158: Bing Maps Ajax Controls Dk 70

158

Pushpin Class (AJAX)

Defines a pushpin on the map.

Constructor

Name Definition Description

Pushpin Pushpin(location:Location,

options?:PushpinOptions)

Initializes a new instance of

the Pushpin class.

Methods

Name Definition Return Value Description

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

getIcon getIcon() string Returns the

pushpin icon.

getHeight getHeight() number Returns the

height of the

pushpin, which

is the height of

the pushpin icon.

getLocation getLocation() Location Returns the

location of the

pushpin.

getText getText() string Returns the text

associated with

the pushpin.

Page 159: Bing Maps Ajax Controls Dk 70

159

Name Definition Return Value Description

getTextOffset getTextOffset() Point Returns the

amount the text

is shifted from

the pushpin icon.

getTypeName getTypeName() string Returns the type

of the pushpin.

getVisible getVisible() boolean 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.

getWidth getWidth() number Returns the

width of the

pushpin, which

is the width of

the pushpin icon.

getZIndex getZIndex() number Returns the z-

index of the

pushpin with

respect to other

items on the

map.

setLocation setLocation(location:Location) None Sets the location

of the pushpin.

setOptions setOptions(options:PushpinOptions) None Sets options for

the pushpin.

toString toString() string Converts the

Pushpin object

to a string.

Events

Page 160: Bing Maps Ajax Controls Dk 70

160

Name Arguments Description

click eventArgs:MouseEventArgs Occurs when the mouse is

used to click the pushpin.

dblclick eventArgs:MouseEventArgs Occurs when the mouse is

used to double click the

pushpin.

drag object: {entity:Pushpin} Occurs when the pushpin

is being dragged.

dragend eventArgs:MouseEventArgs Occurs when the pushpin

stops being dragged.

dragstart eventArgs:MouseEventArgs Occurs when the pushpin

starts being dragged.

entitychanged object: {entity:Entity} Occurs when the location

of the pushpin or any of

the pushpin‟s options

change.

mousedown eventArgs:MouseEventArgs Occurs when the left

mouse button is pressed

when the mouse is over

the pushpin.

mouseout eventArgs:MouseEventArgs Occurs when the mouse

cursor moves out of the

area covered by the

pushpin.

mouseover eventArgs:MouseEventArgs Occurs when the mouse is

over the pushpin.

mouseup eventArgs:MouseEventArgs Occurs when the left

mouse button is lifted up

when the mouse is over

the pushpin.

rightclick eventArgs:MouseEventArgs Occurs when the right

mouse button is used to

click the pushpin.

Page 161: Bing Maps Ajax Controls Dk 70

161

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

function GetMap()

{

// Initialize the map

map = new Microsoft.Maps.Map(document.getElementById("myMap"),

{credentials:"Bing Maps Key"});

// Retrieve the location of the map center

var center = map.getCenter();

// Add a pin to the center of the map

var pin = new Microsoft.Maps.Pushpin(center, {draggable: true});

// Add a handler to the pushpin drag

Microsoft.Maps.Events.addHandler(pin, 'mouseup', DisplayLoc);

map.entities.push(pin);

}

function DisplayLoc(e){

Page 162: Bing Maps Ajax Controls Dk 70

162

if (e.targetType == 'pushpin'){

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.

draggable boolean A boolean indicating whether the pushpin

can be dragged to a new position with

the mouse.

height number The height of the pushpin, which is the

height of the pushpin icon. The default

value is 39.

Page 163: Bing Maps Ajax Controls Dk 70

163

Name Type Description

icon string The path of the image to use as the

pushpin icon.

infobox Infobox The info box associated with this

pushpin. If an info box is assigned and

the Microsoft.Maps.Themes.BingTheme

module is loaded, then the info box

appears when the hover or click events

of the pushpin occur.

text string The text associated with the pushpin.

textOffset Point The amount the text is shifted from the

pushpin icon. The default value is (0,5).

typeName string 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 standard

pushpin type is used unless the

Microsoft.Maps.Themes.BingTheme

module is loaded, in which case

typeName can be set to „micro‟ to use

the micro pushpin type.

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

width number The width of the pushpin, which is the

width of the pushpin icon. The default

value is 25.

zIndex number The z-index of the pushpin with respect

to other items on the map.

Example This example uses the image below, named “BluePushpin.png”, as the pushpin icon.

Page 164: Bing Maps Ajax Controls Dk 70

164

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

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

function GetMap()

{

// Initialize the map

map = new Microsoft.Maps.Map(document.getElementById("myMap"),

{credentials:"Bing Maps Key"});

// Retrieve the location of the map center

var center = map.getCenter();

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

Page 165: Bing Maps Ajax Controls Dk 70

165

</head>

<body onload="GetMap();">

<div id='myMap' style="position:relative; width:400px; height:400px;"></div>

</body>

</html>

TileLayer Class

Represents a tile layer.

Constructor

Name Definition Description

TileLayer TileLayer(options:TileLayerOptions) Initializes a new instance

of the TileLayer class.

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.

getTileSourc

e

getTileSource(projection:string) TileSourc

e

Returns the tile source of

the tile layer.

The projection parameter

accepts the following

values: mercator,

enhancedBirdseyeNorthUp,

enhancedBirdseyeSouthUp

,

enhancedBirdseyeEastUp,

enhancedBirdseyeWestUp

Page 166: Bing Maps Ajax Controls Dk 70

166

Name Definition Return

Type

Description

getZIndex getZIndex() number Returns the z-index of the

tile layer with respect to

other items on the map.

setOptions setOptions(options:TileLayerOptions

)

None Sets options for the tile

layer.

toString toString() string 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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

function GetMap()

{

// Initialize the map

var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),

Page 167: Bing Maps Ajax Controls Dk 70

167

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

// Push the tile layer to the map

map.entities.push(tilelayer);

}

catch(err)

{

alert( 'Error Message:' + err.message);

}

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:400px; height:400px;"></div>

</body>

</html>

Page 168: Bing Maps Ajax Controls Dk 70

168

See Also Working with Tile Layers

TileLayerOptions Object

Defines the options for a tile layer.

Properties

Name Type Description

animationDisplay AnimationVisibility The tile layer‟s visibility

during animation. You can

use this property to prevent

overlays from displaying

during animations, which can

impact performance. The

default value is auto.

mercator TileSource The tile source for the tile

layer.

opacity number The opacity of the tile layer,

defined by a number

between 0 (not visible) and

1.

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

zIndex number The z-index of the tile layer,

with respect to other items

on the map.

Page 169: Bing Maps Ajax Controls Dk 70

169

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var tilelayer = null;

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

// Push the tile layer to the map

Page 170: Bing Maps Ajax Controls Dk 70

170

map.entities.push(tilelayer);

}

catch(err)

{

alert( 'Error Message:' + err.message);

}

}

function SetOpacity()

{

var opacityVal = parseFloat(document.getElementById("txtOpacity").value);

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

<input type="button" value="Set Opacity" onclick="SetOpacity();"/>

Page 171: Bing Maps Ajax Controls Dk 70

171

</body>

</html>

See Also Working with Tile Layers

TileSource Class

Defines a tile source for a tile layer.

Constructor

Name Definition Description

TileSource TileSource(options:TileSourceOptions) Initializes a new instance

of the TileSource class.

Methods

Name Definition Return Type Description

getHeight getHeight() Number Returns the pixel

height of each tile in

the tile source.

getUriConstructor getUriConstructor() string Returns a string

that constructs tile

URLs used to

retrieve tiles for the

tile layer.

getWidth getWidth() number Returns the pixel

width of each tile in

the tile source.

toString toString() string Converts the

TileSource object to

a string.

Page 172: Bing Maps Ajax Controls Dk 70

172

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

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

// Push the tile layer to the map

map.entities.push(tilelayer);

}

Page 173: Bing Maps Ajax Controls Dk 70

173

catch(err)

{

alert( 'Error Message:' + err.message);

}

}

</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 projection‟s tile height

for the tiles to be shown. For

example, since Mercator tile

source tiles are 256x256, this

Page 174: Bing Maps Ajax Controls Dk 70

174

Name Type Description

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

projection‟s 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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

Page 175: Bing Maps Ajax Controls Dk 70

175

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

// Push the tile layer to the map

map.entities.push(tilelayer);

}

catch(err)

{

alert( 'Error Message:' + err.message);

}

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:400px; height:400px;"></div>

</body>

</html>

Page 176: Bing Maps Ajax Controls Dk 70

176

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.

bounds LocationRect The bounding rectangle of the

map view. If both are specified,

bounds takes precedence over

center.

center Location The location of the center of

the map view. If both are

specified, bounds takes

precedence over center.

centerOffset Point The amount the center is

shifted. This property is ignored

if center is not specified.

heading number The directional heading of the

map. The heading is

represented in geometric

degrees with 0 or 360 = North,

90 = East, 180 = South, and

270 = West.

labelOverlay LabelOverlay A constant indicating how map

labels are displayed.

mapTypeId string The map type of the view. Valid

map types are found in the

Page 177: Bing Maps Ajax Controls Dk 70

177

Name Type Description

MapTypeId Enumeration topic.

padding number The amount of padding to be

added to each side of the

bounds of the map view.

zoom number The zoom level of the map

view.

For information about map

scale and resolution with

respect to zoom level, see

Understanding Scale and

Resolution.

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.

function cancelEvent(e)

{

e.handled = true;

}

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

Page 178: Bing Maps Ajax Controls Dk 70

178

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

function GetMap()

{

// Set the initial map and view settings

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

// Initialize the map

map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),options);

}

function SetZoom()

{

// Retrieve the zoom level set by the user - converting it to a number.

var zoomLevel = parseInt(document.getElementById("txtZoom").value);

// Get the existing options.

var options = map.getOptions();

// Set the zoom level of the map

options.zoom = zoomLevel;

map.setView(options);

Page 179: Bing Maps Ajax Controls Dk 70

179

}

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

Microsoft.Maps.AdvancedShapes API Reference

This section contains reference documentation for the Microsoft.Maps.AdvancedShapes API,

which contains types that allow you to draw complex shapes on your Bing Maps AJAX Control

7.0 map.

Before you can access the types found in the Microsoft.Maps.AdvancedShapes 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 EntityCollection Class

Polygon Class

EntityCollection Class (AdvancedShapes)

Contains a collection of entities. These collection of entities can represent a multiple shape entity

on the map. When the Microsoft.Maps.AdvancedShapes module is loaded, this class inherits and

replaces the basic EntityCollection class.

An Entity can be any one of the following types: Infobox, Polygon, Polyline, Pushpin, TileLayer, or

EntityCollection.

Page 180: Bing Maps Ajax Controls Dk 70

180

Constructor

Name Definition Description

EntityCollection EntityCollection(options?:EntityCollectionOptions) Initializes a new

instance of the

EntityCollection

class.

Methods

Name Definition Return

Value

Description

clear clear() None Removes all

entities from the

collection.

get get(index:number) Entity* Returns the entity

at the specified

index in the

collection.

getLength getLength() number Returns the

number of entities

in the collection.

getVisible getVisible() boolean Returns whether

the entity

collection is visible

on the map.

getZIndex getZIndex() number Gets the z-index

of the entity

collection with

respect to other

items on the map.

indexOf indexOf(entity:Entity*) number Returns the index

of the specified

entity in the

collection. If the

entity is not found

in the collection, -1

Page 181: Bing Maps Ajax Controls Dk 70

181

Name Definition Return

Value

Description

is returned.

insert insert(entity:Entity*, index:number) None Inserts the

specified entity

into the collection

at the given index.

pop pop() Entity* Removes the last

entity from the

collection and

returns it.

push push(entity:Entity*) None Adds the specified

entity to the last

position in the

collection.

remove remove(entity:Entity*) Entity* Removes the

specified entity

from the collection

and returns it.

removeAt removeAt(index:number) Entity* Removes the

entity at the

specified index

from the collection

and returns it.

setOptions setOptions(options:EntityCollectionOptions) None Sets the options

for the entity

collection.

toString toString() string Converts the

EntityCollection

object to a string.

* An Entity can be any one of the following types: Infobox, Polygon, Polyline, Pushpin, TileLayer,

or EntityCollection.

Events

Page 182: Bing Maps Ajax Controls Dk 70

182

Name Arguments Description

entityadded object: {collection:

EntityCollection, entity:Entity*}

Occurs when one of the

following happens:

An entity is added to the

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

Page 183: Bing Maps Ajax Controls Dk 70

183

Name Arguments Description

when an entity of collection #2

is removed, two

entityremoved events are

fired.

* An Entity can be any one of the following types: Infobox, Polygon, Polyline, Pushpin, TileLayer,

or EntityCollection.

Remarks The AdvancedShapes EntityCollection class differs from the base EntityCollection class in two

ways:

When an entity of the collection fires an event, the event will fire for all entities of the

collection. For example, if the mouseover event if fired for a pushpin in an entity collection,

then the entity collection‟s mouseover event is fired.

Setting the options of the entity collection sets the options of all its entities unless the entity

collection option bubble is set to false. For example, by default, in an entity collection

composed of multiple polygons, setting one polygon‟s fill color to red changes the fill color of

all of the other polygons in the entity collection to red.

Polygon Class (AdvancedShapes)

Represents a complex polygon on the map. When the Microsoft.Maps.AdvancedShapes module

is loaded, this class replaces the basic Polygon Class.

Constructor

Name Definition Description

Polygon Polygon(locationsArrays:[Location[]],

options?:PolygonOptions)

Initializes a new instance of

a complex Polygon. The

locationsArrays array

represents the polygon

rings, where each element

of the array is an array of

Location objects that

defines a ring. This

constructor can be used to

create a normal polygon, a

multi-polygon, a polygon

Page 184: Bing Maps Ajax Controls Dk 70

184

Name Definition Description

with holes, or a combination

of polygons.

Methods

Name Definition Return Value Description

getFillColor getFillColor() Color Returns the

color of the

inside of the

polygon.

getLocations getLocations() Location[] Returns the

location array

that defines

the first ring of

the polygon.

getRings getRings() [ Location[] ] Returns an

array of

location

arrays, where

each location

array defines

a ring of the

polygon.

getStrokeColor getStrokeColor() Color Returns the

color of the

outline of the

polygon.

getStrokeDashArray getStrokeDashArray() string Returns the

string that

represents the

stroke/gap

sequence

used to draw

the outline of

the polygon.

getStrokeThickness getStrokeThickness() number Returns the

thickness of

Page 185: Bing Maps Ajax Controls Dk 70

185

Name Definition Return Value Description

the outline of

the polygon.

getVisible getVisible() boolean 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.

setLocations setLocations(locations:Location[]) None Sets the

locations that

define a basic

polygon.

setOptions setOptions(options:PolygonOptions) None Sets options

for the

polygon.

setRings setRings(locationArrays:[ Location[]

])

None Sets an array

of location

arrays, where

each location

array defines

a ring of the

polygon.

toString toString() string Converts the

Polygon object

to a string.

Events

Name Arguments Description

click eventArgs:MouseEventArgs Occurs when the mouse is

used to click the polygon.

Page 186: Bing Maps Ajax Controls Dk 70

186

Name Arguments Description

dblclick eventArgs:MouseEventArgs Occurs when the mouse is

used to double click the

polygon.

entitychanged object: {entity:Entity} Occurs when the location

of the polygon or any of

the polygon‟s options

change.

mousedown eventArgs:MouseEventArgs Occurs when the left

mouse button is pressed

when the mouse is over

the polygon.

mouseout eventArgs:MouseEventArgs Occurs when the mouse

cursor moves out of the

area covered by the

polygon.

mouseover eventArgs:MouseEventArgs Occurs when the mouse is

over the polygon.

mouseup eventArgs:MouseEventArgs Occurs when the left

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

Page 187: Bing Maps Ajax Controls Dk 70

187

<script type="text/javascript">

var map = null;

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

Microsoft.Maps.loadModule('Microsoft.Maps.AdvancedShapes', { callback:

shapesModuleLoaded });

}

function shapesModuleLoaded()

{

var polygonWithHoles = new Microsoft.Maps.Polygon([

[new Microsoft.Maps.Location(47.604, -121.940),

new Microsoft.Maps.Location(47.604, -121.540),

new Microsoft.Maps.Location(47.834, -121.540),

new Microsoft.Maps.Location(47.834, -121.940),

new Microsoft.Maps.Location(47.604, -121.940)],

[new Microsoft.Maps.Location(47.704, -121.740),

new Microsoft.Maps.Location(47.704, -121.640),

new Microsoft.Maps.Location(47.804, -121.640),

new Microsoft.Maps.Location(47.804, -121.740),

new Microsoft.Maps.Location(47.704, -121.740)],

[new Microsoft.Maps.Location(47.744, -121.700),

new Microsoft.Maps.Location(47.744, -121.680),

new Microsoft.Maps.Location(47.764, -121.680),

new Microsoft.Maps.Location(47.764, -121.700),

Page 188: Bing Maps Ajax Controls Dk 70

188

new Microsoft.Maps.Location(47.744, -121.700)]]);

map.entities.push(polygonWithHoles);

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:600px; height:600px;"></div>

</body>

</html>

Microsoft.Maps.Directions API Reference

This section contains reference documentation for the Microsoft.Maps.Directions API, which

contains types that allow you to calculate route directions and display them on your Bing Maps

AJAX Control 7.0 map. Use the calculateDirections method of the DirectionsManager Class to

calculate a route. Sample code can be found at http://www.bingmapsportal.com/isdk/ajaxv7.

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

Page 189: Bing Maps Ajax Controls Dk 70

189

DirectionsStepWarning Class

Disambiguation Class

DisambiguationRenderEventArgs Object

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

Page 190: Bing Maps Ajax Controls Dk 70

190

Name Type Description

businessName string The business name of the

waypoint.

entityId string The Bing Maps entity ID of the

business.

phoneNumber string The phone number of the

business.

website string 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 string The address of the business

result.

distance number The distance of the business

result from the originally

specified waypoint address or

location.

entityId string The Yellow Pages ID for the

business.

index number The index of this suggestion

within the business suggestion

array.

isApproximate boolean A boolean indicating whether

the result location is

approximate.

Page 191: Bing Maps Ajax Controls Dk 70

191

Name Type Description

location Location The location of the business

suggestion.

name string The name of the business.

phoneNumber string The phone number of the

business suggestion.

photoUrl string The URL of a photo of the

business suggestion.

rooftopLocation Location The rooftop location of the

business suggestion.

website string The URL of the business

result‟s 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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var directionsManager = null;

function GetMap()

{

// Initialize the map

Page 192: Bing Maps Ajax Controls Dk 70

192

map = new

Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"});

Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback:

directionsModuleLoaded });

}

function directionsModuleLoaded()

{

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

// Specify a handler for when an error occurs

Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError',

displayError);

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

Page 193: Bing Maps Ajax Controls Dk 70

193

function displayError(e)

{

// Display the error message

alert(e.message);

// If the error is a disambiguation error, display the results.

if (e.responseCode ==

Microsoft.Maps.Directions.RouteResponseCode.waypointDisambiguation)

{

DisplayDisambiguation();

}

}

function DisplayDisambiguation()

{

var results = "";

var waypoints = directionsManager.getAllWaypoints();

var i = 0;

for (i=0; i<waypoints.length; i++)

{

var disambigResult = waypoints[i].getDisambiguationResult();

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

Page 194: Bing Maps Ajax Controls Dk 70

194

{

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>

Page 195: Bing Maps Ajax Controls Dk 70

195

See Also Disambiguation Class

DirectionsErrorEventArgs Object

Contains arguments for directions error events.

Properties

Name Type Description

responseCode RouteResponseCode The code which identifies

the error that occurred.

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

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

function GetMap()

{

// Initialize the map

Page 196: Bing Maps Ajax Controls Dk 70

196

map = new

Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"});

Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback:

directionsModuleLoaded });

}

function directionsModuleLoaded()

{

// Initialize the DirectionsManager

var directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

Page 197: Bing Maps Ajax Controls Dk 70

197

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayMessage(e)

{

alert("Route calculation complete!");

}

function displayError(e)

{

alert( e.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>

DirectionsEventArgs Object

Contains the arguments for directions events.

Properties

Page 198: Bing Maps Ajax Controls Dk 70

198

Name Type Description

routeSummary RouteSummary[] The route summary (or

summaries) of the route(s)

defined in the route property.

route Route[] The calculated route (or

routes, if the route mode is

transit).

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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

}

Page 199: Bing Maps Ajax Controls Dk 70

199

function directionsModuleLoaded()

{

// Initialize the DirectionsManager

var directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

directionsManager.setRenderOptions({ itineraryContainer:

document.getElementById('itineraryDiv') });

// Specify a handler for when the directions are calculated

Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated',

displayRouteNumber);

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayRouteNumber(e)

{

Page 200: Bing Maps Ajax Controls Dk 70

200

alert("Number of transit routes available: " + e.route.length);

}

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

DirectionsManager DirectionsManager(map:Map) Initializes a new instance of

the DirectionsManager

class.

Methods

Name Definition Return Value Description

addWaypoint addWaypoint(waypoint:Waypoint,

index:number)

None Adds a

waypoint to the

route at the

given index, if

specified. If an

index is not

specified the

waypoint is

added as the

Page 201: Bing Maps Ajax Controls Dk 70

201

Name Definition Return Value Description

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

calculation is

complete and

Page 202: Bing Maps Ajax Controls Dk 70

202

Name Definition Return Value Description

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.

dispose dispose() None Deletes the

DirectionsMan

ager object and

releases any

associated

resources.

getAllWaypoint

s

getAllWaypoints() Waypoint[] Returns the

waypoints for

the route.

Page 203: Bing Maps Ajax Controls Dk 70

203

Name Definition Return Value Description

getMap getMap() Map Returns the

map object

associated with

the directions

manager.

getNearbyMajor

Roads

getNearbyMajorRoads(location:Locatio

n, callback:function,

errorCallback:function,

userData:object)

None Searches

around the

specified

location for

nearby major

roads and

returns them as

an object to the

callback

function.

getRenderOptio

ns

getRenderOptions() DirectionsRender

Options

Returns the

route render

options.

getRequestOpti

ons

getRequestOptions() DirectionsRequest

Options

Returns the

directions

request

options.

getRouteResult getRouteResult() Route[] Returns the

current

calculated

route(s). If the

route was not

successfully

calculated, null

is returned.

removeWaypoi

nt

removeWaypoint(waypoint:Waypoint) or

removeWaypoints(index:number)

None Removes the

given waypoint

or the waypoint

identified by the

given index

from the route.

Use

calculateDirec

tions to update

Page 204: Bing Maps Ajax Controls Dk 70

204

Name Definition Return Value Description

the route once

a waypoint has

been removed.

resetDirections resetDirections(options:ResetDirectio

nsOptions)

None If no options

object is

supplied, clears

the directions

request and

render options

and removes

all waypoints.

reverseGeocod

e

reverseGeocode(location:Location,

callback:function,

errorCallback:function,

userData:object)

None Matches the

specified

location to an

address and

returns the

address to the

specified

callback

function.

setMapView setMapView() None Sets the map

view based on

the current

route index.

setRenderOptio

ns

setRenderOptions(options:DirectionsR

enderOptions)

None Sets the

specified

render options

for the route.

setRequestOpti

ons

setRequestOptions(options:Directions

RequestOptions)

None Sets the

specified route

calculation

options.

Events

Name Arguments Description

afterRouteSelectorRender RouteSelectorRenderEventArgs Occurs after the route

Page 205: Bing Maps Ajax Controls Dk 70

205

Name Arguments Description

selector has fully rendered.

afterStepRender DirectionsStepRenderEventArgs Occurs after each step in the

itinerary has fully rendered.

afterSummaryRender RouteSummaryRenderEventArg

s

Occurs after the route

summary has fully rendered.

afterWaypointRender WaypointRenderEventArgs Occurs after each route

waypoint has fully rendered.

beforeDisambiguationRende

r

DisambiguationRenderEventArg

s

Occurs before the waypoint

disambiguation element is

rendered. Use the

autoDisplayDisambiguatio

n directions render option to

automatically display

waypoint disambiguation.

beforeRouteSelectorRender RouteSelectorRenderEventArgs Occurs just before the route

selector renders.

beforeStepRender DirectionsStepRenderEventArgs Occurs just before each step

in the itinerary renders.

beforeSummaryRender RouteSummaryRenderEventArg

s

Occurs just before the route

summary renders.

beforeWaypointRender WaypointRenderEventArgs Occurs just before each

route waypoint renders.

directionsError DirectionsErrorEventArgs Occurs when calculating the

directions caused an error.

directionsUpdated DirectionsEventArgs Occurs when the directions

calculation was successful

and the itinerary and route

on the map have been

updated.

dragDropCompleted None Occurs when the drag of a

waypoint or route is

completed.

itineraryStepClicked DirectionsStepEventArgs Occurs when a step in the

itinerary is clicked.

mouseEnterRouteSelector RouteSelectorEventArgs Occurs when the mouse

Page 206: Bing Maps Ajax Controls Dk 70

206

Name Arguments Description

cursor is over the route

selector.

mouseEnterStep DirectionsStepEventArgs Occurs when the mouse

cursor is over a directions

step.

mouseLeaveRouteSelector RouteSelectorEventArgs Occurs when the mouse

cursor leaves the route

selector.

mouseLeaveStep DirectionsStepEventArgs Occurs when the mouse

cursor leaves a directions

step.

routeSelectorClicked RouteSelectorEventArgs Occurs when the route

selector is clicked.

waypointAdded WaypointEventArgs Occurs when a new

waypoint is added to the

route.

waypointRemoved WaypointEventArgs Occurs when a waypoint is

removed from the 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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

Page 207: Bing Maps Ajax Controls Dk 70

207

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

{

// Initialize the DirectionsManager

var directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

// Specify a handler for when an error occurs

Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError',

displayError);

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

Page 208: Bing Maps Ajax Controls Dk 70

208

}

function displayError(e)

{

alert(e.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>

DirectionsRenderOptions Object

Represents render options for a route.

Properties

Name Type Description

autoDisplayDisambiguation boolean A boolean indicating

whether to automatically

display a disambiguation

dialog for waypoints. The

default value is true.

If this value is set to true, a

directionsError event

caused by waypoint

disambiguation is not

thrown.

autoUpdateMapView boolean A boolean indicating

Page 209: Bing Maps Ajax Controls Dk 70

209

Name Type Description

whether to automatically

set the map view to the

best map view of the

calculated route. The

default value is true.

disambiguationPushpinOptions PushpinOptions The options that define the

pushpin to use for

disambiguation.

displayDisclaimer boolean A boolean indicating

whether to display the

disclaimer about the

accuracy of the directions.

The default value is false.

displayManeuverIcons boolean A boolean indicating

whether to display the

icons for each direction

maneuver. The default

value is true.

displayPostItineraryItemHints boolean A boolean indicating

whether to display direction

hints that describe when

an direction step was

missed. The default value

is true.

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

displayRouteSelector boolean A boolean indicating

whether to display the

route selector control. The

default value is true.

displayStepWarnings boolean A boolean indicating

whether to display direction

warnings. The default

value is true.

Page 210: Bing Maps Ajax Controls Dk 70

210

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.

displayWalkingWarning boolean A boolean indicating

whether to display a

warning about walking

directions. The default

value is true.

drivingPolylineOptions PolylineOptions The options that define

how to draw the route line

on the map, if the

RouteMode is driving.

itineraryContainer DOMElement The DOM element inside

which the directions

itinerary will be rendered.

lastWaypointIcon string The URL of the icon to use

for the end waypoint.

middleWaypointIcon string The URL of the icon to use

for intermediate waypoints.

stepPushpinOptions PushpinOptions The options that define the

pushpin to use for each

direction step.

transitPolylineOptions PolylineOptions The options that define

how to draw the route line

on the map, if the

RouteMode is transit.

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

walkingPolylineOptions PolylineOptions The options that define

how to draw the route line

on the map, if the

Page 211: Bing Maps Ajax Controls Dk 70

211

Name Type Description

RouteMode is walking.

waypointPushpinOptions PushpinOptions The options that define the

pushpin to use for the

route waypoint.

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var directionsManager = null;

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

}

Page 212: Bing Maps Ajax Controls Dk 70

212

function directionsModuleLoaded()

{

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

directionsManager.setRequestOptions({ routeMode:

Microsoft.Maps.Directions.RouteMode.walking });

// Set the render options

directionsManager.setRenderOptions({ itineraryContainer:

document.getElementById('itineraryDiv'), displayWalkingWarning: false,

walkingPolylineOptions:{strokeColor: new Microsoft.Maps.Color(200, 0, 255, 0)} });

// Specify a handler for when an error occurs

Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError',

displayError);

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayError(e)

Page 213: Bing Maps Ajax Controls Dk 70

213

{

// Display the error message

alert(e.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>

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.

distanceUnit DistanceUnit The unit to use when displaying

direction distances. The default

value is based on the specified

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

Page 214: Bing Maps Ajax Controls Dk 70

214

Name Type Description

routes can be calculated and the

default is 3.

routeAvoidance RouteAvoidance[] The features to avoid when

calculating the route. The default

value is none.

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

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

routeOptimization RouteOptimization The optimization setting for the

route calculation. The default

value is shortestTime.

transitOptions TransitOptions The extra options for calculating a

route if the routeMode is transit.

Page 215: Bing Maps Ajax Controls Dk 70

215

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var directionsManager = null;

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

{

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

// Create start and end waypoints

Page 216: Bing Maps Ajax Controls Dk 70

216

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

// Set request options

directionsManager.setRequestOptions({ avoidTraffic: true, routeOptimization:

Microsoft.Maps.Directions.RouteOptimization.shortestDistance });

// Set the render options

directionsManager.setRenderOptions({ itineraryContainer:

document.getElementById('itineraryDiv') });

// Specify a handler for when an error occurs

Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError',

displayError);

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayError(e)

{

// Display the error message

alert(e.message);

}

</script>

</head>

Page 217: Bing Maps Ajax Controls Dk 70

217

<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

childItineraryItems DirectionsStep[] The child direction items for this

directions step.

coordinate Location The location of the start of the

direction.

distance string The total distance of the step in

the unit specified in the

distanceUnit property of the

DirectionsRequestOptions.

durationInSeconds number The total time, in seconds, of the

direction step.

formattedText string The HTML formatted route

instruction associated with the

step.

iconType IconType The type of the icon associated

with this step.

isImageRoadShield boolean A boolean indicating whether

the maneuver image is a road

shield image.

maneuver Maneuver The maneuver type associated

with this step.

maneuverImageName string The name of the maneuver

image.

Page 218: Bing Maps Ajax Controls Dk 70

218

Name Type Description

monetaryCost number The cost of the step.

postIntersectionHints string[] 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.

preIntersectionHints string[] 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.

startStopName string The name of the transit stop

where this step originates.

transitLine TransitLine The transit line associated with

this step.

transitStepIcon string The URL of the image to use for

transit direction steps.

transitStopId string The ID of the transit stop.

transitTerminus string The name of the transit line end.

warnings DirectionsStepWarning[] An array of strings, where each

string is a route warning

associated with this step.

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

Page 219: Bing Maps Ajax Controls Dk 70

219

<script type="text/javascript">

var map = null;

var directionsManager = null;

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

{

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

Page 220: Bing Maps Ajax Controls Dk 70

220

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

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayError(e)

{

alert(e.message);

}

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 )

Page 221: Bing Maps Ajax Controls Dk 70

221

{

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.

location Location The location along the route

where the direction step

occurs.

Page 222: Bing Maps Ajax Controls Dk 70

222

Name Type Description

routeIndex number A number indicating the route

(if multiple routes were

returned) to which the

directions step belongs.

routeLegIndex number A number indicating the route

leg to which the directions

step belongs.

step DirectionsStep The directions step.

stepIndex number A number indicating the index

of the directions step within

the route leg array.

stepNumber number A number indicating the

directions step number within

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

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var directionsManager = null;

function GetMap()

{

Page 223: Bing Maps Ajax Controls Dk 70

223

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

{

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

Page 224: Bing Maps Ajax Controls Dk 70

224

Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError',

displayError);

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayError(e)

{

alert(e.message);

}

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>

Page 225: Bing Maps Ajax Controls Dk 70

225

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.

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

lastStep boolean A boolean indicating whether

the step is the last directions

step.

routeIndex number A number indicating the index

of the route to which this step

belongs.

routeLegIndex number A number indicating the index

of the route leg to which this

step belongs.

step DirectionsStep The directions step.

stepIndex number The index of this directions step

within the route leg step array.

Example <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

<head>

Page 226: Bing Maps Ajax Controls Dk 70

226

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var directionsManager = null;

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

{

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

Page 227: Bing Maps Ajax Controls Dk 70

227

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

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayError(e)

{

alert(e.message);

}

function displayStepMessage(e)

{

var message = "A directions step has rendered.";

if (e.lastStep) { message = message + " This is the last itinerary step.";

}

alert(message);

}

Page 228: Bing Maps Ajax Controls Dk 70

228

</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 StepWarningStyle The type of the route warning.

text string The warning text.

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

Page 229: Bing Maps Ajax Controls Dk 70

229

var directionsManager = null;

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

{

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

Page 230: Bing Maps Ajax Controls Dk 70

230

Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated',

displayMessage );

Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError',

displayError);

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayMessage(e)

{

// Variable for counting warnings

var warningCount = 0;

for( j=0; j< e.route[0].routeLegs.length; j++)

{

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;

}

}

}

alert("There are " + warningCount + " warning(s) in this route.");

}

Page 231: Bing Maps Ajax Controls Dk 70

231

function displayError(e)

{

alert(e.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>

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.

hasMoreSuggestions boolean A boolean indicating

whether there are more

result suggestions

available.

headerText string The disambiguation

Page 232: Bing Maps Ajax Controls Dk 70

232

Name Type Description

header text.

locationSuggestions LocationDiambiguationSuggestion[] The possible location

result matches for the

originally specified

waypoint address or

location.

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var directionsManager = null;

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

}

Page 233: Bing Maps Ajax Controls Dk 70

233

function directionsModuleLoaded()

{

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

// 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, and prevent the

default disambiguation dialog from appearing by setting that option

directionsManager.setRenderOptions({autoDisplayDisambiguation:false,

itineraryContainer: document.getElementById('itineraryDiv') });

// Specify a handler for when an error occurs

Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError',

displayError);

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayError(e)

{

// Display the error message

alert(e.message);

Page 234: Bing Maps Ajax Controls Dk 70

234

// If the error is a disambiguation error, display the results.

if (e.responseCode ==

Microsoft.Maps.Directions.RouteResponseCode.waypointDisambiguation)

{

DisplayDisambiguation();

}

}

function DisplayDisambiguation()

{

var results = "";

var waypoints = directionsManager.getAllWaypoints();

var i = 0;

for (i=0; i<waypoints.length; i++)

{

var disambigResult = waypoints[i].getDisambiguationResult();

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)

Page 235: Bing Maps Ajax Controls Dk 70

235

{

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)

DisambiguationRenderEventArgs Object

Contains arguments for a beforeDisambiguationRender event.

Page 236: Bing Maps Ajax Controls Dk 70

236

Properties

Name Type Description

containerElement object The DOM element which

contains the disambiguation

list. You can use this property

to add custom content.

handled boolean A boolean indicating whether

the event is handled. Set this

property to true to override the

default behavior. If this property

is set to true, a directionsError

event for waypoint

disambiguation is thrown.

waypoint Waypoint The waypoint that needs to be

disambiguated.

DistanceUnit Enumeration (AJAX)

Defines the distance unit to use when generating routes and corresponding itineraries.

Constants

Code Name Description

0 kilometers Kilometers are used to measure

route distances.

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

Page 237: Bing Maps Ajax Controls Dk 70

237

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var directionsManager = null;

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

{

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

Page 238: Bing Maps Ajax Controls Dk 70

238

directionsManager.addWaypoint(endWaypoint);

// Set request options

directionsManager.setRequestOptions({ distanceUnit:

Microsoft.Maps.Directions.DistanceUnit.kilometers, routeOptimization:

Microsoft.Maps.Directions.RouteOptimization.shortestDistance });

// Set the render options

directionsManager.setRenderOptions({ itineraryContainer:

document.getElementById('itineraryDiv') });

// Specify a handler for when an error occurs

Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError',

displayError);

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayError(e)

{

// Display the error message

alert(e.message);

}

</script>

</head>

<body onload="GetMap();">

Page 239: Bing Maps Ajax Controls Dk 70

239

<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 none There is no route icon.

1 other The icon is some other type of

icon.

2 auto The icon is a car icon.

3 ferry The icon is a ferry icon.

4 walk The icon is a walking icon.

5 bus The icon is a bus, or transit, icon

6 train The icon is a train icon.

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

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

Page 240: Bing Maps Ajax Controls Dk 70

240

<script type="text/javascript">

var map = null;

var directionsManager = null;

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

{

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

Page 241: Bing Maps Ajax Controls Dk 70

241

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

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayError(e)

{

alert(e.message);

}

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 )

Page 242: Bing Maps Ajax Controls Dk 70

242

{

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

formattedSuggestion string The HTML formatted address

suggestion.

location Location The location of the

suggestion.

rooftopLocation Location The rooftop location of the

suggestion.

Page 243: Bing Maps Ajax Controls Dk 70

243

Name Type Description

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

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var directionsManager = null;

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

{

Page 244: Bing Maps Ajax Controls Dk 70

244

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

// Specify a handler for when an error occurs

Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError',

displayError);

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayError(e)

{

// Display the error message

alert(e.message);

// If the error is a disambiguation error, display the results.

if (e.responseCode ==

Microsoft.Maps.Directions.RouteResponseCode.waypointDisambiguation)

{

DisplayDisambiguation();

Page 245: Bing Maps Ajax Controls Dk 70

245

}

}

function DisplayDisambiguation()

{

var results = "";

var waypoints = directionsManager.getAllWaypoints();

var i = 0;

for (i=0; i<waypoints.length; i++)

{

var disambigResult = waypoints[i].getDisambiguationResult();

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

{

Page 246: Bing Maps Ajax Controls Dk 70

246

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

Page 247: Bing Maps Ajax Controls Dk 70

247

Type Code Name Description

0 none The step is not a maneuver.

1 unknown The maneuver is unknown.

2 departStart Depart from the start

waypoint.

3 departIntermediateStop Depart from an intermediate

stop point going in a

different direction and on a

different road than which

you arrived.

4 departIntermediateStopReturning Depart from an intermediate

stop point going back in the

same direction and on the

same road on which you

arrived.

5 arriveFinish Arrive at the end waypoint.

6 arriveIntermediateStop Arrive at an intermediate

stop point.

7 turnLeft Turn left.

8 turnRight Turn right.

9 turnBack Turn back sharply.

10 uTurn Make a u-turn to go in the

opposite direction.

11 turnToStayLeft Turn left to stay on the

same road.

12 turnToStayRight Turn right to stay on the

same road.

13 bearLeft Bear left.

14 bearRight Bear right.

15 keepToStayLeft Keep left to stay on the

same road.

16 keepToStayRight Keep right to stay on the

same road.

17 keepToStayStraight Keep straight to stay on the

Page 248: Bing Maps Ajax Controls Dk 70

248

Type Code Name Description

same road.

18 keepLeft Keep left onto a different

road.

19 keepRight Keep right onto a different

road.

20 keepStraight Keep straight onto a

different road.

21 take Take the road. This

instruction is used when

you are entering or exiting a

ferry.

22 takeRampLeft Take the ramp to the left.

23 takeRampRight Take the ramp to the right.

24 takeRampStraight Stay straight to take the

ramp.

25 keepOnRampLeft Keep left and continue onto

ramp.

26 keepOnRampRight Keep right and continue

onto ramp.

27 keepOnRampStraight Keep straight and continue

onto ramp.

28 merge Merge onto highway.

29 continueRoute Continue on the current

road.

30 roadNameChange The road name changed.

31 enterRoundabout Enter a roundabout.

32 exitRoundabout Exit a roundabout.

33 turnRightThenTurnRight Turn right and then turn

right.

34 turnRightThenTurnLeft Turn right and then turn left.

35 turnRightThenBearRight Turn right and then bear

right.

Page 249: Bing Maps Ajax Controls Dk 70

249

Type Code Name Description

36 turnRightThenBearLeft Turn right and then bear

left.

37 turnLeftThenTurnLeft Turn left and then turn left.

38 turnLeftThenTurnRight Turn left and then turn right.

39 turnLeftThenBearLeft Turn left and then bear left.

40 turnLeftThenBearRight Turn left and then bear

right.

41 bearRightThenTurnRight Bear right and then turn

right.

42 bearRightThenTurnLeft Bear right and then turn left.

43 bearRightThenBearRight Bear right and then bear

right.

44 bearRightThenBearLeft Bear right and then bear

left.

45 bearLeftThenTurnLeft Bear left and then turn left.

46 bearLeftThenTurnRight Bear left and then turn right.

47 bearLeftThenBearRight Bear left and then bear

right.

48 bearLeftThenBearLeft Bear left and then bear left.

49 rampThenHighwayRight Take left ramp onto

highway. This is part of a

combined instruction.

50 rampThenHighwayLeft Take right ramp onto

highway. This is part of a

combined instruction.

51 rampToHighwayStraight Stay straight to take the

ramp onto the highway.

This is part of a combined

instruction.

52 enterThenExitRoundabout Enter and exit a

roundabout.

53 bearThenMerge Bear instruction and then a

merge instruction.

Page 250: Bing Maps Ajax Controls Dk 70

250

Type Code Name Description

54 turnThenMerge Turn instruction and then a

merge instruction.

55 bearThenKeep Bear instruction and then a

keep instruction.

56 transfer Transfer between public

transit lines at a transit stop.

57 wait Wait at a transit stop.

58 takeTransit Take transit.

59 walk The maneuver is a walking

instruction.

60 transitDepart Get on a public transit line

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var directionsManager = null;

function GetMap()

Page 251: Bing Maps Ajax Controls Dk 70

251

{

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

{

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

Page 252: Bing Maps Ajax Controls Dk 70

252

Microsoft.Maps.Events.addHandler(directionsManager, 'itineraryStepClicked',

displayStepMessage );

Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError',

displayError);

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayError(e)

{

alert(e.message);

}

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 )

{

Page 253: Bing Maps Ajax Controls Dk 70

253

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

}

else

{

alert("This step is not a transit 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.

Page 254: Bing Maps Ajax Controls Dk 70

254

Properties

Name Type Description

removeAllWaypoints boolean A boolean indicating whether

to remove all of the

waypoints of the route. The

default value is false.

resetRenderOptions boolean A boolean indicating whether

to reset all of the render

options set for the route. The

default value is false.

resetRequestOptions boolean A boolean indicating whether

to reset all of the request

options set for the route. The

default value is false.

Route Class (AJAX)

Represents a route.

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

Page 255: Bing Maps Ajax Controls Dk 70

255

Code Name Description

0 none Calculate the best route

using any travel option

available.

1 minimizeLimitedAccessHighway Reduce the use of limited

access highways when

calculating the route.

2 minimizeToll Reduce the use of roads

with tolls when calculating

the route.

4 avoidLimitedAccessHighway Avoid using limited access

highways when calculating

the route.

8 avoidToll Avoid using roads with tolls

when calculating the route.

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

32 avoidAirline Avoid using airlines when

calculating the route. This

option only affects routes

with a transit RouteMode

that have the culture set to

ja-jp.

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

RouteLeg Class (AJAX)

Represents a leg of a route. A route leg is the part of the route between two stop waypoints.

Page 256: Bing Maps Ajax Controls Dk 70

256

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.

endWaypointLocation Location The location of the last waypoint

of this leg.

itineraryItems DirectionsStep[] The directions steps associated

with this route leg.

originalRouteIndex number The index of the route to which

this route leg belongs.

startTime DateTime The start time of the route leg.

This property only applies when

the routeMode of the

DirectionsRequestOptions is set

to transit.

startWaypointLocation Location The location of the first waypoint

of this route leg.

subLegs RouteSubLeg[] 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.

summary RouteSummary The summary which describes

this route leg.

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

Page 257: Bing Maps Ajax Controls Dk 70

257

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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

{

// Initialize the DirectionsManager

var directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

Page 258: Bing Maps Ajax Controls Dk 70

258

Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError',

displayError);

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayMessage(e)

{

alert("The calculated route has " +

e.route[0].routeLegs[0].itineraryItems.length + " direction steps.");

}

function displayError(e)

{

alert("An error has occurred calculating the directions.");

}

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

Page 259: Bing Maps Ajax Controls Dk 70

259

Name Description

driving Driving directions are calculated.

transit Transit directions are calculated.

walking Walking directions are calculated.

RouteOptimization Enumeration (AJAX)

Defines optimization options for calculating directions.

Constants

Code Name Description

0 shortestTime Calculate a route the shortest

time.

1 shortestDistance Calculate a route with the

shortest distance.

3 minimizeMoney Minimize the cost when

calculating directions. This

option only affects routes with

a transit RouteMode that

have the culture set to ja-jp.

4 minimizeTransfers Minimize transit transfers

when calculating directions.

This option only affects routes

with a transit RouteMode that

have the culture set to ja-jp.

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

Page 260: Bing Maps Ajax Controls Dk 70

260

RoutePath Class (AJAX)

Represents the route line shape on the map.

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.

decodedLongitudes double[] An array of longitudes, where

each is the longitude value for

one of the locations that

define the route line.

decodedRegions Object[] An array of regions that

define, depending on the

zoom level, how the route line

should be rendered.

RouteResponseCode Enumeration

Contains response codes for a route calculation request.

Constants

Response Code Name Description

0 success The route was successfully

calculated.

1 unknownError An unknown error has occurred.

2 cannotFindNearbyRoad A nearby road cannot be found for

one or more of the route

Page 261: Bing Maps Ajax Controls Dk 70

261

Response Code Name Description

waypoints.

3 tooFar The distance between two 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.

5 dataSourceNotFound There is no route data for the

specified waypoints.

7 noAvailableTransitTrip There are no transit options

available for the specified time.

8 transitStopsTooClose The transit stops are so close that

walking is always a better option.

9 walkingBestAlternative The transit stops are so close that

walking is a better option.

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

11 timeout The directions calculation request

has timed out.

12 waypointDisambiguation One or more waypoints need to be

disambiguated. This error does not

occur if the

autoDisplayDisambiguation

directions render option is set to

true.

13 hasEmptyWaypoint One or more waypoints do not

have an address or location

specified.

Page 262: Bing Maps Ajax Controls Dk 70

262

Response Code Name Description

14 exceedMaxWaypointLimit The maximum number of

waypoints, which is 25, has been

exceeded.

15 atleastTwoWaypointRequired At least two waypoints are required

to calculate a route.

16 firstOrLastStoppointIsVia The first or last waypoint is a via

point, which is not allowed.

17 searchServiceFailed The search service failed to return

results.

18 invalidCredentials The credentials passed to the

Directions module are invalid.

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var directionsManager = null;

function GetMap()

{

// Initialize the map

map = new

Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"});

Page 263: Bing Maps Ajax Controls Dk 70

263

Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback:

directionsModuleLoaded });

}

function directionsModuleLoaded()

{

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

directionsManager.addWaypoint(waypoint1);

directionsManager.addWaypoint(waypoint2);

directionsManager.addWaypoint(waypoint3);

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

Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError',

displayError);

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

Page 264: Bing Maps Ajax Controls Dk 70

264

}

function displayError(e)

{

// Display the error message

alert(e.message);

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

Page 265: Bing Maps Ajax Controls Dk 70

265

Name Type Description

default behavior.

routeIndex number A number indicating the index

of the route that was selected.

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.

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

routeIndex number A number indicating the index of the

selected route.

routeLeg RouteLeg The route leg of the selected route.

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

Page 266: Bing Maps Ajax Controls Dk 70

266

Name Type Description

actualEnd Location The location of the last

waypoint of the sub leg.

actualStart Location The location of the first

waypoint of the sub leg.

endDescription string The description of the last

waypoint of the sub leg.

routePath RoutePath The properties that define

the route line of this sub leg

on the map.

startDescription string The description of the first

waypoint of the sub leg.

summary RouteSummary The summary of this route

sub leg.

RouteSummary Class (AJAX)

Represents a route summary.

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.

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

northEast Location The location of the northeast corner

of bounding box that defines the

best map view of the route.

southWest Location The location of the southwest corner

Page 267: Bing Maps Ajax Controls Dk 70

267

Name Type Description

of bounding box that defines the

best map view of the route.

time number The total travel time, in seconds, for

the route.

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

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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

Page 268: Bing Maps Ajax Controls Dk 70

268

}

function directionsModuleLoaded()

{

// Initialize the DirectionsManager

var directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayDistanceAndTime(e)

{

Page 269: Bing Maps Ajax Controls Dk 70

269

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.

handled boolean A boolean indicating whether the

event is handled. This property is

only available for the

beforeSummaryRender event.

Set this property to true to

override the default behavior.

routeLegIndex number A number indicating the index of

the route leg which this summary

describes.

Page 270: Bing Maps Ajax Controls Dk 70

270

Name Type Description

summary RouteSummary The summary that was rendered.

StepWarningStyle Enumeration

Contains types of route direction warnings.

Constants

Code Name Description

0 info The warning is just information

about the route direction.

1 minor The warning is a minor

warning, and may affect the

route direction.

2 moderate The warning is a moderate

warning and is likely to affect

the route direction.

3 major The warning is a major

warning, and is highly likely to

affect the route direction.

4 ccZoneEnter The warning indicates a

congestion zone is being

entered.

5 ccZoneExit The warning indicates a

congestion zone is being

exited.

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>

Page 271: Bing Maps Ajax Controls Dk 70

271

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var directionsManager = null;

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

{

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

Page 272: Bing Maps Ajax Controls Dk 70

272

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

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayMessage(e)

{

// Variable for counting warnings

var warningCount = 0;

for( j=0; j< e.route[0].routeLegs.length; j++)

{

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 )

{

Page 273: Bing Maps Ajax Controls Dk 70

273

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

}

}

}

}

}

alert("There are " + warningCount + " warning(s) in this route.");

}

function displayError(e)

{

alert(e.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>

Page 274: Bing Maps Ajax Controls Dk 70

274

</html>

TimeType Enumeration

Defines the transit time type.

Constants

Name Description

arrival The time specified is an arrival time.

departure The time specified is a departure time.

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

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var directionsManager = null;

function GetMap()

Page 275: Bing Maps Ajax Controls Dk 70

275

{

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

{

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

Page 276: Bing Maps Ajax Controls Dk 70

276

// Specify a handler for when the directions are calculated

Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError',

displayError);

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayError(e)

{

alert(e.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>

See Also TransitOptions Object

TransitLine Class

Contains information about a transit line.

Page 277: Bing Maps Ajax Controls Dk 70

277

Properties

Name Type Description

abbreviatedName string The short name for the transit

line.

agencyId number The ID of the agency that

owns the transit line.

agencyName string The name of the agency that

owns the transit line.

agencyUrl string The URL of the website of the

agency that owns the transit

line.

lineColor Color The color to use when

rendering this transit line on

the map.

lineTextColor Color The color to use when

rendering text associated with

this transit line.

providerInfo string Information about the provider

of this transit line data.

verboseName string The full name of this transit

line.

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

Page 278: Bing Maps Ajax Controls Dk 70

278

<script type="text/javascript">

var map = null;

var directionsManager = null;

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

{

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

Page 279: Bing Maps Ajax Controls Dk 70

279

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

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayError(e)

{

alert(e.message);

}

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 )

Page 280: Bing Maps Ajax Controls Dk 70

280

{

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.

transitTime Date The transit time to use when

calculating the route. If this

property is set to null, the

current time is used.

Page 281: Bing Maps Ajax Controls Dk 70

281

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var directionsManager = null;

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

{

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

// Create start and end waypoints and add them to the route

Page 282: Bing Maps Ajax Controls Dk 70

282

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

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayError(e)

{

alert(e.message);

}

Page 283: Bing Maps Ajax Controls Dk 70

283

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

Waypoint Class (AJAX)

Represents a route waypoint.

Constructor

Name Definition Description

Waypoint Waypoint(options:WaypointOptions) Initializes a new instance

of the Waypoint class.

Methods

Name Definition Return Value Description

clear clear() None Clears all

options

associated

with this

waypoint.

dispose dispose() None Releases any

resources

associated

with the

waypoint.

getAddress getAddress() string Returns the

address

associated

Page 284: Bing Maps Ajax Controls Dk 70

284

Name Definition Return Value Description

with the

waypoint.

getBusinessDetails getBusinessDetails() BusinessDetai

ls

Returns the

business

details

associated

with the

waypoint.

getDisambiguationContai

ner

getDisambiguationContainer() DOMElement Returns the

container

element for

the waypoint

disambiguatio

n list.

getDisambiguationResult getDisambiguationResult() Disambiguatio

n

Returns the

result of the

waypoint

geocoding

disambiguatio

n.

getLocation getLocation() Location Returns the

location of the

waypoint.

getPushpin getPushpin() Pushpin Returns the

custom

pushpin

associated

with this

waypoint, if

one has been

specified.

getShortAddress getShortAddress() string Returns the

short address

for the

waypoint.

isExactLocation isExactLocation() boolean Returns a

boolean

indicating

Page 285: Bing Maps Ajax Controls Dk 70

285

Name Definition Return Value Description

whether the

waypoint

location is the

exact

location.

isViapoint isViapoint() boolean 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.

setOptions setOptions(options:WaypointOpti

ons)

None Sets options

for the

waypoint. For

these options

to take effect,

you must

recalculate

the route.

Events

Name Arguments Description

changed WaypointEventArgs Occurs when the any

properties of the waypoint

change or are updated.

geocoded WaypointEventArgs Occurs when a geocoding

request for the waypoint‟s

Page 286: Bing Maps Ajax Controls Dk 70

286

Name Arguments Description

address is made.

reverseGeocoded WaypointEventArgs Occurs when a reverse

geocoding request for the

waypoint‟s 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).

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var directionsManager = null;

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

Page 287: Bing Maps Ajax Controls Dk 70

287

}

function directionsModuleLoaded()

{

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

// Specify a handler for when an error occurs

Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError',

displayError);

// Calculate directions, which displays a route on the map

directionsManager.calculateDirections();

}

function displayError(e)

Page 288: Bing Maps Ajax Controls Dk 70

288

{

// Display the error message

alert(e.message);

// If the error is a disambiguation error, display the results.

if (e.responseCode ==

Microsoft.Maps.Directions.RouteResponseCode.waypointDisambiguation)

{

SelectFirstDisambiguationResult();

}

}

function SelectFirstDisambiguationResult()

{

var results = "";

var waypoints = directionsManager.getAllWaypoints();

var recalculate = false;

var i = 0;

for (i=0; i<waypoints.length; i++)

{

var disambigResult = waypoints[i].getDisambiguationResult();

if (disambigResult != null)

{

// Reset the address to the first business or location suggestion

Page 289: Bing Maps Ajax Controls Dk 70

289

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 The waypoint for which the

Page 290: Bing Maps Ajax Controls Dk 70

290

Name Type Description

event occurred.

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.

businessDetails BusinessDetails The business details of the

waypoint, if it is a business.

disambiguationContainer DOMElement The DOM element inside which

the waypoint disambiguation list

will be rendered. If this property

is not set, the disambiguation list

is rendered inside the

itineraryContainer.

exactLocation boolean A boolean indicating whether the

waypoint location is the exact

location. The default value is

false.

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

Page 291: Bing Maps Ajax Controls Dk 70

291

Name Type Description

false.

location Location The location of the waypoint.

Either the address or location

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.

shortAddress string The short address of the

waypoint.

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var directionsManager = null;

function GetMap()

{

// Initialize the map

Page 292: Bing Maps Ajax Controls Dk 70

292

map = new

Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"});

Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback:

directionsModuleLoaded });

}

function directionsModuleLoaded()

{

// Initialize the DirectionsManager

directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);

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

directionsManager.addWaypoint(startWaypoint);

directionsManager.addWaypoint(viaWaypoint);

directionsManager.addWaypoint(endWaypoint);

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

// Calculate directions, which displays a route on the map

Page 293: Bing Maps Ajax Controls Dk 70

293

directionsManager.calculateDirections();

}

function displayError(e)

{

// Display the error message

alert(e.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>

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.

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

Page 294: Bing Maps Ajax Controls Dk 70

294

Name Type Description

waypoint Waypoint The waypoint for which the event

occurred.

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.

Navigation Bar Style To load the new Bing Maps navigation bar, load the Microsoft.Maps.Overlays.Style module, then

set the customizeOverlays map option to true.

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

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

Microsoft.Maps.loadModule('Microsoft.Maps.Overlays.Style', { callback: GetMap });

function GetMap()

{

Page 295: Bing Maps Ajax Controls Dk 70

295

var options = {credentials: "Bing Maps Key", center: new

Microsoft.Maps.Location(47.5, -122.3), zoom: 9, customizeOverlays: true }

map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), options );

}

</script>

</head>

<body>

<div id='mapDiv' style="position:relative; width:600px; height:600px;"></div>

</body>

</html>

Microsoft.Maps.Search API Reference

This section contains reference documentation for the Microsoft.Maps.Search API, which

contains types that allow you to return search and location results to display on your Bing Maps

AJAX Control 7.0 map. Use the methods geocode, reverseGeocode, and search found on the

SearchManager Class.

Before you can access the types found in the Microsoft.Maps.Search 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 Address Class

GeocodeLocation Class

GeocodeRequestOptions Object

GeocodeResult Class

LocationPrecision Enum

MatchCode Enum

MatchConfidence Enum

PlaceResult Class

Page 296: Bing Maps Ajax Controls Dk 70

296

ReverseGeocodeRequestOptions Object

SearchManager Class

SearchParseResult Class

SearchRegion Class

SearchRequestOptions Object

SearchResponse Class

SearchResponseSummary Class

SearchResult Class

Address Class (AJAX)

Represents an address.

Properties

Name Type Description

addressLine string The street line of an address.

The addressLine property is

the most precise, official line for

an address relative to the

postal agency servicing the

area specified by the locality or

postalCode properties.

adminDistrict string The subdivision name within

the country or region for an

address. This element is also

commonly treated as the first

order administrative

subdivision. An example is a

US state, such as “Oregon”.

countryRegion string The country or region name of

the address.

district string The second, third, or fourth

order subdivision within a

country, dependency, or

region.

formattedAddress string The complete, unparsed

Page 297: Bing Maps Ajax Controls Dk 70

297

Name Type Description

address.

locality string The locality, such as the

primary city, that corresponds

to an address. An example is

“Seattle”.

postalCode string The post code, postal code, or

ZIP code of an address. An

example is a US ZIP code,

such as “98152”.

postalTown string The city or neighborhood that

corresponds to the postalCode.

GeocodeLocation Class (AJAX)

Represents a geocode location.

Properties

Name Type Description

location Location The map location of this

geocode location match.

name string The name of this geocode

location match.

precision LocationPrecision The precision of this geocode

location match.

GeocodeRequestOptions Object

Contains the options for a geocode request.

Properties

Page 298: Bing Maps Ajax Controls Dk 70

298

Name Type Description

bounds LocationRect A location rectangle that defines

the boundaries of the area in which

to search for location results. The

default is the bounds of the map

view associated with this instance

of the SearchManager, which is

usually the current map view.

callback function The name of the function to call

when a successful result is

returned from the geocode request.

The callback function must accept

two parameters: result, which is a

GeocodeResult type, and a

userData object.

count number The maximum number of results to

return. Required. The maximum

number than can be returned is 20.

errorCallback function The name of the function to call

when the request is returned with

an error. The error callback

function must accept a

GeocodeRequestOptions object.

timeout number A number indicating how long to

wait, in seconds, for the geocode

request to return. The default value

is 5 seconds.

userData Object An object containing any data that

needs to be passed to the callback

when the request is completed.

where string A string containing the address or

place to be matched to a location

on the map. Required.

Example <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Page 299: Bing Maps Ajax Controls Dk 70

299

<html>

<head>

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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

Microsoft.Maps.loadModule('Microsoft.Maps.Search', { callback:

searchModuleLoaded });

}

function searchModuleLoaded()

{

var searchManager = new Microsoft.Maps.Search.SearchManager(map);

var geocodeRequest = {where:"1 Microsoft Way, Redmond, WA", count:10,

callback:geocodeCallback, errorCallback:errCallback};

searchManager.geocode(geocodeRequest);

}

function geocodeCallback(geocodeResult, userData)

Page 300: Bing Maps Ajax Controls Dk 70

300

{

alert("The first geocode result is " + geocodeResult.results[0].name + ".");

}

function errCallback(geocodeRequest)

{

alert("An error occurred.");

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:600px; height:600px;"></div>

</body>

</html>

See Also SearchManager Class

GeocodeResult Class (AJAX)

Represents a geocoded result.

Properties

Name Type Description

parsedAddress Address The parsed address of the

input query.

parsedKeyword string The parsed keyword string of

the input query.

parsedSeparator string The parsed separator of the

input query.

Page 301: Bing Maps Ajax Controls Dk 70

301

Name Type Description

results PlaceResult[] The geocoded results.

LocationPrecision Enum

Defines the match precision of a geocoded result.

Constants

Name Description

interpolated The geocoding service matched the location to

a point on the road using interpolation of

multiple geocoded sources.

rooftop The geocoding service matched the location to

the rooftop of a building.

MatchCode Enum

Defines the geocoding level of the location match found by the geocoder.

Constants

Name Description

none No match was found.

good The match was good.

ambiguous The match was ambiguous. Multiple results

were returned.

upHierarchy The match was found by a broader search.

modified The match was found, but possibly using a

modified query.

Page 302: Bing Maps Ajax Controls Dk 70

302

MatchConfidence Enum

Defines the confidence of the location match found by the geocoding service.

Constants

Name Description

high The confidence of the match is high.

medium The confidence of the match is medium.

low The confidence of the match is low.

unknown The confidence of the match is unknown.

PlaceResult Class

Represents a place result.

Properties

Name Type Description

bestview LocationRect The location rectangle that

defines the boundaries of

the best map view of the

place result.

location GeocodeLocation The geocoded location of

the best result.

locations GeocodeLocation[] The geocoded locations.

matchCode MatchCode The match code of the best

result.

matchConfidence MatchConfidence The match confidence of

the best result.

name string The name of the place

result, if one exists.

Page 303: Bing Maps Ajax Controls Dk 70

303

ReverseGeocodeRequestOptions Object

Contains options for a reverse geocode request.

Properties

Name Type Description

callback function The name of the function to call when a

successful result is returned from the

reverse geocode request. The callback

function must accept two parameters: a

result, which is a PlaceResult type, and

a userData object.

errorCallback function The name of the function to call when

the request is returned with an error.

The callback function must accept a

ReverseGeocodeRequestOptions

object.

location Location The location to use to match to

geographic entities and addresses.

timeout number A number indicating how long to wait,

in seconds, for the reverse geocode

request to return. The default value is 5

seconds.

userData Object An object containing any data that

needs to be passed to the callback

when the request is completed.

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

Page 304: Bing Maps Ajax Controls Dk 70

304

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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

Microsoft.Maps.loadModule('Microsoft.Maps.Search', { callback:

searchModuleLoaded });

}

function searchModuleLoaded()

{

var searchManager = new Microsoft.Maps.Search.SearchManager(map);

var reverseGeocodeRequest = {location:new Microsoft.Maps.Location(47.5, -121.5),

count:10, callback:reverseGeocodeCallback, errorCallback:errCallback};

searchManager.reverseGeocode(reverseGeocodeRequest);

}

function reverseGeocodeCallback(result, userData)

{

alert("The first result is " + result.name + ".");

}

Page 305: Bing Maps Ajax Controls Dk 70

305

function errCallback(request)

{

alert("An error occurred.");

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:600px; height:600px;"></div>

</body>

</html>

See Also SearchManager Class

SearchManager Class

Contains methods for returning search and location results.

Constructor

Name Definition Description

SearchManager SearchManager(map:Map) Initializes a new instance of

the SearchManager class.

Methods

Name Definition Retur

n

Value

Descriptio

n

geocode geocode(request:GeocodeRequestOptions Object) None Matches

the

address or

Page 306: Bing Maps Ajax Controls Dk 70

306

Name Definition Retur

n

Value

Descriptio

n

place

query in

the

specified

request

options to

a location

and

returns the

results to

the

request

options

callback

function.

reverseGeocod

e

reverseGeocode(request:ReverseGeocodeRequestOptio

ns Object)

None Matches

the

specified

location to

an

address

and

returns the

address

results to

the

specified

request

options

callback

function.

search search(request:SearchRequestOptions Object) None Performs

a search

based on

the

specified

request

options

and

Page 307: Bing Maps Ajax Controls Dk 70

307

Name Definition Retur

n

Value

Descriptio

n

returns the

results to

the

request

options

callback

function.

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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

Microsoft.Maps.loadModule('Microsoft.Maps.Search', { callback:

searchModuleLoaded });

Page 308: Bing Maps Ajax Controls Dk 70

308

}

function searchModuleLoaded()

{

var searchManager = new Microsoft.Maps.Search.SearchManager(map);

var searchRequest = {query:"pizza in Seattle, WA", count: 5,

callback:searchCallback, errorCallback:searchError};

searchManager.search(searchRequest);

}

function searchCallback(searchResponse, userData)

{

alert("The first search result is " + searchResponse.searchResults[0].name +

".");

}

function searchError(searchRequest)

{

alert("An error occurred.");

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:600px; height:600px;"></div>

</body>

</html>

SearchParseResult Class

Represents a search request parse result.

Page 309: Bing Maps Ajax Controls Dk 70

309

Properties

Name Type Description

keyword string The keyword of the input

query string.

location GeocodeLocation The geocoded location of

the input query string.

matchConfidence MatchConfidence The confidence of the

geocode match.

SearchRegion Class (AJAX)

Represents a search area.

Properties

Name Type Description

address Address The address of the center of

the search region.

geocodeLocations GeocodeLocation[] The geocoded locations.

explicitLocation GeocodeLocation The best geocoded

location.

mapBounds LocationRect A location rectangle that

defines the boundaries of

the search area.

matchCode MatchCode The match code of the

geocoded location.

matchConfidence MatchConfidence The match confidence of

the geocoded location.

source string A string indicating the

region used to infer the

location. The current values

are “Query” or “MapView”.

Page 310: Bing Maps Ajax Controls Dk 70

310

SearchRequestOptions Object

Contains options for a search request.

Properties

Name Type Description

callback function The name of the function to call

when a successful result is

returned from the search request.

The callback function must accept

two parameters: a result, which is

a SearchResponse, and a

userData object.

count number The maximum number of results to

return. Required. The maximum

number than can be returned is 20.

errorCallback function The name of the function to call

when the request is returned with

an error. The callback function

must accept a

SearchRequestOptions object.

query string The search string, such as “pizza

in Seattle, WA”. Either query or

what/where needs to be specified.

If both are specified, an error

occurs.

startIndex number The index of the first result in the

results. For example, if you had

already returned a first set of 10

search results and now wanted to

return the second set of 10 results,

you would specify 10 as the

startIndex and 10 as the count.

timeout number A number indicating how long to

wait, in seconds, for the search

request to return. The default value

is 5 seconds.

Page 311: Bing Maps Ajax Controls Dk 70

311

Name Type Description

entityType string The type of entities to find.

Currently only “Business” is

allowed.

userData Object An object containing any data that

needs to be passed to the callback

when the request is completed.

what string The business name, category, or

other item for which the search is

conducted. For example, “pizza” in

the search string “pizza in Seattle”.

where string The address or place name of the

area for which the search is

conducted. For example, “Seattle”

in the search string “pizza in

Seattle”.

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

function GetMap()

{

Page 312: Bing Maps Ajax Controls Dk 70

312

map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:

"Bing Maps Key", center: new Microsoft.Maps.Location(47.5, -122.3), zoom: 9 });

Microsoft.Maps.loadModule('Microsoft.Maps.Search', { callback:

searchModuleLoaded });

}

function searchModuleLoaded()

{

var searchManager = new Microsoft.Maps.Search.SearchManager(map);

var searchRequest = {what:"pizza", where:"Seattle", count:10,

callback:searchCallback, errorCallback:searchError};

searchManager.search(searchRequest);

}

function searchCallback(searchResponse, userData)

{

alert("The first search result is " + searchResponse.searchResults[0].name +

".");

}

function searchError(searchRequest)

{

alert("An error occurred.");

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:600px; height:600px;"></div>

Page 313: Bing Maps Ajax Controls Dk 70

313

</body>

</html>

See Also SearchManager Class

SearchResponse Class (AJAX)

Represents the results of a search request.

Properties

Name Type Description

alternateSearchRegions SearchRegion[] An array of alternate

search regions.

hasMore boolean A boolean indicating

whether there are more

results to return.

parseResults SearchParseResult[] An array containing the

parsed results of the

search.

responseSummary SearchResponseSummary The summary of the

response to the search

request.

searchRegion SearchRegion The region in which the

search was performed.

searchResults SearchResult[] A search result array

containing the search

results.

See Also SearchManager Class

Page 314: Bing Maps Ajax Controls Dk 70

314

SearchResponseSummary Class

Contains properties that summarize the search service response to a request.

Properties

Name Type Description

authResultCode number The authentication result code.

copyright string The copyright string.

errorMessage string The error message, if an error

occurred.

statusCode number The status code of the request.

traceId number A string representing a trace ID

to enable debugging of the

request.

SearchResult Class

Represents a distinct search result.

Properties

Name Type Description

address Address The address of the search

result.

city string The city of the search result.

country string The country of the search

result.

entityType string The entity type of the search

result.

hoursOfOperation string The hours of operation of the

entity defined by the search

result.

Page 315: Bing Maps Ajax Controls Dk 70

315

Name Type Description

id number The entity ID of the search

result.

location Location The location of the search

result.

name string The name of the entity

defined by the search result.

phone string The phone number of the

search result.

postalCode string The postal code of the search

result.

reviewCount number The number of user reviews

recorded for this search

result.

userRating number The average user rating for

the entity defined by the

search result.

website string The URL of the entity defined

by the search result.

Microsoft.Maps.Themes.BingTheme API Reference

This section contains reference documentation for the Microsoft.Maps.Themes.BingTheme

module, which allows you to use the latest Bing Maps site design.

Before you can access the Microsoft.Maps.Themes.BingTheme functionality, you must

first load this module using the loadModule method. Information about loading modules

is in the Module Loading Methods topic.

BingTheme Features When loaded, the Microsoft.Maps.Themes.BingTheme module updates certain visual aspects of

the map control with the latest Bing Maps design. To see the design changes, simply access the

corresponding API after loading the Microsoft.Maps.Themes.BingTheme module. The affected

map control features are listed below.

Page 316: Bing Maps Ajax Controls Dk 70

316

Map navigation bar The style, position, and size of the map navigation bar elements is

updated, including the map style drop-down, zoom, pan, and rotate controls.

Location bar The style, position, and size of the location bar, which describes the map

context (such as “World”), is updated.

Pushpins The style and behavior of point of interest pushpin icons is updated to match the

latest Bing Maps site design. This includes providing default info boxes for hover and click

events in addition to changing color based on the current imagery. Also, a new „pinmicro‟

value is available for the pushpin typeName option.

Polygons The style and behavior of polygons changes to match the latest Bing Maps

design, which includes providing info boxes for hover and click events.

Info boxes The InfoboxType styles are updated to match the latest Bing Maps site info box

style. This includes color change of the info box based on the current imagery.

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

function GetMap()

{

Microsoft.Maps.loadModule('Microsoft.Maps.Themes.BingTheme', { callback:

themesModuleLoaded });

}

Page 317: Bing Maps Ajax Controls Dk 70

317

function themesModuleLoaded()

{

// Load the map using the Bing theme style.

map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {credentials:

"Bing Maps Key", center: new Microsoft.Maps.Location(47.5, -122.3), zoom: 9, theme: new

Microsoft.Maps.Themes.BingTheme() });

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:600px; height:600px;"></div>

</body>

</html>

Microsoft.Maps.Traffic API Reference

This section contains reference documentation for the Microsoft.Maps.Traffic API, which contains

types that allow you to display traffic on your Bing Maps AJAX Control 7.0 map.

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

Page 318: Bing Maps Ajax Controls Dk 70

318

Name Definition Description

TrafficLayer TrafficLayer(map:Map) Initializes a new instance of

the TrafficLayer class.

Methods

Name Definition Return Value Description

getTileLayer getTileLayer() TileLayer Returns the traffic

layer.

hide hide() None Hides the traffic layer.

show show() None Displays the traffic

layer.

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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

Page 319: Bing Maps Ajax Controls Dk 70

319

Microsoft.Maps.loadModule('Microsoft.Maps.Traffic', { callback:

trafficModuleLoaded });

}

function trafficModuleLoaded()

{

var trafficLayer = new Microsoft.Maps.Traffic.TrafficLayer(map);

trafficLayer.show();

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:600px; height:600px;"></div>

</body>

</html>

Microsoft.Maps.VenueMaps API Reference

This section contains reference documentation for the Microsoft.Maps.VenueMaps API. Use the

VenueMapFactory Class to search for available venue maps.

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

DirectoryGrouping Enumeration

DirectorySortOrder Enumeration

Page 320: Bing Maps Ajax Controls Dk 70

320

Floor Class

Footprint Class

Metadata Class

NearbyVenue Class

NearbyVenueOptions Object

Polygon Class

Primitive Class

VenueMap Class

VenueMapCreationOptions Object

VenueMapFactory Class

Directory Class

Represents a venue map directory, which is a list of businesses and features found within the

venue.

Methods

Name Definition Return

Value

Description

addToDOM addToDom(div:HTMLElement,

sortOrder:DirectorySortOrder,

to_group_or_not:DirectoryGrouping)

None Adds the venue

map directory to

the DOM

(document

object model).

The specified

div becomes the

parent element

of the venue

map directory.

This method

does nothing if

the

createUIElemen

ts is not called

first.

createUIElement

s

createUIElements() None Creates the

necessary UI

elements and

Page 321: Bing Maps Ajax Controls Dk 70

321

Name Definition Return

Value

Description

data structures

to visualize the

venue map

directory. After

this method is

called, use the

addToDOM

method to add

the elements to

the DOM.

handleMouseCli

ck

handleMouseClick(e:{eventArgs:MouseEventArg

s, Primitive})

None The base

method to call if

you override the

click event.

handleMouseOu

t

handleMouseMouseOut(e:{eventArgs:MouseEvent

Args, Primitive})

None The base

method to call if

you override the

mouseout

event.

handleMouseOv

er

handleMouseOver(e:{eventArgs:MouseEventArgs

, Primitive})

None The base

method to call if

you override the

mouseover

event.

isInDOM isInDOM() boolea

n

Returns a

boolean

indicating

whether the

venue map

directory is in the

DOM.

removeFromDO

M

removeFromDOM() None Removes the

venue map

directory from

the DOM. It is

recommended

that you use this

method to

Page 322: Bing Maps Ajax Controls Dk 70

322

Name Definition Return

Value

Description

remove the

venue map

directory from

the DOM instead

of using the

removeChild

method of the

DOM.

setHeight setHeight(h:int or double) None Sets the height

of the venue

map directory,

as a percentage

of the base

map‟s height or

in absolute

pixels. For

example, to set

the directory as

90% of the base

map‟s height,

call

setHeight(.9).

To set the height

as 800 pixels,

call

setHeight(800).

Events

Name Arguments Description

click eventArgs:MouseEventArgs,

Primitive

Occurs when the mouse is

used to click a list item in

the directory. If no handler

is specified for this event,

then the list item is

selected.

mouseout eventArgs:MouseEventArgs, Occurs when the mouse

Page 323: Bing Maps Ajax Controls Dk 70

323

Name Arguments Description

Primitive cursor moves out of the

area covered by a list item

in the directory. If no

handler is specified for this

event, then the highlight is

removed from the directory

list item.

mouseover eventArgs:MouseEventArgs,

Primitive

Occurs when the mouse is

over a list item in the

directory. If no handler is

specified for this event,

then the list item is

highlighted.

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var venue = null;

var Events = null;

var clickhandler = null;

var mouseoverhandler = null;

var mouseouthandler = null;

function GetMap()

{

// Initialize the map

Page 324: Bing Maps Ajax Controls Dk 70

324

map = new

Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Bing Maps Key"});

Events = Microsoft.Maps.Events;

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

}

function successCallback(venueObj)

{

venue = venueObj;

map.setView(venue.bestMapView, true);

venue.show();

venue.directory.createUIElements();

addDirectory();

}

function addDirectory()

{

if (venue && venue.directory && !venue.directory.isInDOM())

{

var directory = venue.directory;

directory.addToDOM(document.getElementById('leftsidebar'),

Microsoft.Maps.VenueMaps.DirectorySortOrder.alphabetical,

Microsoft.Maps.VenueMaps.DirectoryGrouping.none);

directory.setHeight(1.0);

clickhandler = Events.addHandler(directory, 'click', clickHandler);

mouseoverhandler = Events.addHandler(directory, 'mouseover', mouseoverHandler);

Page 325: Bing Maps Ajax Controls Dk 70

325

mouseouthandler = Events.addHandler(directory, 'mouseout', mouseoutHandler);

}

}

function removeDirectory()

{

if (venue)

{

venue.directory.removeFromDOM();

Events.removeHandler(clickHandler);

Events.removeHandler(mouseoverHandler);

Events.removeHandler(mouseoutHandler);

}

}

function clickHandler(e)

{

var p = e.primitive;

venue.directory.handleMouseClick(e);// call base method

display('Clicked Store <br/>' +

'Name : ' + p.name + '<br/>' +

'Id: ' + p.id+ '<br/>' +

'YPId : ' + p.businessId + '<br/>' +

'Category Name : ' + p.categoryName + '<br/>' +

'Category Id : ' + p.categoryId + '<br/>' +

'Optimal Zoom: ' + p.optimalZoom(0.8) + '<br/>' +

'Floor: ' + p.floor.name + '<br/>' +

'Center : ' + p.center + '<br/>' +

'Coordinates : ' + p.locations + '<br/>' +

'Bounding Box: ' + p.bounds);

}

function mouseoverHandler(e)

{

Page 326: Bing Maps Ajax Controls Dk 70

326

var p = e.primitive;

venue.directory.handleMouseOver(e);// call base method

display('Mouse Over <br/>' +

'Name : ' + p.name + '<br/>' +

'Id: ' + p.id+ '<br/>' +

'YPId : ' + p.businessId + '<br/>' +

'Category Name : ' + p.categoryName + '<br/>' +

'Category Id : ' + p.categoryId + '<br/>' +

'Optimal Zoom: ' + p.optimalZoom(0.8) + '<br/>' +

'Floor: ' + p.floor.name + '<br/>' +

'Center : ' + p.center + '<br/>' +

'Coordinates : ' + p.locations + '<br/>' +

'Bounding Box: ' + p.bounds);

}

function mouseoutHandler(e)

{

var p = e.primitive;

venue.directory.handleMouseOut(e);// call base method

display('Mouse Out <br/>' +

'Name : ' + p.name + '<br/>' +

'Id: ' + p.id+ '<br/>' +

'YPId : ' + p.businessId + '<br/>' +

'Category Name : ' + p.categoryName + '<br/>' +

'Category Id : ' + p.categoryId + '<br/>' +

'Optimal Zoom: ' + p.optimalZoom(0.8) + '<br/>' +

'Floor: ' + p.floor.name + '<br/>' +

'Center : ' + p.center + '<br/>' +

'Coordinates : ' + p.locations + '<br/>' +

'Bounding Box: ' + p.bounds);

}

function display(html)

{

Page 327: Bing Maps Ajax Controls Dk 70

327

var e = document.getElementById('rightsidebar');

e.innerHTML = html;

}

</script>

</head>

<body onload="GetMap();">

<div id='leftsidebar' style="position:absolute; top:0px; left:0px; width:300px;"></div>

<div id='mapDiv' style="position:absolute; top:0px; left:310px; width:500px;

height:500px;"></div>

<div id='rightsidebar' style="position:absolute; top:0px; left:820px; width:300px;

height:500px;"></div>

<input style="position:absolute; top:520px; left:310px" type='button'

onclick='addDirectory();' value='Add Directory' />

<input style="position:absolute; top:520px; left:470px" type='button'

onclick='removeDirectory();' value='Remove Directory' />

</body>

</html>

DirectoryGrouping Enumeration

Contains constants that specify how listings in a venue map directory are grouped.

Constants

Name Description

byCategory The listings in the directory are grouped by

category.

none The listings in the directory are not grouped.

They are displayed in a flat list.

DirectorySortOrder Enumeration

Contains constants that specify the way a venue map directory is sorted.

Page 328: Bing Maps Ajax Controls Dk 70

328

Constants

Name Description

alphabetical The listings in the directory are sorted

alphabetically.

byFloor The listings in the directory are sorted by floor.

Floor Class

Represents one floor map of a venue map.

Properties

Name Type Description

name string The name of the floor.

primitives Primitive[] An array of Primitive objects

that represent the points of

interest (for example, stores)

on this venue floor.

zoomRange double[] An array of doubles indicating

the minimum and maximum

zoom levels where imagery is

available for this venue map

floor.

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

Page 329: Bing Maps Ajax Controls Dk 70

329

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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:ShowVenue,

error:ShowError});

}

function ShowVenue(venue)

{

// Set the map view

map.setView(venue.bestMapView);

Page 330: Bing Maps Ajax Controls Dk 70

330

venue.show();

DisplayVenueFloorInfo(venue);

}

function ShowError()

{

// Show an error

alert("An error occurred trying to create the venue map.");

}

function DisplayVenueFloorInfo(venue)

{

var floors = "Available floor maps for " + venue.name +":\n";

for(var i in venue.floors)

{

floors = floors + venue.floors[i].name + "\n";

}

// Display the floor info

alert(floors);

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:500px; height:500px;"></div>

Page 331: Bing Maps Ajax Controls Dk 70

331

</body>

</html>

Footprint Class

Represents the footprint of the venue map.

Properties

Name Type Description

polygons Polygon[] The shapes that make up the

footprint of this venue.

zoomRange double[] 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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

function GetMap()

{

Page 332: Bing Maps Ajax Controls Dk 70

332

// 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:ShowVenue,

error:ShowError});

}

function ShowVenue(venue)

{

// Set the map view

map.setView(venue.bestMapView);

venue.show();

DisplayVenueInfo(venue);

}

function ShowError()

{

// Show an error

alert("An error occurred trying to create the venue map.");

}

Page 333: Bing Maps Ajax Controls Dk 70

333

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

// Display the venue info

alert(venueinfo);

}

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

CenterLat number The latitude of the center

location of the venue map.

CenterLong number The longitude of the center

location of the venue map.

DefaultFloor string The ID of the default floor of

the venue map.

FloorHeader string A string used in the floor bar of

the venue map.

Floors Floor[] An array containing the floors

Page 334: Bing Maps Ajax Controls Dk 70

334

Name Type Description

of the venue map.

Footprint Footprint The footprint of the venue

map.

MapId string The unique ID of the venue

map.

MapType string A string describing the venue

map type (for example, “mall”).

Name string The name of the venue map.

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

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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

Page 335: Bing Maps Ajax Controls Dk 70

335

Microsoft.Maps.loadModule('Microsoft.Maps.VenueMaps', { callback:

venuemapsModuleLoaded });

}

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

}

Page 336: Bing Maps Ajax Controls Dk 70

336

</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 double The distance, in meters, to the

venue.

metadata Metadata The venue map 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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

Page 337: Bing Maps Ajax Controls Dk 70

337

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

Microsoft.Maps.loadModule('Microsoft.Maps.VenueMaps', { callback:

venuemapsModuleLoaded });

}

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

}

Page 338: Bing Maps Ajax Controls Dk 70

338

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.

location Location The center of the circle in which

to search for nearby venue

maps.

map Map The base map.

radius double The radius, in meters, of the

circle in which to search for

nearby venue maps.

Example <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Page 339: Bing Maps Ajax Controls Dk 70

339

<html>

<head>

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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

Microsoft.Maps.loadModule('Microsoft.Maps.VenueMaps', { callback:

venuemapsModuleLoaded });

}

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

}

Page 340: Bing Maps Ajax Controls Dk 70

340

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>

Polygon Class (Venue Map)

Defines the shape of venue map entities.

Properties

Name Type Description

bounds LocationRect The rectangle that defines the

bounding box for the polygon.

center Location The center of the polygon.

locations Location[] The locations that define the

vertices of the polygon.

Primitive Class

Represents a venue map primitive, which represents a venue map entity.

Page 341: Bing Maps Ajax Controls Dk 70

341

Properties

Name Type Description

bounds LocationRect The rectangle that defines the

bounding box for the

primitive.

businessId string The Yellow Pages ID for the

entity.

categoryId string The Yellow Pages business

category ID for the entity.

categoryName string The Yellow Pages business

category name for the entity.

center Location The location of the center of

the primitive.

floor Floor The floor to which this

primitive belongs.

id string The unique ID of the entity.

locations Location[] An array of locations that

represent the vertices of the

primitive.

name string The name of the entity.

Methods

Name Definition Return Type Description

highlight highlight() None Highlights the

primitive.

unhighlight unhighlight() None Removes the

highlighting of the

primitive.

Page 342: Bing Maps Ajax Controls Dk 70

342

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var vmaps = null;

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

Page 343: Bing Maps Ajax Controls Dk 70

343

}

function ShowVenue(venue)

{

// Set the map view

map.setView(venue.bestMapView);

venue.show();

Microsoft.Maps.Events.addHandler(venue, 'click', DisplayVenueEntity);

alert("Click on the venue map to display entity info.");

}

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>

Page 344: Bing Maps Ajax Controls Dk 70

344

VenueMap Class

Represents a venue map. An example of a venue map is a mall.

Properties

Name Type Description

address string The full address of the venue.

bestMapView ViewOptions The best map view of the

venue map.

businessId string The Yellow Pages ID for the

venue map.

center Location The location of the center of

the venue map.

defaultFloor string The floor that is displayed if

no floor is specified.

directory Directory The venue map directory,

which is a list of businesses

and features found within the

venue

floorHeader string The header for floors for this

venue map. For example, for

a mall the floor header would

be “Level”.

floors Floor[] An array, where each element

represents a floor of the

venue.

footprint Footprint The shapes that make up the

venue map.

id string The unique venue map ID.

name string The name of the venue

represented by the venue

map.

phoneNumber string The phone number for the

venue represented by the

venue map.

Page 345: Bing Maps Ajax Controls Dk 70

345

Name Type Description

type string The venue map type, such as

“Mall”.

Methods

Name Definition Return Type Description

dispose dispose() None Disposes the

venue map object.

getActiveFloor getActiveFloor() string Returns the venue

floor map that is

currently

displayed.

hide hide() None Hides the venue

map.

setActiveFloor setActiveFloor(floor:string) None Displays the floor

map for the

specified floor.

show show() None Displays the venue

map.

Events

Name Arguments Description

click eventArgs:Primitive Occurs when the mouse is

used to click the venue map.

close None Occurs when the close

button on the venue map is

clicked.

footprintclick eventArgs:Primitive Occurs when the detailed

map of the venue is clicked.

mouseout eventArgs:Primitive Occurs when the mouse

cursor moves out of the area

covered by the venue map.

Page 346: Bing Maps Ajax Controls Dk 70

346

Name Arguments Description

mouseover eventArgs:Primitive Occurs when the mouse

cursor is over the 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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

var venue = null;

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

{

Page 347: Bing Maps Ajax Controls Dk 70

347

// Create the venue map

var vmaps = new Microsoft.Maps.VenueMaps.VenueMapFactory(map);

vmaps.create({venueMapId: 'bingmapsteam-bellevuesquare', success:SetVenue});

}

function SetVenue(venueObj)

{

venue = venueObj;

}

function ShowVenue()

{

// Set the map view

map.setView(venue.bestMapView);

venue.show();

}

function HideVenue()

{

venue.hide();

}

</script>

</head>

<body onload="GetMap();">

<div id='mapDiv' style="position:relative; width:500px; height:500px;"></div>

Page 348: Bing Maps Ajax Controls Dk 70

348

<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

method of the VenueMapFactory.

Page 349: Bing Maps Ajax Controls Dk 70

349

Name Type Description

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"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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

Page 350: Bing Maps Ajax Controls Dk 70

350

var vmaps = new Microsoft.Maps.VenueMaps.VenueMapFactory(map);

vmaps.create({venueMapId: 'bingmapsteam-bellevuesquare', success:ShowVenue,

error:ShowError});

}

function ShowVenue(venue)

{

// Set the map view

map.setView(venue.bestMapView);

venue.show();

}

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

Page 351: Bing Maps Ajax Controls Dk 70

351

Name Definition Description

VenueMapFactory VenueMapFactory(map:Map) Initializes a new instance of

the VenueMapFactory class.

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

Page 352: Bing Maps Ajax Controls Dk 70

352

<script type="text/javascript"

src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<script type="text/javascript">

var map = null;

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

}

function DisplayInfobox(venue)

{

// Set the map view

map.setView(venue.bestMapView);

venue.show();

// Put an info box label on the map

mapCenter = map.getTargetCenter();

Page 353: Bing Maps Ajax Controls Dk 70

353

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>

Bing Maps AJAX Control 7.0 Supported Browsers

This topic contains information about browser support for the Bing Maps AJAX Control 7.0.

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 Supported on the PC

Internet Explorer 8.0 Supported on the PC

Internet Explorer 9.0 Supported on the PC

Firefox 3.6 Supported on the PC and the Mac

Firefox 4.0 Supported on the PC and the Mac

Page 354: Bing Maps Ajax Controls Dk 70

354

Desktop Browser Description

Safari 5 Supported on the Mac

Google Chrome Supported on the PC

Mobile Browser

Apple 3GS/4.0 iPhone Browser

Google Android 2.X Browser

Research in Motion (RIM) BlackBerry 6.0

Browser

Bing Maps AJAX Control 7.0 Developer Resources

This topic contains support resources and contact information.

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 [email protected].

Licensing Questions If you are interested in finding out more about Bing Maps or have questions about licensing Bing

Maps, you can request information at Contact Us: Bing Maps for Enterprise. From North, Central,

and South America, you can also contact Bing Maps by calling (800) 426-9400, ext. 11315.


Recommended