"Using the Google Maps directive inside a separate modal directive in Angular results in a blank map display

As a newcomer to Angular, I have encountered a hurdle while attempting to incorporate a 'google maps' directive inside another directive.

The following code showcases a 'modal-view' directive that loads a form:

    angular.module('test').directive('modal', function () {
    return {
      template: '<div class="modal fade">' +
          '<div class="modal-dialog">' +
            '<div class="modal-content">' +
              '<div class="modal-header">' +
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' +
                '<h4 class="modal-title">{{ title }}</h4>' +
              '</div>' +
              '<div class="modal-body" ng-transclude></div>' +
            '</div>' +
          '</div>' +
        '</div>',
      restrict: 'E',
      transclude: 'element',
      replace:true,
      scope:false,
      link: function postLink(scope, element, attrs) {
        ...
      }
    };
});

Next is the google maps directive:

    angular.module('test').directive('googleMaps', function () {
  return {
    restrict:'E',
    template:"<div></div>",
    replace:true,
    transclude: true,
    scope:false,
    link:function(scope, element, attrs){
      window.onload = function() {
        scope.map = new google.maps.Map(document.getElementById(attrs.id), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 8
        });

        scope.map.addListener('click', function() {
          alert("Click!");
        });
      };
    }
  };
});

When I load the map directive independently, it displays correctly. However, the issue arises when I attempt to load the map within another directive, like so:

//modal directive        
<modal title="{{title}}" visible="showModal">

          <div class="row">
            <div class="col-sm-12">
              <form class="dropzone" dropzone="dropzoneConfig"></form>
            </div>
          </div>
          <form role="form" name="userForm"  ng-submit="addPerson(person)" novalidate>
            <div class="form-group">
              <label for="name">Name</label>
              <input type="text" name="name" class="form-control" id="name" placeholder="Enter your name" ng-model="person.name" required />
            </div>

    //Maps directive
            <google-maps id="map" class="form-group"></google-maps>

          </form>

        </modal>

Upon implementation, the frame loads with the Google logo but fails to display the map, leaving a grey background instead.

Any assistance on this matter would be greatly appreciated! Thank you.

Answer №1

If the display is not working properly, it could be due to an angular digest issue. One solution is to initialize the map inside a $timeout function instead of waiting for document.onload. Make sure to inject $timeout before using it.

Example:

angular.module('test').directive('googleMaps', ['$timeout', function ($timeout) {
    return {
        restrict:'E',
        template:"<div></div>",
        replace:true,
        transclude: true,
        scope:false,
        link:function(scope, element, attrs){
            $timeout(function() {
                scope.map = new google.maps.Map(document.getElementById(attrs.id), {
                    center: {lat: -34.397, lng: 150.644},
                    zoom: 8
                });

                scope.map.addListener('click', function() {
                    alert("Click!");
                });
            });
        }
    };
}]);

Answer №2

I am grateful for shaishab roy's recommendation to use '$timeout', which helped me realize that my mistake was trying to load the map in a hidden div. The solution turned out to be initializing the map when the modal view is displayed. Thank you for your valuable assistance :)

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

Personalized Grid Design for Showcasing Athletic Teams

I am looking to create a custom grid layout that represents the team's Players, separated by their positions (GK, Defense, Midfielders, and Forwards), similar to the image below. The layout should also be responsive like in image 1. Currently, the re ...

Is it possible to decrease the size of a div by scrolling both vertically and horizontally?

Can a div's height and width both be reduced at the same time while scrolling down a page? Let's say that as the user scrolls, the size of the div changes from 400px by 400px to 200px by 200px, all while remaining centered on the page. I've ...

Create a list of items with checkboxes next to each that can be repeated using PdfMake

Incorporating pdfMake into my project, I am trying to display text next to an image and replicate this section in my docDefinition. The issue arises when I attempt to repeat this part using the following code snippet: { columns: [ { ...

Minimizing repeated autofocus calls in material-ui's <TextField> component

In the realm of coding with material-ui, when dealing with the <TextField> component, it's important to keep in mind that the solution may actually lie within React itself. Let's paint a scenario where we're crafting a basic login for ...

Next.js - utilizing dynamic API routes within nested folders

Currently, I am working on developing a basic API that reads a local JSON file. My goal is to create a dynamic API that can adjust based on the specific calls it receives. Within my API folder structure, I have: api --book ---[id].js ----content -----[id ...

A guide on adding two fields together in AngularJS and displaying the output in a label

I am facing a unique issue on my webpage. Including two inputs and a label in the page, I want the label to display the sum of the values entered into these two inputs. My initial attempt was as follows: Sub-Total <input type="text" ng-model="Propert ...

Trigger a warning pop-up if a selection has not been made in a dropdown menu using jQuery

I am attempting to display an alert popup when the user fails to select a value from the dropdown menu. Below is my HTML code: <div id="reminder" class="popup-layout"> ... ... </form> </div> In my JavaScript function page, I have tried ...

Adding event listeners to modal buttons in a Handlebars template is a simple process that involves utilizing the `

I've been working on developing a web application that interacts with a news API to display articles. Each article is presented in a card format, and I have also incorporated modals using handlebars. My goal is for each card's button to trigger ...

Harness the power of JavaScript to generate a dynamic overlay with a see-through image that can be expanded

Within different sections of my website, we display banner ads that are loaded in real-time from third-party sources and come in various sizes. I'm interested in adding a transparent overlay image to each ad which would allow me to trigger a click ev ...

Change the icon switch from fas fa-lock-open to fas fa-lock by adding an event listener for a click action

let lockIcon = document.createElement("i"); lockIcon.setAttribute("class", "fas fa-lock-open"); lockIcon.setAttribute("id", color + "lock"); Is there a way to toggle between the icons fas fa-lock-open and fas fa-lock when clicking using a ...

AngularJS: Issue with Variable Value Rendering

I recently started working with Angular. In my JavaScript file, I have the following code: App.controller('ProductController', ['$scope', 'ProductService', function ($scope, ProductService) { console.clear(); console. ...

I am facing difficulty in incorporating an IP address or URL within an IFRAME in my Cordova Android application

This page does not allow any iframes to load except for the YouTube video URL. When attempting to use any other iframe URL, the following error code is displayed: Error : net::ERR_BLOCKED_BY_RESPONSE In the example below, any URL or IP address fails to l ...

Is it possible for the *ngIf directive to stop unauthorized users from accessing my admin page through their browsers?

When the *ngIf directive is set to false, a certain element or component will not be included in the DOM. For example, let's say there is a component that displays admin tools and should only be accessible to authorized users (administrators). Will se ...

Sped up object outpacing the mouse pointer

I'm currently developing a drag and drop minigame, but I've encountered an issue with the touch functionality. The draggable function (using only cursor) works flawlessly, however, when I tried to implement touch support for mobile and tablet use ...

Refresh the page using a promise in Angular after a delay of 3 seconds

Currently, I am working on enhancing the functionality of the login page. In case a user enters an incorrect login and password combination, my goal is to have the page automatically reload after 3 seconds. Despite my best efforts, I have encountered chall ...

Sending numerous messages from a single event using Socket.io

After an exhaustive search, I have yet to find a solution to my problem. I am attempting to send a message from the server every time it detects a file change in a specific directory. However, instead of sending just one message, it sends the same message ...

Integration of Unlayer EmailEditor into React causes fatal errors in the application

I am attempting to integrate Unlayer into my React Application by using this guide: https://github.com/unlayer/react-email-editor. I have configured Webpack for this purpose. However, when I try to import EmailEditor in one of my modules: import React fr ...

Making HTTP requests with axios in Node.js based on multiple conditions

I'm facing an issue with making get calls using axios to both activeURl and inactiveURl. The goal is to handle error messages from the activeUrl call by checking data from the inactiveUrl. However, I keep receiving error messages for the inactiveURL e ...

Simultaneously updating the states in both the child and parent components when clicked

In my code, I have two components: the parent component where a prop is passed in for changing state and the child component where the function is called. The function changes the state of the parent component based on an index. changeState={() => this ...

What is preventing access to the global scope in this particular situation?

Recently, I encountered a problem where I was able to pass through the issue but couldn't fully grasp the concept behind it. If you run the code snippet provided, you'll see what's happening. Can someone clarify this for me? function fu ...