Trouble initializing Google Maps in an Angular directive

I'm currently working on integrating the Google Maps API into an Angular website, but I'm encountering initialization issues.

Within my HTML page, I'm utilizing bootstrap nav nav-tabs and switching between tabs using an Angular controller.

<ul class="nav navbar-nav">
    <li ng-class="{ active:myCtrl.isSet('map') }">
        <a href ng-click="myCtrl.setTab('map')">Show Map</a>
    </li>
</ul>

One of the tabs includes only the Google map canvas element, implemented through an Angular directive:

Module.directive('mapPage', function() {
    return {
        restrict: 'E',
        template: '<div id="map-canvas"></div>'
    };
});

In my Angular controller, I've set up a listener for the window 'load' event to initialize the map:

google.maps.event.addDomListener(window, 'load', myCtrl.initMap);


myCtrl.initMap = function() {

    var mapOptions = {
        zoom: 12,
        center: new google.maps.LatLng(55.937879, -3.241619),
    };

    myCtrl.map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(55.937879, -3.241619),
        map: myCtrl.map
    });

    myCtrl.map.setCenter(new google.maps.LatLng(55.937879, -3.241619));
}

Upon viewing the screen, the map element displays a grey area with the location marker not correctly centered (slightly off-screen).

Moving the map-canvas div to the main section of the index.html page results in correct loading, indicating that my Google API JavaScript code and HTML are accurate. The map also displays when resizing the page.

However, the issue arises when using it on a non-immediate rendering page. Despite searching for similar questions/answers, this particular problem remains unresolved.

I've created a simple fiddle showcasing the issue.

http://jsfiddle.net/johntough/nc0u7h2c/5/

Any assistance would be highly appreciated!

Answer â„–1

The problem lies in the timing of loading the Map. The container becomes visible only when clicked, but you are trying to load the map on window load. Google Maps has a behavior (not officially documented, but I have observed it multiple times) where if the container is hidden initially, the map will not load inside it. By changing the event trigger from "load" to "click", the issue was resolved. Here is the modified code:

google.maps.event.addDomListener(window, 'click', myCtrl.initMap);

You can check the updated functionality in this fiddle: http://jsfiddle.net/anandgh/nc0u7h2c/6/

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

ExpressJS sends null response to Angular's $http POST request

I am relatively new to backend development and working with Node.js. I am currently facing an issue when setting up an $http POST request to send a form to Express. Every time I make the request, the callback data returns as null. It makes me wonder if my ...

Finding the Right Value from a REST Call in AngularJS - A Step-by-Step Guide

In my AngularJS project, I have implemented a select box in two different ways. One method includes static options directly in the HTML along with ng-model, while the other method utilizes ng-options. Both methods successfully populate the select box, but ...

Show Text When Clicking Within Separate DIVs

I have a set of three divs. One contains a Twitter icon, another holds a LinkedIn icon, and the last one is designated for displaying text upon clicking. My goal is to click on the Twitter icon and have corresponding text appear in the third div. Then, if ...

Does the modularization of code impact the performance of the react-app?

The client provided me with a React app that includes an index.jsx file where 90% of the coding has been completed. To prevent getting stuck in Scroll Limbo, I have started breaking down the code into modules for each specific requirement. These include ...

The nested route controller in ui-router is not functioning correctly

PLNKR: http://plnkr.co/edit/Or4JTiUrPOJUoW78c8Xd Hello everyone, currently facing an issue that I have managed to simplify into the following example: var myapp = angular.module('myapp', ["ui.router"]) myapp.config(function($stateProvider, $url ...

JavaScript Function to Retrieve URL Parameter in PHPIn this tutorial

I'm currently working on an HTML5 game where each level has its own dedicated HTML page. The results of each level are saved in a JavaScript variable. My question is, how can I pass this information to the next page using the URL? I was considering ...

I'm having trouble getting PHP/AJAX to return the expected XML data - it keeps

I have a JavaScript script that looks like this: function showItems(type) { var xmlhttp = new XMLHttpRequest(); //creating object var call = "getitems"; xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState ...

Vue 3 feature: Click the button to dynamically insert a new row into the grid

Just starting out in the world of coding, I've zero experience with Vue - it's my introduction to frameworks and arrays are currently my nemesis. In a recent exercise, I managed to display the first five elements of an array in a table after filt ...

I'm currently attempting to incorporate the Material-UI InfoIcon into my code, but I'm unsure of how to properly integrate it within a TextField component

I am attempting to integrate the Material-UI InfoIcon into my TextField code, but I'm unsure of how to go about it. Here is the snippet of Material-UI code: <InfoIcon fontSize="small" /> This is where I would like to place it: <Grid item ...

The $q.all() function in angular seems to struggle with resolving properly

Having trouble with 3 $http calls in a factory. Creating 4 promises: var promise = $q.defer(), PBdeferred = $q.defer(), Rdeferred = $q.defer(), Pdeferred = $q.defer(); Making the first call to the API: $http.get('/pendingBills').then(fu ...

Building a table from JSON using only JavaScript.orGenerate a

I am working with a dynamic Json containing multiple keys that may vary. Here is an example: Var children = [{num = 6, name = me, phone = 7}, {num = 8, name = him, phone = 9}] My goal is to create a table with the headers (num, name, phone) Is there a w ...

What advantages can be gained from having multiple package.json files within a single application?

Embarking on the journey of creating my inaugural full react web application entirely from scratch. Previously, I've mainly worked on assignments that were partially pre-made for me. While setting up my project, I couldn't help but notice that I ...

What is the process for activating namespacing on a VueX module that has been imported?

I am currently utilizing a helper file to import VueX modules: const requireModule = require.context('.', false, /\.store\.js$/) const modules = {} requireModule.keys().forEach(filename => { const moduleName = filename ...

Tips for using the deferred method in ajax to enhance the efficiency of data loading from a php script

I recently discovered this method of fetching data simultaneously using ajax. However, I'm struggling to grasp the concept. Can someone please explain how to retrieve this data from a PHP script and then add it to a div similar to the example provided ...

`Troubleshooting Firebase Cloud Functions and Cloud Firestore integration`

I previously used the following Firebase Database code in a project: const getDeviceUser = admin.database().ref(`/users/${notification.to}/`).once('value'); Now, I am attempting to convert it for Firestore. My goal is to retrieve my users' ...

What is the process of utilizing marked plugins within a Vue3 project?

I attempted to integrate the marked plugin into my Vue.js applications. After installing [email protected], I did not encounter any issues during compilation. However, when I viewed the contents in the browser, nothing appeared. My Vue project was built u ...

Challenges with Hangman in JavaScript

As a beginner in JavaScript, I recently developed a simple hangman-like game. However, I encountered some challenges that I need help with. One issue is related to my lettersGuessed array. Currently, the array displays every time a key is pressed and repea ...

Error: The function `map` cannot be applied to `cardsData`

I'm encountering an issue where I need to store user queries in cardsData and then map through the data within cardsData. However, when I run the code on my terminal, it throws an error. As a beginner, I've researched various forums that mention ...

Incorporate a button within a listview on Kendoui to trigger the opening of a modal window

I am seeking assistance on how to insert a button on each element of a Listview (PHP/Json) result. When clicked, this button should open a modal window where the customer can input reservation details such as Date, Adults, and Children. Below is the JavaSc ...

Extracting <p> elements from a separate HTML file and cycling through them

I successfully created a website using only HTML, JavaScript, and jQuery without any server-side scripting or language. Within my website, I have a simple stream.html page that remains unstyled with no CSS formatting. <html> <head> </head& ...