Maps in modal windows are experiencing issues with Google Maps integration

I've been troubleshooting how to integrate Google Maps into a modal, but I keep encountering the error TypeError: Cannot read property 'offsetWidth' of null. I've gone through all the suggested solutions on various forums, and it seems that the issue could be because the modal doesn't exist when the page initially loads. I attempted using ng-init to load it when the modal appears, but I still face the same error. Interestingly, I discovered that the map controller runs when the main page loads instead of when the modal is displayed.

Controller

.controller('mapCtrl', function($scope) {
  $scope.init = function() {
    var myLatlng = new google.maps.LatLng(51.508742,-0.120850);
  var mapProp = {
    center: myLatlng,
    zoom:5,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  };
  var map=new google.maps.Map(document.getElementById("map"),mapProp);

    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map
    });
    $scope.map = map;
}
})

Modal

<ion-modal-view ng-controller="mapCtrl">
    <ion-header-bar id="modalheader">
        <h1 class="title"></h1>
<!-- button to close the modal -->
        <button class="button icon ion-android-close" ng-click="closeModal();"></button>
    </ion-header-bar>
<ion-content class="item-icon-right item-text-wrap" id="modal">
<ion-list id="modalitem">
<ion-item>
<!-- displays the larger view of the office address -->
    <h1>{{office.LocationName}}</h1>
        <p id="mdets">{{office.LocAddressLine1 + ", " + office.LocAddressLine2 + ", " + office.LocCity + ", " + office.LocCountryDescription + ", " + office.LocZipPostalCode}}</p>
        <i ng-class="{'icon ion-android-star': favicon(office.id), 'icon ion-android-star-outline': !favicon(office.id)}"  ng-click="togglefav(office.id); $event.stopPropagation();"></i>
    </ion-item>
</ion-list>
<!-- creates the map view from the json data -->
<div ng-init="init()">
    <div id="map" style="width:500px;height:380px;"></div>
</div>

</ion-content>

</ion-modal-view>

Answer №1

This issue arises under the circumstance that

document.getElementById("map")

does not have an offsetWidth, therefore it remains hidden. It is necessary to initialize the map only when you are ready to display it, not in advance. The function

init()

gets triggered only upon clicking to open the modal.

Answer №2

To improve the map initialization, consider using the $timeout function.

$timeout(function() {
  $scope.initializeMap();
})

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

Navigating through content using jQuery scroll bar

Could someone please assist me with scrolling the content on my website? For example, I have a link like this: <a href="#">content3</a> When a user clicks that link, I would like the content to scroll to div content3. I am looking for guidan ...

What is the best way to attach an event listener to every child node within a div that is stored in an array of divs?

Currently, I am dedicated to learning JS on my own and have decided to hold off on using jQuery until my JavaScript skills have improved. The objective is to attach an event listener for the click event to all divs of a specific class and have all child n ...

Requests in Node.js may unexpectedly stall and remain unresolved until the server is restarted

I've encountered a strange and seemingly sporadic issue with our web application that I can't seem to resolve through debugging. The app runs smoothly for varying durations, ranging from 10 minutes to 6 hours, but then all of a sudden, any remote ...

Refresh of posts is not occurring upon removal from the database

I am currently in the process of creating a blog using a MEAN stack, and I have encountered a minor issue. Below is the HTML code I am utilizing to fetch all my posts: index.html: <div ng-repeat="post in posts"> <h2> {{post.title}} ...

Select elements using jQuery in events while excluding others

I need to prevent form submission when the user presses Enter, except for three specific inputs. To prevent form submission on Enter key press, I can use this code: $(document).keydown(function(event){ if(event.keyCode == 13) { event.preventDefault(); re ...

Display DataTable in a JavaScript alert message

... { foreach (ListEntry.Custom listrow in mySpread.Elements) { DC = myTable.Columns[listrow.LocalName] ?? myTable. Columns.Add(listrow.LocalName); myDR[DC] = listrow.Value; ...

Establishing the Time-to-Live (TTL) with Redis-OM and Node Object Mapping

Recently, I stumbled upon the exciting new Redis-OM Node Object Mapping feature. Although I have limited experience with Redis, I am eager to dive into it now. Currently, I have a basic function in place for creating rooms but I want these rooms to automa ...

Can you provide guidance on the most effective approach to appending to a file using async await?

Is it safe to repeatedly call functions like fs.appendFile()? For instance, when using child_process.spawn and a "for-async-of" loop to implement tee with JavaScript. Chunked file data needs to be appended to a file while performing other processing. If ap ...

Failure to authorize Google Maps API

Having trouble connecting to the Google MAP API with a persistent error: Authorization failure. Please see https://developers.google.com/maps/documentation/android/start for instructions on properly setting up the map. Make sure that the following match ...

What guidelines should be followed when using nested ternary operators in code formatting?

Consider a scenario with nested ternary statements: return foo ? 1 : bar ? 2 : 3; How can we effectively format this code for better readability by future viewers? ...

Troubleshooting: Directives in Angular 4 not recognizing RegEx patterns

I have developed a directive that validates the input in a text field, allowing users to enter numbers, dots, and commas. However, the validator only seems to work for numbers and not for commas and dots. import { Directive, ElementRef, HostListener } fro ...

Locate and retrieve a document by its unique identifier in MongoDB, and then store its information in an array

I am working with two models: Meal and Ingredient. Let's take a look at their schemas: const mealSchema = new Schema({ title: { type: String, required: true }, image: { type: String, required: false }, ingredients: [{ ingredient: { ...

Using JavaScript to Detect Asynchronous Postbacks in ASP.NET AJAX

Seeking advice on the JavaScript code required to determine if an asynchronous postback is in progress. Can anyone help with this? Appreciate any assistance. ...

Transferring account information to a function call in the near-js-api

I am attempting to utilize the following method in near-js-api for my contract. It requires a Rust AccountId as input. What is the correct procedure to serialize an Account and send it to the contract? Also, are there any specific considerations when inv ...

Tips for reducing the amount of repetitive code in your reducers when working with redux and a plain old JavaScript object (

When it comes to writing reducers for Redux, I often encounter challenges. My struggle usually lies in wrapping a lot of my state manipulation in functions like .map and .slice. As the structure of my state object becomes more complex, the reducers become ...

Ways to display an error page while keeping the current URL unaffected

I've created a custom error page named 500.tsx for displaying errors with a status of 500, but I want to show this page while keeping the client on the same URL (e.g. /auth/register). I have an error listener using axios that should handle this, but I ...

Guide to accessing contact list on Ionic framework

I'm new to using Ionic and I'm trying to access the contact list in my app to display contacts only. Can someone please guide me on how to achieve this? I watched a tutorial on YouTube but the code provided doesn't seem to work. I've ad ...

How can we use the nth-of-type selector to target a set of eight elements in a

I am trying to style a group of divs in such a way that every set of eight elements will have the same left positioning. Rather than just styling every eighth element individually, I want to apply the styling to groups of eight elements at once. However, ...

Avoid duplicate form submissions with jQuery

Issue: I am facing an issue with a script that allows users to press the keys C or M to choose an option. However, some users are pressing these keys multiple times even though each option can only be submitted once. Query: How can I prevent users from ...

Combining promises to handle the asynchronous promise received from this.storage.get() function

Struggling with managing asynchronous data retrieval from local storage in my Angular2/ionic2 app. The code snippet I'm using: request(args) { var headers = new Headers(); headers.append('Content-Type', 'application/json&a ...