14500+ website owners are using this wordpress map plugin

Buy Now - $89

How to Synchronously Load Map APIs?

Introduction:

The Maps API is loaded synchronously in this case. The async and defer characteristics from the script tag that loads the API were removed, as was the callback argument.

<html>

<head>

<title>Synchronous Loading</title>

<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <div id="map"></div>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&v=weekly"></script>
  </body>
</html>

When the API is loaded synchronously, following script tags will not be executed until the API has been completely loaded. As a result, the final script tag may utilise new google.maps.Map and presume that google.maps.Map has already been defined.

Code:

const map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
  center: { lat: -34.397, lng: 150.644 },
  zoom: 8,
});

declare global {
  interface Window {
    map: google.maps.Map;
  }
}
window.map = map;
export {};

Explanation:

  • The line, “map = new google.maps.Map(document.getElementById(“map”)”; creates a new map inside the <div> element with the help of the mentioned id which is ‘map’ as an HTMLElement.
  • const map = new google.maps.Map(document.getElementById("map") as HTMLElement, 
    
  • The ‘centre’ attribute defines where the map should be centered with the help of the latitude and longitude coordinates.
  •  center: { lat: -34.397, lng: 150.644 },
    
  • The ‘zoom’ attribute specifies the map’s zoom level.
  • zoom: 8,
    
  • Lastly, the function is called and executed.
  • window.map = map;
    

Conclusion:

Thus, in this tutorial we learned how to load the maps synchronously.

Live Example

Install Plugin Now!

This plugin is exclusively available at codecanyon.net. You'll get free updates and full support to use this plugin.