Display loading animation until Google Maps is fully loaded - Utilizing AngularJs

Is there a way to check the readiness of Google Maps before displaying it? I'd like to show a preloader block while the Google Maps is loading.

Here is the factory code I am using:

var map = false;
var myLatlng = new google.maps.LatLng(48.6908333333, 9.14055555556);

var myOptions = {
    zoom: 5,
    minZoom: 2,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    draggableCursor:'crosshair',
    zoomControl: false,
    center: myLatlng,
    panControl: false,
    streetViewControl: false,
    preserveViewport: true
}

function addMap(mapId) {
    var map = new google.maps.Map(document.getElementById("map"), myOptions);
}

function getMap(mapId) {
    if (!map) addMap(mapId);
        return map;
}

return {
    addMap: addMap,
    getMap: getMap
}

And here is the code inside the controller:

$scope.map = GoogleMaps.getMap();

Appreciate your help!

Answer №1

To ensure that the Google Maps event is triggered once the map is ready, you can add an event listener as shown below:

function addMap(mapId) {
    var map = new google.maps.Map(document.getElementById("map"), myOptions);
    google.maps.event.addListenerOnce(map, "idle", function () {
        scope.$emit('mapInitialized', map);
    });
}

In your splash screen directive, you can then listen for the event like this:

$scope.$on('mapInitialized', function(event, map) {
    // this is where you can manipulate variables to hide the splash screen
});

Here is a sample code snippet that includes a black splash screen:

angular
  .module('splashMap', [])
  .directive('map', function() {
      var link = function(scope, element) {

        var el = document.createElement("div");
        el.style.width = "100%";
        el.style.height = "100%";
        element.prepend(el);

        var map = new google.maps.Map(el, {
          center: {
            lat: 48.6908333333,
            lng: 9.14055555556
          },
          zoom: 8

        });

        google.maps.event.addListenerOnce(map, "idle", function() {
          scope.$emit('mapInitialized', map);
        });

      }
      return {
        restrict: 'E',
        link: link
      };

    }

  ).directive('splash', function() {
    var link = function(scope, element) {
      scope.loaded = false;
      scope.$on('mapInitialized', function(e, map) {
        console.log('loaded');
        scope.loaded = true;
        scope.$apply();
      })
    }
    return {
      restrict: 'E',
      link: link,
    }
  });
body,
html,
map {
  font-family: "Open Sans", sans-serif;
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
}
map,
splash {
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
}
splash {
  background-color: #000;
  z-index: 2;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<body ng-app="splashMap">

  <splash ng-hide="loaded"></splash>

  <map></map>

</body>

Answer №2

As of now, I haven't had the opportunity to explore Google Maps.

However, is it possible to achieve this by utilizing the following event:

tilesloaded

Alternatively, you could explore other events mentioned in the following document:

https://developers.google.com/maps/documentation/javascript/reference

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on verifying internet connection status using Ajax request

Ensuring authentication by checking the availability of network connection on mobile devices. To do this, we must have both a username and password. The authentication process will be conducted online, requiring an active internet connection on the device. ...

Guide to establishing a connection to the Companies House API: Essential guidelines on setting up cURL headers and requisite API key specifications

I am attempting to establish a connection with the UK Companies House API, preferably using JavaScript. However, I am currently trying to set up this PHP version. How can I obtain access to the API using an API key? PHP: public function GetCompanyHouse( ...

Using the Karma testing framework to interact with the service of an AngularJS application

Currently, I am in the process of creating an end-to-end test using Karma for an AngularJS application. My goal is to automate the process of filling out a form and submitting it. Once submitted, an object is generated that should be accessible by calling ...

How to utilize the Ember generate command for an addon

In my Ember addon project, the package.json file looks like this: { "name": "my-addon-ui", "version": "1.0.0", "devDependencies": { "test-addon": "http://example.com/test-addon-1.1.1.tgz", } } Additionally, the package.json file of the depe ...

Upon page load, a dazzling SVG file will flicker before being adorned with CSS styles

I'm experiencing an issue with an SVG arrow icon on my webpage that flashes quickly across the entire screen upon page load before settling into its proper size and placement. I've tried using CSS to initially hide the icon and then reveal it aft ...

background image alteration when scrolling

I've been attempting to change the background image on scroll, but I haven't had any luck finding a guide. So, I'm hoping someone here can help me out. I found a video that showcases exactly what I'm trying to accomplish - https://www.y ...

In order to ensure proper alignment, adjust the width of the select element to match the width of the

Is there a way for the select element to adjust its width based on the length of the selected option? I want the default option value's width to be shorter, but once another option is selected, I'd like the select element to resize itself so that ...

We encountered a surprise issue: "/Users/username/package.json: Unexpected character \ in JSON at index 1" – this is not a duplicate question

While running the yarn command in various projects, I encountered the same error consistently. Error message: "An unexpected error occurred: "/Users/name/package.json: Unexpected token \ in JSON at position 1". Trace: SyntaxError: /Users/name/pack ...

Having trouble with your custom AngularJS directive not functioning correctly?

I am facing an issue with my custom directive implementation. I have a custom directive that contains a table which references a controller. The ProjectController part works fine when it is not included in the code, but as soon as I put everything into the ...

What is the process for saving information to a database with JavaScript?

I am currently utilizing the Google Maps API for address translation, primarily through the use of a geocoder. I am interested in saving these results to a local database for future reference, as there are limitations on the total number and frequency of ...

Activate on-demand static regeneration with Next.js

I am thoroughly impressed by the functionality of Incremental Static Regeneration in Next.js. However, I am currently seeking a method to manually trigger static page regeneration as needed. It would be ideal to have a command that can be executed via an ...

Sidenav Content with all elements having opacity applied

How can I ensure that all page elements have a black background color when the mobile navigation is opened on the left screen, while ensuring that my sidebar and content image do not get overlaid by the black background? Here is my code: function openNav( ...

Tips for updating the filename in a file input using AngularJS

Is it possible to dynamically change the name of a chosen file? For instance, if I select a file with the name "img1", can it be automatically changed to a different dynamic name upon selection? <input type="file" fd-input/> https://i.sstatic.net/d ...

What is the process for updating a placeholder text after the user makes a guess or enters

My latest project involves creating a fun guessing game where players have to identify the driver based on the teams they have driven for. The game displays the number of guesses allowed and keeps track of how many attempts the player has made so far. For ...

Eliminate every instance using the global regular expression and the replace method from the String prototype

function filterWords(match, before, after) { return before && after ? ' ' : '' } var regex = /(^|\s)(?:y|x)(\s|$)/g var sentence1 = ('x 1 y 2 x 3 y').replace(regex, filterWords) console.log(sentence1) sentence2 ...

Issue with long text in a resizable table using jQuery tablesorter 2.31.1

My issue is that when I try to resize the columns in tablesorter, they snap back into place. The column width set with resizable_widths does not apply correctly until a column is manually resized. Despite setting the width of all cells to 120px, any cells ...

Once the GeoJson data is loaded with map.data.loadGeoJson, the circle events are obscured by the polygons from the

When I use map.data.loadGeoJson() to load a Geo Json file, the markers and circles on my map are being covered by polygons and their events cannot be clicked. Below are some sample codes for reference. How can this issue be resolved? Is there another way ...

Creating Docker images in a lerna monorepo without the need for publishing

In the context of Lerna monorepos, the primary goal is to facilitate branch building and deployments. The challenge arises from the fact that Lerna monorepos either consolidate dependencies in NPM or utilize yarn workspaces to achieve the same outcome, re ...

Combining Two Tables Using jQuery

I am currently attempting to combine two tables into one using jQuery in the following manner: var table = document.createElement("table"); table.id = "mergedTable"; $("#mergedTable > tbody:last") .append($("#csvInfoTable2 > tbody").html()) ...

Revising variables in Java Script

How can I shuffle a list of variables in JS and maintain the order while changing their values? The following code snippet demonstrates what I am trying to achieve. <p id="demo"></p> <script> var gen = "male "; var race = "white"; var ...