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

Verify the text file for any data, and if it contains any, display it on the web browser using JavaScript

I have a program in C that works with a temperature sensor. It creates a file to store the temperature and indicates whether it falls within specific values. I want to display this data on a web browser and update it every 5 minutes. I'm looking for ...

Is it possible to connect ng-model with a style tag?

Is it feasible to create a basic template editor using angularjs where an input field with an ng-model can be connected to a style tag to control the css on an entire page rather than applying it to a specific element with inline styling? Could something ...

Error encountered while attempting to install material-ui v3.0.3 due to an unexpected termination of the JSON input

I'm currently in the process of installing the most recent stable version of material-ui(v3.03) by running: npm install @material-ui/core. However, I encountered an issue with npm ERR! Unexpected end of JSON input while parsing near '...-/brcast- ...

How to effectively test $transition service hooks in UI-Router 1.X using karma?

I have been working on migrating to ui-router 1.0.5 and have made good progress, but I am having trouble finding examples of how to test the new transition hooks that replaced the $stateChangeXXX event listeners. Previous Code: scope.$on('$stateChan ...

Finding All Initial Table Cells in jQuery

Is there a streamlined method for retrieving all td elements (cells) from every row within a specific table, or do I have to manually iterate through the collection myself? ...

The heroku error message states: "ENOENT - unable to locate the file 'index.html' within the build folder."

I'm currently facing an issue while trying to deploy my application on Heroku. I keep receiving the error message Error: ENOENT, stat '/app/build/index.html' when I access my address. Oddly enough, the deployment process does not throw any e ...

Is there a way to automatically input an array of elements into a form without having to do it manually

Is it possible to create a form using an array of items fetched from a database, and automatically populate the form with each of these elements? Currently, I'm facing difficulties as the form appears empty. What am I missing? Below is the code I ha ...

Showing HTML element when the model count is zero - ASP.NET MVC View

My view has a dynamic element that switches between two options depending on the Model.Count property. Check out the code below: @if (Model.Count() == 0) { <div class="well well-lg"><h3>Everyone is present! No absences today :)</h3>& ...

Creating a web form with HTML and integrating it with jQuery AJAX

Looking to fetch data from the server through jQuery AJAX on an HTML form and store the response in a PHP string variable. Here is my current code snippet: <form method="post" name="myform" id="myform" action="https://domain.com/cgi-bin/cgi.exe"> &l ...

The duplication of printed keys and values from a JavaScript object is causing issues

I am working with a JSON object structured like this: var data = { "2020-01-20": ["08:00 - 09:00", "09:00 - 10:00"], "2020-01-21": ["08:00 - 09:00"] }; My objective is to display each value along with its corresponding key in a list format, as follow ...

Serve Webpack bundle on various routes - Express Way

I recently completed a web application using an Express backend and React frontend. Upon sending a request to the Express server, it undergoes a process where the URL is checked against the backend routes. If there isn't a match, the React bundle gen ...

As you scroll, the opacity gradually increases, creating a dynamic visual

Struggling to replicate a feature on a website where images gain opacity as you scroll down? Check out this site for reference: . While my current code somewhat achieves this effect, I'm having trouble figuring out how to apply a darker opacity gradua ...

Why is the time input field in AngularJS programmed to expect a date instead?

When booking, I stored the time using $filter('date')($scope.booktime, 'mediumTime'). After booking, I have an editbooking function where I pass the time and encounter an error in the console: Error: [ngModel:datefmt] Expected 11:59:00 ...

Zoom in and Zoom out functions in ngPdf with centered view

I have incorporated the pdf canvas to showcase PDFs on my AngularJS/Bootstrap application, and I must say, the preview feature is working exceptionally well. However, one thing that I would like to achieve is centering either my modal or the canvas itself ...

Issue with retrieving data from controller in Spring MVC 3 using jQuery and AJAX via $.get method. The value is not being returned to the

I am currently diving into the world of AJAX, particularly in conjunction with Spring MVC. However, I am encountering some challenges along the way. Before delving into my actual real-time project requirements, I decided to test out the AJAX+Spring MVC+jQ ...

How to target a class in jQuery that contains two specific strings

There are multiple images in my HTML, each assigned two classes. Here's a snippet of the relevant code: class = "thing other0-a" class = "thing other1-a" class = "thing other2-a" class = "thing other3-a" class = ...

What steps can I take to successfully run Node.js within Eclipse when the JavaScript runtime is not showing up in the preferences?

I have been encountering some difficulties with integrating Node.js into my Eclipse IDE for enterprise Java developers. I am using Eclipse Ide 2021-06 and have installed Node.js 16.3 along with npm. According to the Eclipse news, Eclipse Neon and later ve ...

Incorporating HTML elements into a Jade template

Can HTML elements be passed into a jade file? For example, I want to insert text into the p element and nest some content inside the code element within the p element. JSON with string data var news = { one : { title : "Using JSON", body : "Us ...

establishing a minimum number of characters in a regular expression enclosed in parentheses

/^[a-z]+[0-9]*$/igm Tom //valid tom12123 //valid 12tom //invalid to12m //invalid T23 //valid T //valid but I want a minimum of two characters. /^([a-z]+[0-9]*){2,}$/igm Tom //valid tom12123 //valid 12tom //invalid to12m //should be inval ...

Tips on handling parameters in the form of a single value or an array of values

I've implemented multiple functions structured like this: this.something = function (which) { // Can be one or many. if (!Array.isArray(which)) { // Single input case. doSomething(which); } else { ...