Using the Google Maps API to display a map on two different HTML pages, but encountering an error on one of them

"Map: Expected mapDiv of type Element but was passed null."

-The height of the div is set in the css.

Javascript (googleMaps.js):

    function initMap() {
    try {
   

      const sportHall2 = { lat: 51.18310959584043, lng: 
         4.38829092697164 }; 
     
        const map2 = new google.maps.Map(document.getElementById("map-2"), 
        {
          zoom: 13,
          center: sportHall2,
          disableDefaultUI: true,
          zoomControl: true,
          fullscreenControl: true,
          streetViewControl: true,
        });
    
        const map2b = new google.maps.Map(document.getElementById("map-2b"), {
          zoom: 13,
          center: sportHall2,
          disableDefaultUI: true,
          zoomControl: true,
          fullscreenControl: true,
          streetViewControl: true,
        });
        } catch (error) {
        console.log(error);
      } 
    } 

HTML Page 1:

 <script src="/scripts/googleMaps.js"></script>
          <div class="grid-card">
                <h3>Pius X-instituut</h3>
                <h5>Bekijk de sporthal hier.</h5>
                <p>Adres: Hof Van Tichelen 28 2020 Antwerpen</p>
                <div id="map-2"></div>
            </div>
    <script src="/scripts/googleMaps.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js? 
    key=YOUR_API_KEY&callback=
    initMap&libraries=&v= 
    weekly" async></script>

HTML Page 2 (error occurs and map won't display on this page):

  <script src="/scripts/googleMaps.js"></script>

        <div class="grid-card map-2b-container">
            <h3>Pius X-instituut</h3>
            <h5>Bekijk de sporthal hier.</h5>
            <p>Adres: Hof Van Tichelen 28 2020 Antwerpen</p>
            <div id="map-2b"></div>
        </div>

    <script src="/scripts/googleMaps.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js? 
    key=YOUR_API_KEY&callback=
    initMap&libraries=&v=weekly" async></script>

CSS:

#map-2{
height: 300px;
width: 100%;
}
 
#map-2b{
height: 300px;
width: 100%;
}

ERROR: Se {message: "Map: Expected mapDiv of type Element but was passed null.", name: "InvalidValueError", stack: "Error↵ at new Se (https://maps.googleapis.com/m… 6ho4&callback=initMap&libraries=&v=weekly:156:128"}

Answer №1

Give this a shot:

Reference: Google Maps API

let mapContainer = document.getElementById("map-container");

let customMap = new google.maps.Map(mapContainer, {
    zoom: 13,
    center: sportsComplex,
    disableDefaultUI: true,
    zoomControl: true,
    fullscreenControl: true,
    streetViewControl: true,
});

Answer №2

If you haven't yet experimented with embedding google maps through iframe, this can be a simple way to include a map in your HTML.

First, visit https://www.google.com/maps
Secondly, input the specific location you wish to embed.
Thirdly, navigate to the menu, select share or embed map, then access the embed map tab.
Lastly, copy the iframe tag and insert it into your HTML file.

Answer №3

   function initializeMap() {
   try {

   const recreationCenter = { lat: 51.18310959584043, lng: 
     4.38829092697164 }; 

   if(document.getElementById('map-2')){
    const map2 = new google.maps.Map(document.getElementById("map-2"), {
        zoom: 13,
        center: recreationCenter,
        disableDefaultUI: true,
        zoomControl: true,
        fullscreenControl: true,
        streetViewControl: true,
    });
  }
} 

The code above sets the div Id's on individual pages as "map-2" and verifies the existence of the div before executing the Map() constructor.

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

What could be causing the TypeError I encounter when trying to import @wordpress/element?

Encountering a similar issue as discussed in this related question. This time, I've switched to using '@wordpress/element' instead of 'react-dom/client' based on the recommendation that it also leverages React functionalities. Ho ...

Methods for removing cookie during logout with Express and Passport JS?

I have been struggling to delete cookies upon logout but haven't had any luck so far. I searched online and came across two methods: Setting a new expiration date for the cookie res.cookie('connect.sid', '', {expires: new Date(1 ...

Error: Appwrite Login Authentication failed due to account.createEmailSession function not recognized as a valid function

Looking for help with Vue and Appwrite? Check out this tutorial: https://appwrite.io/docs/tutorials/vue/step-1 src/appwrite/index.js import { Client, Databases, Account } from "appwrite"; const client = new Client(); client .setEndpoint(" ...

consistent height across the div when expanding

There is a recurring issue I encounter where it takes too long for me to solve the problem. My goal is to ensure that the bootstrap boxes at the bottom of the page have the same height. I attempted to set a fixed height in pixels using my CSS, but this cau ...

Transform your data visualization with Highcharts enhanced with the stylish appearance of DHTML

I am currently using a dhtmlx menu with my charts, specifically the legendItemClick event. It worked perfectly when I was using highcharts 3.0.1. However, after upgrading to version 4.1.7, the function legendMenu_<?=$id?>.showContextMenu(x,y) in the ...

Leveraging react redux in conjunction with next.js

Recently, I attempted to integrate Redux into my project using the next.js starter template from here. I successfully installed the next-redux-wrapper, however, I am having trouble locating the root file in the project. I followed the tutorial provided on ...

What is the syntax for creating a for loop in JSX within a React component?

I am working on a simple program that involves using a for loop to print numbers from 0 to 10. My goal is to utilize a for loop to print these numbers and pass the props to a child component. Please see my code below: import React, { Component } from &apo ...

Placement of navigation bar on top of picture

Creating a gaming website and encountering challenges with text alignment. The goal is to have the navbar text positioned on top of a customized navbar background. Current appearance navbar example <!DOCTYPE html> <html> <head> ...

Is there a way to align my green button beside the red button instead of below it?

I'm looking to rearrange the positioning of my green button on the screen. When I initially created the button, it ended up below my red button, but I want them to be displayed side by side. I haven't attempted any solutions because I am a beginn ...

Utilize key-value pairs to reference variables when importing as a namespace

Is it feasible to utilize a string for performing a lookup on an imported namespace, or am I approaching this the wrong way? Consider a file named my_file.ts with contents similar to: export const MyThing: CustomType = { propertyOne: "name", ...

Retrieving a specific time using a JavaScript interface

I am currently implementing a JavaScript control that can be found on this website: My question is, how can I retrieve the selected date from the control in order to pass it to a postback page? I attempted to figure it out myself, but my JavaScript skills ...

Problem with Marionette AppRouter compatibility when used with Browserify

app.js module.exports = function () { if (!window.__medicineManager) { var Backbone = require('backbone'); var Marionette = require('backbone.marionette'); var MedicineManager = new Marionette.Application(); Medicin ...

What advantages does JWT have over Firebase that make it the preferred choice?

In our authentication systems, we have the option to verify a user through Firebase or by their stored email in the database. Despite having these methods of verification, why do we incorporate JWT (json web token) into our processes? What distinct advan ...

Can you explain the purpose of App.hiddenDivs in jQuery code snippet provided?

Exploring various JQuery performance tips on this insightful website Do you happen to know the significance of App.hiddenDivs ? ...

Rotation with a tilt in Three.js

My goal is to create a solar system simulation using Three.js, but I'm having trouble getting the planets to rotate in an inclined manner around the star. I have attempted to implement a solution, but the rotation is not correct. Here is a sample in a ...

The CSS infinite animation becomes erratic and sluggish after a short period of time

My website featured a banner with a series of thumbnail images that animated at different intervals and looped indefinitely. Initially, the animations ran smoothly, but after a few seconds, they began to slow down and lose consistency. To troubleshoot, I u ...

Parallel ajax function

After creating a form for registering new accounts, I wanted to ensure that the chosen email is available by checking it against a webservice. However, this process takes a few seconds. Let's take a look at the method used: function validateEmail(ema ...

Show button once modal has been closed

I have a 'start' button that triggers a modal window with an embedded video. Once the user closes the modal, I want to show a 'redeem' button after a delay of 6 seconds. HTML: <a id="video-start" onclick="openVideoModal()"><i ...

I am experiencing difficulty with the button not responding when clicked, despite trying to implement JavaScript and the Actions syntax

Currently, I am in the process of automating form filling. After filling out the form, there is an update button that changes color instead of clicking when activated. This alteration indicates that the xpath is correctly identified. I have attempted two ...

Incorporating Vuetify into a Vue CLI application with the help of webpack

I am facing an issue with my Vue CLI application that uses Webpack and Vuetify. The Vuetify components are not loading properly, and I keep getting the following warnings: Unknown custom element: < v-app > - did you register the component correctly? ...