Alphavima Technologies

February 13th, 2025

Bing Maps API Integration with Dynamics 365 CRM: 3 Steps to Enable Distance Calculation

Learn how to implement distance calculation

In our previous blog, we helped you with the integration of Bing Maps API with Dynamics 365 CRM application and creation of Auto Suggestion functionality on the address field. With this blog, we will guide you on how to calculate the distance between a source and the destination address.

Distance Calculation from Source to Destination Address Field into Dynamics 365 CRM

Step 1: Create a web resource name it as Source Web Resource and place all the above code into it. Our Source Web resource will remain the same and will not change.

Step 2: Create another web resource and name it as Destination Web Resource and place the below code:

<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>
</head>
<body style=”overflow-wrap: break-word;” onfocusout=”parent.setEmailRange();”>
<div id=”searchBoxContainer”>
<label style=”display: inline-block; max-width: 100%;margin-bottom: 5px;font-weight: bold;color: #666;” for=”Search”>
To Address</label>
<br>
<input id=”searchBox” style=”display: block;width: 450px;height: 35px;font-size: 15px;line-height: 1.42857;&#10;        color: rgb(85, 85, 85);background-color: rgb(255, 255, 255);background-image: none;&#10;        border: 1px solid rgb(204, 204, 204);border-radius: 0px;box-shadow: rgba(0, 0, 0, 0.075) 0px 1px 1px inset;&#10;        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;” type=”text” placeholder=”Search your address here…” autocomplete=”off”>
</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) { _formContext.getAttribute(“crm-deststreet”).setValue(suggestionResult.address.addressLine); _formContext.getAttribute(“crm-destcity”).setValue(suggestionResult.address.locality); _formContext.getAttribute(“crm-destpostalcode”).setValue(suggestionResult.address.postalCode); _formContext.getAttribute(“crm-deststateorprovince”).setValue(suggestionResult.address.adminDistrict); _formContext.getAttribute(“crm-destcountry”).setValue(suggestionResult.address.countryRegion); var concatDestinationAddress = suggestionResult.address.addressLine + ‘,’ + suggestionResult.address.locality + ‘,’ + suggestionResult.address.adminDistrict + ‘,’ + suggestionResult.address.countryRegion; var sourceAddressLine = _formContext.getAttribute(“crm-srcstreet”).getValue(); var sourceAddressCity = _formContext.getAttribute(“crm-srccity”).getValue(); var sourceAddressState = _formContext.getAttribute(“crm-srcstate”).getValue(); var sourceAddressCountry = _formContext.getAttribute(“crm-srccountry “).getValue(); var concatSourceAddress = sourceAddressLine + ‘,’ + sourceAddressCity + ‘,’ + sourceAddressState + ‘,’ + sourceAddressCountry; map = new Microsoft.Maps.Map(‘#myMap’, {}); //Load the directions module. Microsoft.Maps.loadModule(‘Microsoft.Maps.Directions’, function () { //Create an instance of the directions manager. directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map); //Create waypoints to route between. var sourceWayPoint = new Microsoft.Maps.Directions.Waypoint({ address: concatSourceAddress }); directionsManager.addWaypoint(sourceWayPoint); var destinationWayPoint = new Microsoft.Maps.Directions.Waypoint({ address: concatDestinationAddress }); directionsManager.addWaypoint(destinationWayPoint); //Add event handlers to directions manager. Microsoft.Maps.Events.addHandler(directionsManager, ‘directionsError’, directionsError); Microsoft.Maps.Events.addHandler(directionsManager, ‘directionsUpdated’, directionsUpdated); //Calculate directions. directionsManager.calculateDirections(); }); } function directionsUpdated(e) { //Get the current route index. var routeIdx = directionsManager.getRequestOptions().routeIndex; //Get the distance of the route, rounded to 2 decimal places. var distance = Math.round(e.routeSummary[routeIdx].distance * 100) / 100; //Get the distance units used to calculate the route. var units = directionsManager.getRequestOptions().distanceUnit; var distanceUnits = “; if (units == Microsoft.Maps.Directions.DistanceUnit.km) { distanceUnits = ‘km’ } else { //Must be in miles distanceUnits = ‘miles’ } } function directionsError(e) { alert(‘Error: ‘ + e.message + ‘\r\nResponse Code: ‘ + e.responseCode) } } </script>
<script src=”https://www.bing.com/api/maps/mapcontrol?key={Your Bing Maps API Key} &amp;callback=loadMapScenario” defer=”” type=”text/javascript” async=””>
</script>
<div id=”myMap” style=”position:relative;width:500px;height:500px;display:none;”>
</div>
<div id=”directionsItinerary”>
</div>
</body>
</html>

Step 3: Almost all the above code is the same as explained earlier with some of the additions. Major additional code comes under selectedSuggestions function where we are getting source address field values into our destination address web resource and concatenating all the field values to form full address.

var concatSourceAddress = sourceAddressLine+’,’+sourceAddressCity+’,’+sourceAddressState+’,’+sourceAddressCountry;

Step 4: The most important step is where we are using Microsoft.Maps.Directions.DirectionsManager API and creating the object of it. Also, we are creating an object of Microsoft.Maps.Directions.Waypoint to provide sourceWaypoint and destinationWaypoint and pass our source address and destination address.

We are getting source address from CRM fields through the execution context while the destination address is from the (current) web resource autosuggestion address field.

Step 5: In the below section of the code, we are finally getting distance from the source to the destination address.

function directionsUpdated(e)

{

//Get the current route index.

var routeIdx = directionsManager.getRequestOptions().routeIndex;

//Get the distance of the route, rounded to 2 decimal places.

var distance = Math.round(e.routeSummary[routeIdx].distance * 100)/100;

//Get the distance units used to calculate the route.

var units = directionsManager.getRequestOptions().distanceUnit;

var distanceUnits = ”;

if (units == Microsoft.Maps.Directions.DistanceUnit.km)

{

distanceUnits = ‘km’

}

else

{

//Must be in miles

distanceUnits = ‘miles’

}

}

Here, we are creating a new function name directionsUpdated to get the shortest route index and distance using DirectionsManager.getRequestOptions AP. We can just display this distance using an alert field or store this value into the CRM Distance field by using _formContext global variable.

Provide Bing Maps API key in the highlighted section while keeping the rest of the code the same. It’s already been explained earlier in the blog.

Step 6: Similarly create JavaScript function to pass executioncontext object into our source as well as destination web resource created and place this Jscript function onload of that form.

Similarly, place both the web resources created into any entity form where you want distance functionality as shown above and finally Save and Publish.

Conclusion

In this blog, we went through the integration of Distance Calculation with just a few lines of code. Layering your CRM with Bing Maps will enable you to map your sales, accounts, leads, opportunities based on customer demographics lending you an unparalleled competitive edge in the market.

Want to integrate location intelligence in your CRM? Contact our experts for a tailored demo.

Ready to enhance Dynamics 365 with location intelligence?

Integrate Bing Maps with Dynamics 365 to track, optimize, and manage distances more effectively – powered by Alphavima’s implementation expertise.

FAQs

What Is the Purpose of Bing Maps API Dynamics 365 Integration?

The Bing Maps API Dynamics 365 integration adds geographic intelligence to your CRM platform. First, it enables address auto-fill on contact and account records. Additionally, it renders an interactive map view directly within CRM record forms. As a result, users visually confirm customer locations without leaving the CRM interface.

Furthermore, the integration enables distance calculation between two CRM address records. This is particularly valuable for field service teams planning daily routes. However, the most impactful use case is territory management. Sales leaders can visualise account distribution and identify coverage gaps on a map view. Therefore, geographic data becomes a strategic tool rather than just a display feature. Moreover, the integration works across Dynamics 365 Sales, Customer Service, and Field Service modules. As a result, multiple business teams benefit from the same mapping capability within a single platform.

Can I Calculate the Distance Between Two CRM Account Addresses?

Yes, Dynamics 365 supports distance calculation between CRM address records through the Bing Maps API. First, the platform sends geocoded address data to the API. Additionally, the API returns the straight-line or driving distance between the two points. As a result, field service teams identify the nearest technician to each customer job location easily.

Furthermore, distance data can trigger workflows and automation rules. For example, a route optimisation workflow can assign jobs to the closest available resource automatically. However, distance calculation requires that both address records are accurately geocoded. Therefore, data quality management is essential for this feature to work reliably. Moreover, calculation frequency affects API transaction consumption. As a result, organisations should monitor usage to ensure they stay within their Bing Maps licence allocation throughout the billing year.

What Are the Main Steps to Enable Distance Calculation in CRM?

Enabling distance calculation in Dynamics 365 follows three main steps. First, obtain an active Bing Maps Enterprise API key from the Bing Maps Dev Center. This key authenticates your CRM environment with the mapping service. Additionally, navigate to System Settings in Dynamics 365 and enter your API key in the Bing Maps configuration field. As a result, the mapping integration becomes active across all CRM record forms immediately.

Furthermore, the third step involves testing the integration on a sample contact or account record. Confirm that the map renders correctly and address auto-fill responds as expected. However, advanced distance scenarios such as multi-record route calculation may require additional workflow configuration. Therefore, work with your CRM implementation partner for these more complex use cases. Our detailed Bing Maps integration setup guide covers the full configuration walkthrough for Dynamics 365 environments step by step.

Is Custom Development Required to Set Up the Integration?

No, basic Bing Maps API integration with Dynamics 365 does not require custom development. First, the integration is a native built-in feature of Dynamics 365. Additionally, enabling it requires only an API key entry in the System Settings panel. As a result, system administrators can activate the mapping feature without involving any developers.

Furthermore, address auto-fill and interactive map display work out of the box once the API key is configured. However, more advanced use cases such as distance-based workflow triggers require additional configuration. Therefore, these scenarios typically involve Power Automate flows or lightweight JavaScript customisations. Moreover, custom map overlays and territory visualisations require Power Apps component development. As a result, the level of development required depends entirely on the complexity of your specific mapping requirements and the business use cases you want to support across your CRM environment.

Which CRM Record Types Support the Distance Calculation Feature?

Several CRM record types support Bing Maps distance calculation in Dynamics 365. First, Contact and Account records are the primary supported entity types. Address fields on these records are automatically geocoded when the integration is active. Additionally, Lead records also support map display and address auto-fill. As a result, the feature covers the full customer lifecycle from initial lead through to long-term account management.

Furthermore, Case records in Dynamics 365 Customer Service display location data for dispatching support teams. Work Order records in Dynamics 365 Field Service also support full mapping and routing capabilities. However, custom entities require additional configuration to enable mapping features. Therefore, consult your implementation partner before expecting map support on non-standard record types. Moreover, the scope of supported entities may vary depending on your Dynamics 365 licence tier and module configuration.

What Data Does the Mapping Service Return to the CRM Platform?

The Bing Maps API returns several data types to Dynamics 365 when called. First, it returns geocoding data including latitude and longitude coordinates for each address. Additionally, it validates and standardises address formatting automatically. As a result, address data quality in CRM improves through the integration without manual effort.

Furthermore, the API returns interactive map tile images that render on CRM record forms. These allow users to pan, zoom, and explore the area surrounding each customer location. However, the API also returns distance and travel time data for route calculations when specifically queried. Therefore, the integration supports both visual display and functional routing use cases simultaneously. Our CRM solutions team helps organisations configure Dynamics 365 mapping features to maximise the value of their Bing Maps API licence and transaction allocation effectively.

How Do I Obtain and Configure the Required API Key?

Obtaining a Bing Maps API key is a straightforward process. First, visit the Bing Maps Dev Center at bingmapsportal.com and sign in with a Microsoft account. Additionally, create a new application and select the Enterprise key type. As a result, the system generates your unique API key immediately after submission.

Furthermore, copy the key and navigate to Dynamics 365 System Settings. Select Administration and open the System Settings dialog panel. However, you must hold a System Administrator security role to access this configuration option. Therefore, confirm your permissions before starting the configuration process. Moreover, paste the API key into the designated Bing Maps field and save your settings. As a result, the integration activates across your entire Dynamics 365 environment immediately. Test by opening any account or contact record to verify the map tile renders correctly without any additional steps required.

Is the Integration Secure for Production Use?

Yes, the Bing Maps API integration is secure for production Dynamics 365 environments. First, all API calls use HTTPS with TLS encryption. Additionally, the API key is stored within Dynamics 365 system settings rather than in client-side code. As a result, the key benefits from Dynamics 365 role-based access control protection.

Furthermore, Microsoft Bing Maps Enterprise complies with standard data handling and privacy regulations. Address data sent to the API for geocoding is processed according to Microsoft privacy policies. However, organisations in regulated industries should review the specific data residency requirements of the service. Therefore, confirm the service meets your compliance requirements before deploying in sensitive environments. Our CRM services team provides security assessments for Dynamics 365 integrations including mapping configurations for enterprise and regulated-industry clients.

Does the Bing Maps API Dynamics 365 Integration Work on Mobile Devices?

Yes, the Bing Maps API Dynamics 365 integration works on mobile devices through the Dynamics 365 mobile app. First, the mobile app renders map views on Contact and Account records just like the desktop interface. Additionally, field sales and service teams access geographic CRM data while working away from the office. As a result, the integration delivers value for mobile workers and office-based users equally.

Furthermore, mobile users benefit from address auto-fill when creating or updating records from their devices. This improves data quality for organisations capturing customer data in the field. However, map rendering on mobile depends on available network connectivity. Therefore, offline scenarios may not display full map tiles when data coverage is limited or unavailable. Moreover, the Dynamics 365 mobile app for both iOS and Android supports the Bing Maps integration natively. As a result, field teams on any device access the same mapping features as their office colleagues.

    Get in Touch