Load Bing map in AngularJS application

Balasaheb Molawade 136 Reputation points
2023-07-27T05:50:28.1033333+00:00

Hi,

We have an angularJS application in which we used the below code to load the Bing map in our controller.js. Bing map load takes around 1-2 secs. Is there any faster way to load Bing map in angularJS.

function loadMap() {
            var functionName = "loadMap ";
        
            try {
             
                console.log(" loadMap " + new Date());
                var mapScriptUrl = 'https://www.bing.com/api/maps/mapcontrol?branch=release&callback=getMap';
                var script = document.createElement("script");
                script.setAttribute('defer', '');
                script.setAttribute('async', '');
                script.setAttribute("type", "text/javascript");
                script.setAttribute("src", mapScriptUrl);
                document.body.appendChild(script);
            } catch (e) {
                alert(e.message);
            }
        }
        var getMap = function () {
            var getMap;
            var mapCenter = {};
            var zoom = "";
            var location = "";
            var functionName = "getMap ";
            try {
                console.log(" getMap " + new Date());

                map = new Microsoft.Maps.Map(document.querySelector("#myMap"), {
                    credentials: "Our Bing Map Key",
                    minZoom: 2,
                    enableCORS: true
                });

            } catch (e) {
                aler(e.message);
            }
        };

Thanks!

Azure Maps
Azure Maps
An Azure service that provides geospatial APIs to add maps, spatial analytics, and mobility solutions to apps.
831 questions
{count} votes

3 answers

Sort by: Most helpful
  1. RevelinoB 3,675 Reputation points
    2023-07-27T06:08:20.4+00:00

    Hi Balasaheb,

    To potentially speed up the loading of the Bing map in your AngularJS application, there are some tricks for that:

    • Asynchronous Loading: The current implementation is already using the async attribute, which loads the Bing Maps script asynchronously. This is good as it allows other parts of your web page to load without being blocked by the map script.
    • Defer Script Loading: The current implementation is using the defer attribute, which is also a good practice. It allows the HTML parsing to continue while the map script loads in the background. This is particularly useful when the map script is not essential for the initial page rendering. Minimize Dependencies: Make sure you only load essential Bing Maps modules that your application requires. This can help reduce the overall script size and loading time. Caching the Map Script: Consider using the max-age parameter in the URL of the map script to specify caching settings. This allows the browser to cache the script locally, reducing subsequent load times. Lazy Loading: If the map is not needed immediately on page load, you can defer loading the map until it's actually required. This way, you won't incur the initial loading time if the user doesn't interact with the map right away. Optimize the Map Configuration: Review your map configuration and ensure that you're not doing any unnecessary operations or setting any properties that might slow down the map initialization. CDN Consideration: Make sure that the Bing Maps script is hosted on a reliable and fast Content Delivery Network (CDN) to ensure faster loading times.

    However, it's important to note that the primary factor influencing the loading time of the Bing map is the network speed and the distance from the user to the Bing Maps servers. You can optimize the above aspects within your control, but you might not be able to drastically reduce the loading time if the user's network connection is slow or has high latency.

    And AngularJS is a bit old school now. Maybe consider moving to Angular or React for a smoother and more modern experience, especially when working with external libraries like Bing Maps.

    I hope this helps?


  2. RevelinoB 3,675 Reputation points
    2023-08-03T11:21:32.43+00:00

    Hi @Balasaheb Molawade

    If loading the Bing map script and optimizing the initialization didn't provide a significant improvement, there are a few more things you can try to further optimize the loading time of the Bing map in your AngularJS application:

    Asynchronous Loading with Preconnect: Use the rel="preconnect" attribute in the link tag to indicate that your page intends to establish a connection to the Bing map domain. This allows the browser to start the DNS resolution and TCP handshake process earlier, which can potentially reduce the connection setup time when the script is fetched.

    Add the preconnect link before the script tag:

    htmlCopy code
    <link rel="preconnect" href="https://www.bing.com" crossorigin>
    <script defer async type="text/javascript" src="https://www.bing.com/api/maps/mapcontrol?branch=release&callback=getMap"></script>
    

    Use a Local Copy of the Bing Map Script: Instead of loading the Bing map script directly from the Bing servers, you can download a copy of the script and host it on your server. This way, you can benefit from the browser cache for subsequent visits, reducing the loading time for returning users.

    Download the Bing map script from https://www.bing.com/api/maps/mapcontrol?branch=release&callback=getMap, save it as bing-maps.js, and host it on your server. Then, update the script tag in your HTML to use the local copy:

    htmlCopy code
    <script defer async type="text/javascript" src="path/to/bing-maps.js"></script>
    

    Optimize Your Bing Maps Key: Make sure you are using the most appropriate type of Bing Maps key for your application. There are several types of keys with different usage scenarios. Using the correct type of key can improve performance.

    Code Splitting: Consider code splitting your AngularJS application using tools like Webpack or AngularJS's built-in mechanisms. By breaking your application into smaller chunks, the initial loading time can be reduced, as only the necessary code is loaded when the user first visits the page.

    Web Workers: You can explore the possibility of using web workers to offload non-essential tasks, like map initialization, to a separate thread. This way, the main thread can focus on rendering critical content while the web worker handles the map initialization asynchronously.

    Server-Side Rendering (SSR): If it's feasible for your application, consider implementing server-side rendering. SSR can improve the perceived loading time as the initial rendering of the page happens on the server, and a pre-rendered version is sent to the client, reducing the time taken to display meaningful content.

    Remember that the actual performance improvements might vary depending on your specific application and the user's network conditions. It's a good idea to measure the loading time and performance metrics before and after applying each optimization to see the actual impact. Additionally, monitor the application's performance regularly and make adjustments as needed.

    I hope this helps?

    0 comments No comments

  3. rbrundritt 20,836 Reputation points Microsoft Employee Moderator
    2023-08-08T20:00:33.3766667+00:00

    Looks like you are trying to do something like this: https://samples.bingmapsportal.com/?search=&sample=dispose-map but in Angular.

    The loading time of the map in depends on several factors:

    1. When is the map SDK code loaded? In your case it is through a loadMap function which I suspect you load in response to a button press, rather than loading the source code once when your app initially loads. This means you have to wait for the physical time it takes to download the SDK source code.
    2. Once the SDK code is loaded, it then triggers your function to create a map object. The map not only has to create the DOM elements, but also needs to load the base map data which can be 1MB or more depending on the size of the map. Large maps will need more map tiles and take longer to load. One option to improve performance is to set the maps liteMode option to true. This will disable the vector labels and fallback to having the labels in the map tiles. This helps a lot with performance, but the map labels will then appear behind any data you add to the map. Note that this option can't be changed after the map is loaded.
    3. In addition to the base map, the time it takes to load your data depends on the size and time to download your data. That said, if you use a lot of different custom icons for displaying points, performance will be impacted as well as each icon image needs to be loaded (more http requests). Using the default circle pushpin and simply changing its color will be much faster than using custom image icons. Rendering a couple hundred points will be fast, while tens of thousands will be a bit slower. A lot of complex lines and polygons can also impact performance. That said, the time it takes to load the map tiles will depend on if they have been loaded previously and are in the web cache. If you have no tiles in the cache it will take time to download them, while cached tiles load really fast.

    If you have other resources loading on your page such as images or other HTTP requests, these will be competing for bandwidth in the browser as browsers limit how many concurrent requests can be made. This is the most common bottleneck I've seen related to initial map loading.

    All of that said, the map loading within 2 seconds is actually good and what the target is. Most of my career that was the loading time nearly every major company I worked with was aiming for, until the last few years where many actually set lower expectations due to the grow of JS Frameworks that actually load slower.

    If the 2 seconds is really an issue for your user experience, there are some tricks you can use to make it more seamless.

    • One of the most common solutions used for this is to load a static map image in place of the map initially, kind of like a splash page in the area the map will be loaded. https://learn.microsoft.com/en-us/bingmaps/rest-services/imagery/get-a-static-map This won't have the zoom buttons and things like that, or any custom pushpins, but it will let the user know there is a map and it is even in the right area.
    • Modify your user experience a bit. Maybe start by loading a smaller size map, then let the user increase its size. A smaller map area will load faster than a larger one.
    • Load the Bing Maps SDK code sooner and preload the map and hide it. Note that transactions are based on how many time the map control is loaded. Load it once when your page loads in the background or as soon as you think the user may be heading that way, and never load the map again, simply hide and show it as needed while they are on the page. This has a tradeoff of not releasing the resources the map is using when they aren't using the map, but that also means the map will display near instantly and there is only one map session charge. I believe you can include your Bing Maps key in the script URL to get the session to apply to all map loads on a single page session. So that's another way to reduce that individual cost.
    • There is Azure Maps, which may be possible to load slightly faster with the right settings, but I wouldn't migrate an app from one platform to another over this concern.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.