In this article, we will learn how to integrate and demonstrate how to create interactive maps using the Bing Maps V8 Web Control. We will also show you how to use this API to generate maps, capture the values, and potentially save them to a database in order to create rich interfaces for your users to easily generate dynamic Bing Maps on their own.

In this example we will be using ColdFusion on the server, however, any web-based technology can be used, the only requirement for this modern SDK is using either JavaScript or TypeScript and having a Bing Maps API key

Bing Maps V8 Web Control Example


As we have seen in our last article, creating the code to generate a dynamic map that allows your users to pan and zoom is easy and it only requires a few lines of code. However, you can also use the Bing Maps Web Control to create interfaces that will generate the code for you. Please click on the button below to see the V8 Web Control in action.


Integrating the Bing Maps V8 Web Control Into Your Own Web Application


It is relatively easy to incorporate the Bing Maps Web Control into your own web application. I have incorporated a WYSIWYG Bing Maps interface to create static maps as seen in the image below. This allows Galaxie Blog administrators to create a static map for their own blog posts. 

The following code will allow you to integrate the map control into your own web page to allow users to generate their own maps using a familiar Bing Maps interface. I will explain the key concepts below.

Click on the button below to view the code. 


Dissecting the Code

The following code has three sections- the JavaScript functions that include the GetMap, suggestionSelected, and saveMap functions, the CSS that sets the properties for the various Bing Maps containers, and the HTML

In this article, we are going to focus on the Bing Maps API JavaScript code. 


If you want to immediately start using the Bing Maps Control in your own page you can copy the JavaScript verbatim with a few potential changes:

In this example, the map declaration in the GetMap() function has a dedicated empty DIV element that Bing Maps will use to render the map after a location has been entered. In this example, the Bing Maps object is mapped to an empty myMap DIV element at the very bottom of the HTML code.


map = new Microsoft.Maps.Map('#myMap', {});

The AutoSuggest Manager declaration, also inside of the GetMap() function, requires the ID of the element used for the location search input, in this case, searchBox, along with the ID of the div container that wraps the client-side code, which in our example is searchBoxContainer.


manager.attachAutosuggest('#searchBox', '#searchBoxContainer', suggestionSelected);

I am also saving the location that was typed in and saving the geo-coordinates provided by the Bing Maps control into two hidden form fields like so:


// Save the location data into a hidden form
// console.log(result)
$("#mapAddress").val(result.formattedSuggestion);
$("#mapCoordinates").val(result.location.latitude + ',' + result.location.longitude);

If you're copying and pasting the code here in its entirety and not changing the HTML, these changes are not necessary.


Overview of the Bing Maps AutoSuggest Manager

The AutoSuggest Manager accepts a string and returns a list of addresses or places that best match the provided string. In our example, we are passing the location that the user entered into the searchBox text input in the HTML and parsing and saving the results.


Overview of the Bing Maps SuggestionResult Object

After the location (ie a geographical name) is entered, the AutoSuggest Manager will send back a SuggestionResult object with a variety of properties. The properties that we are using here are:

  • a location object with the latitude and longitude
  • the formattedLocation which is a simple formatted string
  • and bestView, a Bing Maps location object which is a rectangle map representation with the height and width determined by the autosuggest module

Creating Custom Push Pins

The code to create the push pin inside of the suggestionSelected function contains logic to anchor the push pin. The code that I am using is standard for the default location marker. 


// Create a custom Pushpin
var pin = new Microsoft.Maps.Pushpin(result.location, {
	anchor: new Microsoft.Maps.Point(12, 39)
});

// Show the suggestion as a pushpin and center map over it.
map.entities.push(pin);

Setting the MapView Options

Typically, the setView method is used to determine the properties of the map. For example, we can set the map zoom, and the map type (road, aerial, etc), among other settings. Here, we are letting the AutoSuggest Manager determine the best map properties based on the search string that was entered.


map.setView({ bounds: result.bestView });

Saving the Latitude and Longitude Into Hidden Forms

At the end of the suggestionSelected function, save the suggested location and the latitude and longitude into a hidden form to preserve the results.


// Save the location data into a hidden form
$("#mapAddress").val(result.formattedSuggestion);
$("#mapCoordinates").val(result.location.latitude + ',' + result.location.longitude);

Extracting the AutoSuggest Manager Results

Typically, I use the saveMap function to post the results using AJAX to the server and save them to a database. This allows me to put the Bing Maps Control in front of my users and allow them to generate their own maps for a blog post using a WYSIWYG interface. However, here I am omitting the extraneous code and just showing how to extract the results returned by the Bing Maps Control.


function saveMap(){
	// The mapId determines the map type- ie 'road', 'Aerial', etc.
	var mapTypeId = map.getImageryId();
	var mapZoomLevel = map.getZoom();
	// Get the map address from the hidden form that we populated earlier
	var mapAddress = $("#mapAddress").val();
	var mapCoordinates = $("#mapCoordinates").val();
}

HTML

The essential parts of the API in the HTML are the call to the  Bing Maps Control script that passes your Bing Maps Key to Bing Maps, the searchBox text input container, the submit button that invokes the saveMap JavaScript function, and the empty myMap DIV that will be used to generate the map at the bottom of the page.


<!--- Call the mapcontrol script. --->
<script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=<cfoutput>#application.bingMapsApiKey#</cfoutput>' async defer></script>

<div class="directionsContainer">
	<div id="searchBoxContainer" class="k-content">
		<input type="hidden" name="mapAddress" id="mapAddress" value="">
		<input type="hidden" name="mapCoordinates" id="mapCoordinates" value="">
		<table align="center" width="95%" class="k-content" cellpadding="2" cellspacing="0">
			<tbody><tr height="1px">
				<td align="left" valign="top" colspan="2" class="k-content"></td>
			</tr>
			<tr>
				<td colspan="2"> 
					<p>Type in a location or address in the location form to drop a pin. An autosuggest will appear below the location input to help you select the proper location.</p>

					<p>You can also use the map controls to the right to customize the map type (road, arial, etc) and set the zoom. If you want a different location pin, indicate the path to the image in the field below.</p> 
					<p>If the location is a city, state, or region, you can highlight the location by clicking on the highlight checkmark below. When you're satisfied with the look and feel of the map, click on the submit button below.</p>
				</td>
			</tr>
			<!-- Border -->
			<tr height="2px">
			  <td align="left" valign="top" colspan="2" class="k-content"></td>
			</tr>
			<tr height="2px">
			  <td align="left" valign="top" colspan="2" class="border k-alt"></td>
			</tr>
			<!-- Form content -->
			<tr>
				<td align="right" class="k-alt"> 
					<label for="searchBox">Location</label>
				</td>
				<td class="k-alt">
					<input id="searchBox" name="searchBox" value="" class="k-textbox" style="width: 85%; box-sizing: content-box;" autocorrect="off" autocapitalize="off" aria-controls="as_containerSearch_searchBox" aria-owns="as_containerSearch_searchBox" aria-expanded="false" aria-autocomplete="both" type="search">
				</td>
			</tr>
			<!-- Border -->
			<tr height="2px">
			  <td align="left" valign="top" colspan="2" class="k-alt"></td>
			</tr>
			<tr valign="middle">
			  <td colspan="2">
				<button id="createMap" class="k-button k-primary" type="button" onclick="saveMap()">Submit</button>
			  </td>
			</tr>   
		</tbody></table>
	<div class="MicrosoftMap" style="position: absolute;"></div></div>
</div>

<!--- Map container to the right of the screen holding the map--->
<div id="myMap"></div>

Further Reading

The Bing Maps API is one of the best-documented APIs that I have ever used- and it is one of the reasons why I chose to use Bing Maps instead of Google. Here is a small collection of some of the sites that I refer to when using the Bing Maps API:

Happy Mapping!