"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

Express.js post request not functioning properly

I am currently in the process of developing a discussion-based Node.js/Express app and I am focusing on creating a discussion page. I have been attempting to test if my discussion controller file is properly linked, but for some reason every time I click t ...

Use `$$state: {…}` within the request rather than the data

When attempting to send a request with data, I am only getting "f {$$state: {…}}" in the console. $scope.createTask = function () { var req = $http.post('api/insert', { title: $scope.newTitle, description: ...

Is there a way to display my array within my React component using JavaScript?

I am working with an element that looks like this: const DropdownElements = [ { key: 1, title: "City", placeholder: "Select City", apiUrl: "https://api.npoint.io/995de746afde6410e3bd", type: "city&qu ...

When the CSS animation has finished in JavaScript

I am currently developing a game using HTML/JavaScript, and I have implemented a "special ability" that can only be activated once every x seconds. To indicate when this ability is available for use, I have created a graphical user interface element. Since ...

Angular.js line 68 threw an error stating that the argument 'fn' is not a function and instead got an Object

Currently in the process of converting our angular application to use ES6 Style syntax. After making changes to all files, encountering the following error: Error Message: angular.js:68 Uncaught Error: [ng:areq] Argument 'fn' is not a function, ...

Surprising use of template string value

After following a tutorial, I decided to create ProductScreen.js and Product.js. However, when implementing my code, I encountered some warnings. Can anyone help me identify the issue? product.js import React from 'react' import Rating from &apo ...

AngularJS: Issue with JQuery Slider not Updating Scope Value

I am currently working on a project using AngularJS and I have integrated a jQuery slider into it. However, I am facing an issue where I need to change the value of a select box which is defined in a $scope array, but the functionality is not working as ex ...

Trouble loading nested view template

I am currently working on developing a tabbed interface that maintains state using AngularJS, UI Router, and UI Router Extras. I have been referencing this example as a guide. Everything functions correctly if I do not include a nested view with an abstra ...

Unable to modify the model of the directive

I'm facing an issue where additional elements added to my array within a controller of a directive are not being displayed in the view. What's even more frustrating is that when I print my model, it doesn't reflect the new elements that have ...

I currently have an array of strings and wish to print only the lines that include a specific substring

Here i want to showcase lines that contain the following strings: Object.< anonymous > These are multiple lines: Discover those lines that have the substring Object . < anonymous > Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'you ...

How to iterate over an array and assign values to distinct labels using AngularJS

Challenge My goal is to present the user with information about their upcoming 4 events. I have used splice on an array to extract the first 4 objects. Now, I need to iterate through these objects and display the relevant data. Each label is unique and w ...

Is there a way to customize the pagination dots in react-native-swiper-flatlist?

Is it possible to customize the pagination dots style for react-native-swiper-flatlist? <View style={styles.container}> <SwiperFlatList autoplay={false} autoplayLoop={false} index={0} showPagination ...

Code snippet for calculating the size of an HTML page using JavaScript/jQuery

Does anyone know of a way to calculate and display the size/weight (in KB) of an HTML page, similar to what is done here: Page size: 403.86KB This would include all resources such as text, images, and scripts. I came across a Pelican plugin that does th ...

The functions getFiles and getFolders will consistently retrieve a single file or folder each time they are

When attempting to fetch all files and folders from my Google Drive, the function .getFiles() is only returning one file, while .getFolders() is only returning a single folder. However, I can confirm that there are multiple folders and files in my drive. ...

Is it possible to extract only the time from a date and time using angular-moment library?

I am trying to display only the time from a date. My code looks like this: $scope.sample_time = "September 14th 2017, 1:00:00 pm"; What I want in my view is to show just the time, for example 1:00 pm. I attempted to use angular-moment, with something li ...

The request method 'PUT' is not currently supported

Currently, I am working on a project that involves springboot, angularjs, and restful services. Here is my REST controller: @RequestMapping(value="/updatestructure/{ch}", method = RequestMethod.PUT) public @ResponseBody Structurenotification updateStruct ...

Troubleshooting problem with Ajax responseText

Can an ajax responseText be received without replacing the existing content? For instance: <div id="content"> <p>Original content</p> </div> Typically, after running an ajax request with a responseText that targets id="conten ...

Navigating between pages using the ExpressJS and Angular 1 routing system

Can someone help me troubleshoot an issue I'm having with my Express API and Angular front-end? Whenever I try to access the /about route, it keeps defaulting back to index.html and displaying a 404 error message. Can you take a look at my code and pi ...

Tips for Showing Websocket Response On Web Browser Using Node.js

Just starting out with NodeJS and here's my code snippet: const webSocket= require('ws'); const express = require('express'); const app=express(); Var url = "wss://stream.binance.com:9443/BTCUSDT@trade`" const ws = new webS ...

Node accurately handles and displays errors, such as validation errors, in a precise manner

I am currently restructuring our code base to incorporate promises. Below are two blocks of sample code: user.service.js export function updateUserProfileByUsername(req, res) { userController.getUserByUsername(req.params.username) .then((userProfile ...