Error accessing property 'offsetwidth' of null in Google Maps JavaScript API

I am currently utilizing the Google Maps JS API to showcase a map on my website. However, I am encountering an issue where the website is displaying an empty card and upon inspecting the elements, I came across the error message: Cannot read property 'offsetwidth' of null.

Any assistance in resolving this matter would be greatly appreciated! Provided below is all the relevant code snippets.

CSS

.content {
    position: fixed;
    top: 15%;
    width: 100%;
    height: 85%;
    overflow: auto;
}

.card {
    width: 85%;
    height: auto;
    margin-left: auto;
    margin-right: auto;
    box-shadow: 0 2px 6px #888888, 0 2px 6px #888888;
}

.card-map {
    width: 100%;
    height: 300px;
}

HTML

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="../style.css">
</head>

<body>
    <div class="content">
         <div class="card">
              <div class="card-map"></div>
              <script type="text/javascript" src="../google-maps.js"></script>
         </div>
    </div>
</body>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDb8GJ8wzza1nQyrYBUf4iKBzF1TcC6BXA&callback=initMap"></script>
</body>

JS

function initMap() {
    var customMapType = new google.maps.StyledMapType([{
        "featureType": "administrative",
        "stylers": [
            { "visibility": "off" }
    ]},{
        "featureType": "poi.attraction",
        "stylers": [
            { "visibility": "off" }
    ]},{
        "featureType": "poi.business",
        "stylers": [
            { "visibility": "off" }
    ]},{
        "featureType": "poi.government",
        "stylers": [
            { "visibility": "off" }
    ]},{
        "featureType": "poi.medical",
        "stylers": [
            { "visibility": "off" }
    ]},{
        "featureType": "poi.park",
        "stylers": [
            { "visibility": "off" }
    ]},{
        "featureType": "poi.place_of_worship",
        "stylers": [
            { "visibility": "off" }
    ]},{
        "featureType": "poi.school",
        "stylers": [
            { "visibility": "off" }
    ]},{
        "featureType": "poi.sports_complex",
        "stylers": [
            { "visibility": "off" }
     ]},{
        name: 'Custom Style'
     }]);
    var customMapTypeId = 'custom_style';

    var map = new google.maps.Map(document.getElementById("card-map"), {
        zoom: 12,
        center: {lat: 40.674, lng: -73.946},
        disableDefaultUI: true,
            mapTypeControlOptions: {
                mapTypeIds: [google.maps.MapTypeId.ROADMAP, customMapTypeId]
            }
        });

    var marker = new google.maps.Marker({
        position: {lat: 40.674, lng: -73.946},
        map: map,
    });

    map.mapTypes.set(customMapTypeId, customMapType);
    map.setMapTypeId(customMapTypeId);
    window.addEventListener("load",initMap, false);

}

Answer №1

It seems like the issue lies in attempting to set up the map before the page has fully loaded (prior to the card-map element being generated).

Here's a suggestion to address it:

Get rid of this particular line

google.maps.event.addDomListener(window, "load", initialize);

from the initialize function

and include this one outside of that function (in the global context).

window.addEventListener("load",initialize, false);

Furthermore, eliminate any other instances of calls to the initialize function.

Answer №2

The problem has been identified: instead of using an id, I mistakenly used a class. Correcting this error by changing the class to an id both in CSS and HTML resolved the issue.

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

Looking to import a 3D gltf model using the input tag in an HTML file for use in three.js (JavaScript), but encountering an issue with the process

I am trying to upload my 3D model from an HTML input tag, but I keep encountering this error message: t.lastIndexOf is not a function Here's the HTML code I am using: <input type="file" id="MODEL" /> <button onclick=&qu ...

Thumbnail Carousel Caption in Bootstrap 3

Is it possible to create a Bootstrap 3 carousel where the image changes when the mouse cursor hovers over the thumbnail under the carousel? Currently, I have a setup with the carousel and thumbnails below it. Typically in Bootstrap, the image changes autom ...

Steps for adding user identification to a CoffeeScript file

I'm facing a dilemma. I have a User model, an Event model, and also using fullcalendar. $(document).ready -> $("#calendar").fullCalendar( events: '/events.json' ) In my coffeescript file, the code isn't working because it r ...

Utilizing Angular's asynchronous validators to handle incoming response data

Struggling with async validators in Angular and trying to implement Container/Presentational Components architecture. Created an async validator to check for the existence of an article number, with the service returning detailed information about the arti ...

The Angular frontend appears to be experiencing difficulties displaying content on the website

I'm currently working through the AngularJS on Rails tutorial from Thinkster(). Check out my progress so far https://jsfiddle.net/dcbavw4e/ I'm not seeing anything on the web page. I've already installed node.js and npm. Are there any othe ...

developing a fresh node within the jstree framework

Recently, I have been working on creating a node using crrm as shown below $("#TreeDiv").jstree("create", $("#somenode"), "inside", { "data":"new_node" }); This specific function is triggered by a wizard, enabling me to seamlessly create a new node withi ...

Look into HTML and JavaScript problems specific to IOS devices

I have encountered some HTML markup and JavaScript functionality issues on my web-app that seem to only occur on iPad and iPhone. Unfortunately, I do not have access to any iOS devices to debug these problems. How can I replicate and troubleshoot these i ...

Issue with looping in Javascript with jQuery

Can anyone explain why this for loop returns "bob" but "undefined" for "jacob"? $(function(){ count = 1; for(x=0; x <= count; x++) { track = $('#track' + x).val(); document.write(track ...

Is it possible to make an element draggable after it has been prep

Seeking assistance with making a notification draggable when added to a webpage. The notifications are housed in a parent div named notification_holder Here is the structure: <div class="notification_holder"> <div class="container"><b ...

Tips on rotating a 3D shape using axis in three.js

Help needed with rotation in three.js I am facing a challenge when trying to rotate a 3D cube in one of my games. //initialize geometry = new THREE.CubeGeometry grid, grid, grid material = new THREE.MeshLambertMaterial {color:0xFFFFFF * Math.random(), sha ...

How can YouTube Videos be integrated using the HTML5 <video> Tag?

I'm working on a project that involves embedding Youtube videos into a div tag using HTML5. Can anyone share a way to do this without relying on the <iframe> element? ...

Using async/await in an Express route handler

Currently, I am facing an issue with my node/express route. The route collects information through url parameters and then uses these parameters to trigger a separate function that takes some time to execute. Despite using async/await to pause the executio ...

div added on the fly not showing up

I'm attempting to dynamically add a div to a webpage using Chrome. Despite following several instructional guides, the code does not seem to be working as expected. I have added style attributes to make it more visible, but the element is not showing ...

Customizing Bootstrap CSS

In my recent code, I included a bootstrap css reference in this manner: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5T ...

An error of type TypeError occurred while attempting to browserify a module in a Node.js environment

Is there a way to integrate this algorithm into a client-side function? I'm looking to use the RAKE Module within a browserified function on the client side. You can find the RAKE Module on GitHub here: https://github.com/waseem18/node-rake To compi ...

Encountered Runtime Error: TypeError - Carousel triggering issue with reading properties of null (specifically 'classList') in Tailwind Elements

Currently, I am encountering the error message: Unhandled Runtime Error TypeError: Cannot read properties of null (reading 'classList') while utilizing the Carousel component. The problem arises when I attempt to populate the carousel with images ...

Creating a heading transition that moves from the bottom to the top with CSS

I am looking to add an animation effect to the H1 element in my program. I want it to smoothly appear from the bottom hidden position using a CSS transition when the page loads. How can I achieve this? Additionally, I need the height of the bounding elemen ...

Each time the web animation is utilized, it gets faster and faster

As part of an assignment, I am working on creating an interactive book that can be controlled by the arrow keys and smoothly comes to a stop when no key is being pressed. However, I have noticed that with each arrow key press, the animation speeds up. Bel ...

Using JavaScript to organize and categorize data within an array

I am working with a multidimensional array and need to filter it based on the value at a specific index position. Here is what the array looks like: arr = [ [1 , 101 , 'New post ', 0], [2, 101 , 'New Post' , 1], ...

Differentiating between mouseenter and tap events: What's the key?

When a mouseenter event is present, touch-enabled devices will activate this event when the user taps on the element. Is there a way to differentiate between an actual physical mouse entering and a simulated tap (which resembles a mouse enter)? ...