BING MAPS API INTEGRATION WITH DYNAMICS 365 CRM

LEARN HOW TO CREATE ADDRESS AUTOSUGGESTION
BING MAPS API INTEGRATION WITH DYNAMICS 365 CRM

The evolution of maps has changed the way individuals explore the world. The transition from inaccurate physical maps to highly accurate digital maps has been mind boggling. It has also changed the way businesses are reaching out to their customers. To ensure growth, most businesses are employing CRMs, such as Microsoft Dynamics 365. Such tools have enabled businesses with improved sales, service, marketing and higher revenue generation. Taking a leap further, commercial organizations are now integrating the power of Bing Maps with the versatile Dynamics CRM to scale new heights of success.

Custom POI hosting, search, batch geocoding, and truck routing are some of the exclusive features that Bing Maps offers. Integrating your CRM with Bing Maps is really pocket friendly. If you use the Bing Map’s tools for development and testing only, it allows you to make 125000 billable calls in a year. Similarly, if the users integrates Bing Maps in Windows application, they get 50000 calls a day for education or Non-Profit usage. Similarly, if the users integrate Bing Maps in Windows application, they get 50000 calls a day for education or Non-Profit usage.

Businesses can use session IDs with Bing Maps HTML5 Web Control to make 25 free calls in one session. Beyond this, the enterprise license charges are based on the number of API calls teams make rather than varying by which APIs we call.

Turn Bing Maps Feature ON Or OFF For Our Organization CRM Product 
  1. Browse to the Power Platform admin center and sign in using administrator credentials.
  2. Go to Environments and select environment such as dev/prod/test and further navigate to Settings and Product.
  3. Click on Features option.
  4. Under the Embedded content, turn on Bing Maps
  5. And finally, select Save and our Bing Maps feature turn to ON state.

After turning on Bing Maps feature into Power Platform, open make.powerapps.com and you will notice the Bing Maps icon on top navigation bar inside Insert option.

Get Bing Maps API Basic Key For Free

Simply search- Bing Maps API Basic key for free onto any browser or just paste below-mentioned URL into your browser:

https://www.microsoft.com/en-us/maps/create-a-bing-maps-key/

We will see this option which is Start for Free

And you will be navigated to this page. Click on Get a free Basic Key option.

Login as developer login and provide necessary credentials.

Click on My Account dropdown and you will see My Keys option. Click on it and you will be directed to Bing Maps API key. Copy and paste the key and store it in your records for future references.

After getting the Bing Maps API key as a prerequisite, you need to move forward with further steps, such as Auto Suggestion Address field and Distance Calculation between two addresses.

Integrating Auto Suggestion Address Field into Dynamics 365 CRM

 Step 1: Create an HTML web resource which will contain HTML, CSS, and JavaScript code.

Open any code editor where you can write above language code. We usually prefer VS Code.

Step 2: Copy and paste this code into your editor. We will go through the code section by section.

<html>
<head>
<title>autosuggestuiwithoutmapHTML</title>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>
<style type=”text/css”>
body {
margin: 0;
padding: 0;
overflow: hidden;
font-family: ‘Segoe UI’, Helvetica, Arial, Sans-Serif
}
</style>
<meta><meta><meta><meta><meta><meta>
</head>
<body onfocusout=”parent.setEmailRange();” style=”overflow-wrap: break-word;”>
<div id=”printoutPanel”></div>
<div id=”searchBoxContainer” >
<input type=”text” id=”searchBox” placeholder=”Search your address here…” autocomplete=”off” style=”display: block;width: 450px;height: 35px;font-size: 15px;line-height: 1.42857;
color: rgb(85, 85, 85);background-color: rgb(255, 255, 255);background-image: none;overflow: scroll;
border: 1px solid rgb(204, 204, 204);border-radius: 0px;box-shadow: rgba(0, 0, 0, 0.075) 0px 1px 1px inset;
transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;box-sizing:content-box;/* padding: 10px; */padding-left: 12px;”>
</div>
<script type=”text/javascript”>
function setClientApiContext(formContext) {
// Optionally set Xrm and formContext as global variables on the page.
window._formContext = formContext;
}

function loadMapScenario() {
Microsoft.Maps.loadModule(‘Microsoft.Maps.AutoSuggest’, {
callback: onLoad,
errorCallback: onError
});

function onLoad() {
var options = {
maxResults: 5
};

var manager = new Microsoft.Maps.AutosuggestManager(options);
manager.attachAutosuggest(‘#searchBox’, ‘#searchBoxContainer’, selectedSuggestion);
}

function onError(message) {
document.getElementById(‘printoutPanel’).innerHTML = message;
}

function selectedSuggestion(suggestionResult)
{
document.getElementById(‘printoutPanel’).innerHTML =
‘Street Address: ‘ + suggestionResult.address.addressLine +
‘<br> City: ‘ + suggestionResult.address.locality +
‘<br> State Or Province: ‘ + suggestionResult.address.adminDistrict +
‘<br> Postal Code: ‘ + suggestionResult.address.postalCode+
‘<br> Country: ‘ + suggestionResult.address.countryRegion;
_formContext.getAttribute(“crm-streetfield”).setValue(suggestionResult.address.addressLine);
_formContext.getAttribute(“crm-cityfield “).setValue(suggestionResult.address.locality);
_formContext.getAttribute(“crm-countryfield”).setValue(suggestionResult.address.countryRegion);
_formContext.getAttribute(“crm-statefield”).setValue(suggestionResult.address.adminDistrict);
}
}

</script>
<script type=”text/javascript” src=”https://www.bing.com/api/maps/mapcontrol?key={Your Bing Maps API Key} &amp;callback=loadMapScenario” async=”” defer=””></script>

</body>
</html>

Step 3: In this section, we will go through the HTML code.
<head>
<title>autosuggestuiwithoutmapHTML</title>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>
<style type=”text/css”>
body {
margin: 0;
padding: 0;
overflow: hidden;
font-family: ‘Segoe UI’, Helvetica, Arial, Sans-Serif
}
</style>
<meta><meta><meta><meta><meta><meta>
</head>

Here, you are creating normal HTML page section. You are also required to add title and inline CSS formatting for your body section. This can be done by adjusting margins, padding and font style.

Step 4: In this section we will go through the search field code.

In first div tag, with printoutpanel as id will act as panel in our form.

In second div tag, with searchBoxContainer as id, you will create search field with searchBox as id, where user will be able to input address.

As soon as the user starts typing an address, the Bing Maps API will display address suggestions.

<body onfocusout=”parent.setEmailRange();” style=”overflow-wrap: break-word;”>

    <div id=”printoutPanel”></div>

    <div id=”searchBoxContainer” >

    <input type=”text” id=”searchBox” placeholder=”Search your address here…” autocomplete=”off” style=”display: block;width: 450px;height: 35px;font-size: 15px;line-height: 1.42857;

        color: rgb(85, 85, 85);background-color: rgb(255, 255, 255);background-image: none;overflow: scroll;

        border: 1px solid rgb(204, 204, 204);border-radius: 0px;box-shadow: rgba(0, 0, 0, 0.075) 0px 1px 1px inset;

        transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;box-sizing:content-box;/* padding: 10px; */padding-left: 12px;”>

    </div>

Step 5: Let’s go deep into below section of important codes:

<script type=”text/javascript”>

        function setClientApiContext(formContext) {

    // Optionally set Xrm and formContext as global variables on the page.

    window._formContext = formContext;

    }

        function loadMapScenario() {

            Microsoft.Maps.loadModule(‘Microsoft.Maps.AutoSuggest’, {

                callback: onLoad,

                errorCallback: onError

            });

            function onLoad() {

                var options = {

                    maxResults: 5

                };

                var manager = new Microsoft.Maps.AutosuggestManager(options);

                manager.attachAutosuggest(‘#searchBox’, ‘#searchBoxContainer’, selectedSuggestion);

            }

            function onError(message) {

                document.getElementById(‘printoutPanel’).innerHTML = message;

            }

The actual JavaScript code starts now. It’s here where we will use Bing Maps APIs.

In Dynamics CRM v9, Xrm.Page and many other features have been denounced. That’s why we need to use the execution context. However, we can’t pass execution context onto the HTML web resource as a parameter. To achieve this, we will create JavaScript function as below:

function passExecutionContext (executionContext)

{

    var formContext = executionContext.getFormContext();

    var wrControl = formContext.getControl(“WebResource_ ourWebResourceName “);

    if (wrControl)

    {

        wrControl.getContentWindow().then(

            function (contentWindow)

            {

                contentWindow.setClientApiContext(formContext);

            })

    }

}

In this line of code, we are passing the web resource name, which we created before with the above line of code.

var wrControl = formContext.getControl(“WebResource_ourWebResourceName”);

The address search web resource which we created earlier you will pass as execution context on load of the form.

window._formContext = formContext;

You will create global variable named _formContext. This variable can be used anywhere in our address search web resource also inside any method with which we can access or set values to any CRM fields.

Step 6: Let’s split code function by function to get deep insights of code.

function loadMapScenario() {

            Microsoft.Maps.loadModule(‘Microsoft.Maps.AutoSuggest’, {

                callback: onLoad,

                errorCallback: onError

            });

LoadMapScenario function is the callback function which is assigned to callback property in script tag where we are calling BingMaps API with its key.

There is built-in API function called AutoSuggest provided by Microsoft.Maps API.

Inside this function, you are assigning callback property with onload function. This onload function will be our first function which will be executed after loadMapScenario function in our web resource.

There is another property named errorCallback which suggests you to define error function in code i.e. onError.

Any exception occurred during web resource execution will be handled by onError function and error message will be displayed to user on the screen.

function onLoad() {

                var options = {

                    maxResults: 5

                };

                var manager = new Microsoft.Maps.AutosuggestManager(options);

                manager.attachAutosuggest(‘#searchBox’, ‘#searchBoxContainer’, selectedSuggestion);

            }

In the onload function, we are defining maxResults parameter as 5 which can be changed to any number as per requirement.

This property will display 5 address suggestions to the user in search box container.

You will create variable named manager of AutosuggestManager class type by passing options as parameter.

There is inbuilt function i.e. attachAutoSuggest which takes three parameters as input.

First parameter is searchBox which is the ID of input field basically search field where user can type address. Second parameter is searchBoxContainer which is the ID of div tag i.e. container where address suggestions will be displayed.

Last parameter selectedSuggestion is the function name where you will write your code to perform necessary operations as per your requirement. Such as displaying specific address fields onto screen setting CRM fields with the address choosen by user.

Step 7:

function selectedSuggestion(suggestionResult)

            {

                  document.getElementById(‘printoutPanel’).innerHTML =

                    ‘Street Address: ‘ + suggestionResult.address.addressLine +

                    ‘<br> City: ‘ + suggestionResult.address.locality +

                    ‘<br> State Or Province: ‘ + suggestionResult.address.adminDistrict +

                    ‘<br> Postal Code: ‘ + suggestionResult.address.postalCode+

                    ‘<br> Country: ‘ + suggestionResult.address.countryRegion;

               _formContext.getAttribute(“crm-streetfield”).setValue(suggestionResult.address.addressLine);

               _formContext.getAttribute(“crm-cityfield “).setValue(suggestionResult.address.locality);

               _formContext.getAttribute(“crm-countryfield”).setValue(suggestionResult.address.countryRegion);

               _formContext.getAttribute(“crm-statefield”).setValue(suggestionResult.address.adminDistrict);

            }

        }

    </script>

    <script type=”text/javascript” src=”https://www.bing.com/api/maps/mapcontrol?key={Your Bing Maps API Key} &amp;callback=loadMapScenario” async=”” defer=””></script>

</body>

</html>

In the selected Suggestion function, we are getting parameter as suggestionResult from AutoSuggestManager API, which contains a collection of all the fields that you want to display.

The Address API of Bing Maps contains Address Line, Locality, Admin, District, Postal Code, Country, Region, which contains street address, city, state, postal code & country values respectively.

Also using _formContext global variable, you would need to set CRM field values with the suggestion parameter values, which user clicks while suggestions are populated. Provide logical names of CRM fields over “crm-streetfield”.

The main step is to provide your Bing Maps API Key in the section highlighted above.

Step 8: The final step is to insert your web resource into the section where you want to place your form by making an entry into make.powerapps navbar. Find the Insert option and then click on WebResource.

You need to provide necessary name for your web resource. You would also be required to copy the provided name and paste it into onload JavaScript function explained above for passing the execution context. Click OK and finally Save and Publish.

Conclusion

 In this blog we went through Bing Maps API Integration steps into our Dynamics 365 CRM application and easily integrated Auto Suggestion with just few lines of code.