How to Get Latitude and Longitude from an Address Using Bing Maps API in JavaScript for D365

 

Getting Latitude & Longitude from an Address Using Bing Maps API


In Microsoft Dynamics 365, capturing latitude and longitude based on a given address is crucial for various business scenarios, such as the following:

  • Customer Location Tracking: Storing precise geolocation details for customers.

  • Field Service Optimization: Assigning technicians based on customer locations.

  • Sales Territory Management: Mapping sales territories.

To achieve this, we use the Bing Maps API to convert an input address into geographic coordinates (latitude and longitude) and auto-populate them in Dynamics 365 fields.


Prerequisites

1. Bing Maps API Key

To use Bing Maps for geocoding, you need a Microsoft API key. You can obtain one by registering at the Bing Maps Developer Portal.

2. Bing Maps API Endpoints

We will use the following REST API endpoint to fetch location coordinates:

https://dev.virtualearth.net/REST/v1/Locations?query={Address}&key={YourBingMapsAPIKey}
        {Address}: The full address to be geocoded.
        {YourBingMapsAPIKey}: Your unique Bing Maps API key.

JavaScript Code to Get Latitude & Longitude in D365

Below is a JavaScript function to fetch latitude and longitude from an address and store them in CRM fields (dbt_latitude and dbt_longitude) before saving the form.

var isGeoCodeFetched = false; // Prevent infinite loop

function populateGeoCodeOnSave(executionContext) {

    var formContext = executionContext.getFormContext();

    var eventArgs = executionContext.getEventArgs();


    var latitudeAttr = formContext.getAttribute("dbt_latitude");

    var longitudeAttr = formContext.getAttribute("dbt_longitude");


    if ((latitudeAttr?.getValue() && longitudeAttr?.getValue()) || isGeoCodeFetched) return; // Allow save if values exist


    // Prevent form save until geocoding completes

    if (eventArgs) eventArgs.preventDefault();


    var fullAddress = [

        formContext.getAttribute("dbt_street")?.getValue(),

        formContext.getAttribute("dbt_city")?.getValue(),

        formContext.getAttribute("dbt_postalcode")?.getValue(),

        formContext.getAttribute("dbt_country")?.getValue()

    ].filter(Boolean).join(", "); // Removes empty values and avoids ',, , ,,'


    if (!fullAddress) { // If fullAddress is empty after filtering, show an error

        Xrm.Navigation.openErrorDialog({ message: "Address fields are empty." });

        return;

    }

    var geocodeUrl = `https://dev.virtualearth.net/REST/v1/Locations?query=${encodeURIComponent(fullAddress)}&key=YourBingMapsAPIKey`;


    fetch(geocodeUrl)

        .then(response => response.json())

        .then(data => {

            console.log("Bing Maps API Response:", data);


            if (data.resourceSets && data.resourceSets.length > 0 && data.resourceSets[0].resources.length > 0) {

                var coordinates = data.resourceSets[0].resources[0].point.coordinates;

                var latitude = coordinates[0].toString();

                var longitude = coordinates[1].toString();


                latitudeAttr.setValue(latitude);

                longitudeAttr.setValue(longitude);


                isGeoCodeFetched = true; // Set flag to prevent infinite loop

                formContext.data.entity.save();    // Manually save the form after setting values

            } else {

                throw new Error("Address not found.");

            }

        })

        .catch(error => {

            console.error("Fetch Error:", error);

            Xrm.Navigation.openErrorDialog({ message: "An error occurred while fetching coordinates. Details: " + error.message });

        });

}

Creating a Web Resource to Run the Script in D365

  1. Navigate to Power Apps > Solutions and open your desired solution.

  2. Click New > Web Resource.

  3. Set Name (e.g., GeoCodeAddress.js) and Type as JavaScript (JScript).

  4. Upload the JavaScript file containing the above code.

  5. Save and publish the web resource.

  6. Open your Entity Form, navigate to Form Properties, and add the web resource.

  7. Set the function populateGeoCodeOnSave to run on Save Event.

  8. Click OK and publish changes.

Testing and Validating the Implementation

  1. Ensure the Bing Maps API key is active.

  2. Enter a valid address in the CRM form.

  3. Trigger the script by saving the record.

  4. Check if latitude & longitude fields are populated correctly.

  5. Test with different addresses to verify accuracy.

  6. Use the browser console (F12) to check API responses and debug errors.

latitude and longitude image

Conclusion

Using the Bing Maps API, we can automate the process of fetching geolocation coordinates based on a given address in Dynamics 365. This enhances data accuracy and enables better business decision-making.

Key Takeaways:

  • Use Bing Maps API for address geocoding.

  • Ensure a valid API key and permissions.

  • Implemented error handling for smooth functionality.

  • Test across different browsers and devices.


FAQs

1. How do I get a Bing Maps API key?

You can generate an API key from the Bing Maps Developer Portal.

2. What if Bing Maps API does not return coordinates?

  • Check if the entered address is correct.

  • Ensure that the API key is valid.

  • Use console.log() to inspect API responses for errors.

3. Can I use Google Maps API instead of Bing Maps API?

Yes, you can use Google Maps Geocoding API, but it requires separate API credentials and has different request limits.



No comments:

Post a Comment