Inkey Solution Logo
banner

Blogs

Use Google maps to measure distance in Microsoft Dynamics 365 for Sales Part 3 of 3

, March 27, 2020 2318 Views

Story so far…

In the previous blogs, I gave a brief overview of what we need and how to get the API key from Google Maps. In the final part of the blog, I will tell you how to measure the distance. In this part we will be dealing with the CRM side of things. I mentioned the use of a web resource. If you have already used this then make sure you get Latitude and Longitude of the locations. We will need these to measure distance. If you haven’t, no worries. Just check out this wonderful tutorial by Quratulain Ibrahim

So Dynamics…

Remember the link that I shared in the first part of the blog about Microsoft giving what is required? No? Then here is the link, check it out. Download the sample code and add GoogleDataContracts.cs file in your project. Make sure you add the urls and API key as suggested in the link. Don’t, under any circumstances, share your API key. You will get a fairly good idea what this code does. 

So go ahead and create a plug-in.

And now, the plug-in code.

Within the plug-in include this code, but before that make sure you get the latitude and longitude values for both source and destination entity records.

WebClient client = new WebClient();
var url = String.Format($"https://maps.googleapis.com/maps/api/distancematrix/json"
                      + "?units=imperial"
                      + $"&origins=" + originAddress1Latitude + "," + originAddress1Longitude
                      + $"&destinations=" + destinationAddress1Latitude + "," + destinationAddress1Longitude
                      + $"&key={GoogleConstants.GoogleApiKey}");

string response = client.DownloadString(url);
System.Runtime.Serialization.Json.DataContractJsonSerializer jsonSerializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(DistanceMatrixResponse));
object objResponse = jsonSerializer.ReadObject(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(response)));
DistanceMatrixResponse distancematrixResponse = objResponse as DistanceMatrixResponse; 

if (distancematrixResponse.Status != "OK")
              throw new ApplicationException($"Server{GoogleConstants.GoogleApiServer} application error (Status={distancematrixResponse.Status}).{distancematrixResponse.ErrorMessage}");

double distanceValueInKiloMeter = 0;
if (distancematrixResponse.Rows != null && distancematrixResponse.Rows.Count > 0 &&
distancematrixResponse.Rows[0].Columns.Count > 0 && distancematrixResponse.Rows[0].Columns[0].Distance != null)
{
              double distanceValueInMeter = distancematrixResponse.Rows[0].Columns[0].Distance.Value;
              distanceValueInKiloMeter = distanceValueInMeter / 1000;
}

So, now let’s go through the code.

In the first part of the code we are merely calling the Distance Matrix API with appropriate parameters

WebClient client = new WebClient();
var url = String.Format($"https://maps.googleapis.com/maps/api/distancematrix/json"
                      + "?units=imperial"
                      + $"&origins=" + originAddress1Latitude + "," + originAddress1Longitude
                      + $"&destinations=" + destinationAddress1Latitude + "," + destinationAddress1Longitude
                      + $"&key={GoogleConstants.GoogleApiKey}");

string response = client.DownloadString(url);
System.Runtime.Serialization.Json.DataContractJsonSerializer jsonSerializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(DistanceMatrixResponse));
object objResponse = jsonSerializer.ReadObject(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(response)));

The variables originAddress1Latitude and originAddress1Longitude contain latitude and longitude values of the source entity record. Similarly the variables destinationAddress1Latitude and destinationAddress1Longitude contain latitude and longitude values of the destination entity record. You can have multiple source and destination entities and the API will return distance between each of them, but for the sake of simplicity, I have used only one.

Now the next part of code stores the actual distance in meters. But, we want the distance in kilometers so we multiply the value by 1000.

DistanceMatrixResponse distancematrixResponse = objResponse as DistanceMatrixResponse; 

if (distancematrixResponse.Status != "OK")
              throw new ApplicationException($"Server{GoogleConstants.GoogleApiServer} application error (Status={distancematrixResponse.Status}).{distancematrixResponse.ErrorMessage}");

double distanceValueInKiloMeter = 0;
if (distancematrixResponse.Rows != null && distancematrixResponse.Rows.Count > 0 &&
distancematrixResponse.Rows[0].Columns.Count > 0 && distancematrixResponse.Rows[0].Columns[0].Distance != null)
{
              double distanceValueInMeter = distancematrixResponse.Rows[0].Columns[0].Distance.Value;
              distanceValueInKiloMeter = distanceValueInMeter / 1000;
}

The distancematrixResponse object is where response will be stored and will contain the distance. It will contain multiple values including the time it would take to cover the distance but we don’t need that now, do we?

The variable distanceValueInKiloMeter stores the actual value which you can use just about anywhere.

The end..or is it?

So, in the blog posts starting from part 1, part 2 and this one, I walked you through the task of measuring distance between two entities. Feel free to provide some feedback. It will help me improve my skills.


ATM Inspection PowerApp to ease ATM inspection and report generation process.
https://powerapps.microsoft.com/en-us/partner-showcase/inkey-solutions-atm-inspection/

Insert data into Many-to-Many relationship in Dynamics CRM very easily & quickly, using the Drag and drop listbox.
http://www.inkeysolutions.com/what-we-do/dynamicscrmaddons/drag-and-drop-listbox

Comply your Lead, Contact, and User entities of D365 CRM with GDPR compliance using the GDPR add-on.
https://www.inkeysolutions.com/microsoft-dynamics-365/dynamicscrmaddons/gdpr

Create a personal / system view in Dynamics CRM with all the fields on the form/s which you select for a particular entity using the View Creator.
http://www.inkeysolutions.com/what-we-do/dynamicscrmaddons/view-creator

mm

Inkey

INKEY is your solution partner.
Our focus is to deliver you in-time intelligent innovative solutions ("key") for the problems in hand. Maintaining a quality standard right from the inception of a project is our top most priority.

Our team of talented professionals will execute your projects with dedication and excellence. We take ownership and accountability for the effort that goes into meeting our client’s needs.

Years of experience and proven success of delivering innovative custom solutions.

More posts by

2 responses to “Use Google maps to measure distance in Microsoft Dynamics 365 for Sales Part 3 of 3”

  1. Thank you for referring to my blog post.

Leave a Reply

Your email address will not be published. Required fields are marked *

The maximum upload file size: 2 MB. You can upload: image, audio, video, document, spreadsheet, interactive, text, archive, code, other. Drop file here

Would you like to digitize your business and put it on the cloud?
Do you need clear, concise reports for your organization?