The issue of Google map content failing to display within a Bootstrap modal view

https://i.sstatic.net/gaN2t.pngHello amazing coders on Stackoverflow! I am facing an issue where the code below displays a google map when run from a page, but when I embed it into a bootstrap modal, only the shape of the map is shown with no location displayed. Please refer to the attached image for clarification. Can someone kindly assist me with this problem?

Thank you

<!DOCTYPE html>
<html>
<head>
<style>
/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    position: relative;
    background-color: #fefefe;
    margin: auto;
    padding: 0;
    border: 1px solid #888;
    width: 80%;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    -webkit-animation-name: animatetop;
    -webkit-animation-duration: 0.4s;
    animation-name: animatetop;
    animation-duration: 0.4s
}

/* Add Animation */
@-webkit-keyframes animatetop {
    from {top:-300px; opacity:0} 
    to {top:0; opacity:1}
}

@keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}

/* The Close Button */
.close {
    color: white;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}

.modal-header {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;
}

.modal-body {padding: 2px 16px;}

.modal-footer {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;
}
</style>
</head>
<body>

<h2>Animated Modal with Header and Footer</h2>

<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h2>Modal Header</h2>
    </div>
    <div class="modal-body">

<script src="http://maps.google.com/maps/api/js?sensor=false&key=AIzaSyAlb3bRgk_Jq3mBzgpVyLTeeKL-RKaSkx4&callback=initMap" type="text/javascript"></script>


<style>

.map{width: 430px; height: 150px;}
</style>

<div id="map1" class="map"></div>
<script type="text/javascript"> 
var address = "california,USA";
var myLatlng = new google.maps.LatLng(95.1, 16.0);
var map1 = new google.maps.Map(document.getElementById("map1"), {mapTypeId: google.maps.MapTypeId.ROADMAP,zoom: 12,center: myLatlng});
var geocoder = new google.maps.Geocoder();
geocoder.geocode({"address": address},function(results, status) {if(status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({position: results[0].geometry.location,map: map1});
map1.setCenter(results[0].geometry.location);}});
</script>

    </div>
    <div class="modal-footer">
      <h3>Modal Footer</h3>
    </div>
  </div>

</div>

<script>
// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>

</body>
</html>

Answer №1

There have been some improvements made to the code below. Pay attention to the "CHANGE" notes in the comments. The main issues addressed are:

  1. Create a parent div for the map div and control the visibility of the parent instead of the map itself. Setting the map div to be invisible initially could disrupt the map functionality, so controlling its parent's visibility will prevent this issue.
  2. Merged the map creation into a function call that only executes the first time you attempt to show the modal. This is managed with a global boolean variable.

Below is the revised and tested code:

<!DOCTYPE html>
<html>

<head>
    <style>
        /* CHANGE 1: created a hidden parent for the modal */

        #parent {
            display: none;
        }
        /* The Modal (background) - CHANGE 2: removed display none */

        .modal {
            position: fixed;
            /* Fixed position */
            z-index: 1;
            /* Top layer */
            padding-top: 100px;
            /* Positioning */
            left: 0;
            top: 0;
            width: 100%;
            /* Full width */
            height: 100%;
            /* Full height */
            overflow: auto;
            /* Scroll enabled if needed */
            background-color: rgb(0, 0, 0);
            /* Fallback color */
            background-color: rgba(0, 0, 0, 0.4);
            /* Black with opacity */
        }
        /* Modal Content */

        .modal-content {
            position: relative;
            background-color: #fefefe;
            margin: auto;
            padding: 0;
            border: 1px solid #888;
            width: 80%;
            box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
            -webkit-animation-name: animatetop;
            -webkit-animation-duration: 0.4s;
            animation-name: animatetop;
            animation-duration: 0.4s
        }
        /* Animation */

        @-webkit-keyframes animatetop {
            from {
                top: -300px;
                opacity: 0
            }
            to {
                top: 0;
                opacity: 1
            }
        }

        @keyframes animatetop {
            from {
                top: -300px;
                opacity: 0
            }
            to {
                top: 0;
                opacity: 1
            }
        }
        /* Close Button */

        .close {
            color: white;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: #000;
            text-decoration: none;
            cursor: pointer;
        }

        .modal-header {
            padding: 2px 16px;
            background-color: #5cb85c;
            color: white;
        }

        .modal-body {
            padding: 2px 16px;
        }

        .modal-footer {
            padding: 2px 16px;
            background-color: #5cb85c;
            color: white;
        }
    </style>
</head>

<body>

    <h2>Animated Modal with Header and Footer</h2>

    <!-- Trigger/Open The Modal -->
    <button id="myBtn">Open Modal</button>
    <!-- CHANGE 3: added the parent div -->
    <div id="parent">

        <!-- The Modal -->
        <div id="myModal" class="modal">

            <!-- Modal content -->
            <div class="modal-content">
                <div class="modal-header">
                    <span class="close">&times;</span>
                    <h2>Modal Header</h2>
                </div>
                <div class="modal-body">
                    <script>
                        /* CHANGE 4: included a callback function definition */
                        function initMap() {

                        };

                        /* CHANGE 5: function to create the map when needed */
                        function doMap() {
                            var address = "California, USA";
                            var myLatlng = new google.maps.LatLng(30.2719771, -97.7475389);
                            var map1 = new google.maps.Map(document.getElementById("map1"), {
                                mapTypeId: google.maps.MapTypeId.ROADMAP,
                                zoom: 12,
                                center: myLatlng
                            });
                            var geocoder = new google.maps.Geocoder();
                            geocoder.geocode({
                                "address": address
                            }, function(results, status) {
                                if (status == google.maps.GeocoderStatus.OK) {
                                    var marker = new google.maps.Marker({
                                        position: results[0].geometry.location,
                                        map: map1
                                    });
                                    map1.setCenter(results[0].geometry.location);
                                }
                            });
                        }

                        // CHANGE 6: additional variable to control the parent
                        var parent = document.getElementById('parent');
                        var modal = document.getElementById('myModal');

                        // Access the button that opens the modal
                        var btn = document.getElementById("myBtn");

                        // Locate the <span> element that closes the modal
                        var span = document.getElementsByClassName("close")[0];

                        // CHANGE 7: perform initial setup once
                        var bFirstShow = true;

                        // When the user clicks the button, open the modal
                        btn.onclick = function() {
                            parent.style.display = "block";
                            // Initiate the map when required
                            if (bFirstShow == true) {
                                doMap();
                                bFirstShow = false;
                            }
                        }

                        // On clicking the <span> (x) close the modal
                        span.onclick = function() {
                            parent.style.display = "none";
                        }

                        // If you click outside the modal, close it
                        window.onclick = function(event) {
                            if (event.target == modal) {
                                parent.style.display = "none";
                            }
                        }
                    </script>
                    <script src="http://maps.google.com/maps/api/js?sensor=false&key=YOUR_API_KEY_HERE&callback=initMap" type="text/javascript"></script>


                    <style>
                        .map {
                            width: 430px;
                            height: 150px;
                        }
                    </style>

                    <div id="map1" class="map"></div>
                </div>
                <div class="modal-footer">
                    <h3>Modal Footer</h3>
                </div>
            </div>

        </div>
    </div>
</body>

</html>

I hope this explanation helps! :)

Sincerely,

Dave

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

Ways to apply jquery.validate rules that have already been defined to form fields that are added dynamically

I need to duplicate a specific section of a form and apply the same validation rules that were set up before. After researching this issue, I found that most recommendations suggest adding new rules to the newly generated elements. Therefore, I attempted ...

the issue of undefined values continue to persist

I've been struggling with this code for a couple of days and it's causing issues. All the other functions are working fine except for this EQUAL function. Here is the code: equal.addEventListener("click", function(e){ if (screen.value == ...

Guide to iterating through an array within an object in Vue.js

Can someone help me with looping through data fetched from an API using a GET request in Vue.js? This is the sample response obtained: "data": { "Orders": [ { "OrderID": 1, "Ordered_Products": { ...

Develop an Engaging JavaScript Quiz with Elements That are Generated Dynamically

** Need help setting answer values for checkboxes Currently, I have a code that displays (2) questions with (4) possible answers each. Next to each answer is a checkbox with a default value of false. However, I want to link the value of each checkbox to ...

Channeling requests from webpack dev server to .net MVC website

I am working on incorporating Vue into my .net MVC project. After installing Vue using the CLI, I included the following vue.config.js: module.exports = { devServer: { proxy: { '/': { target: 'http://mvcsite.local', ...

Is it feasible to utilize math.max with an array of objects?

When it comes to finding the largest number in an array, solutions like this are commonly used: var arr = [1, 2, 3]; var max = Math.max(...arr); But how can we achieve a similar result for an array of objects, each containing a 'number' field? ...

Exploring the child element of the present DOM node within Angular

In my template, I have a code snippet similar to the one below: <button class="btn" > <audio src="mySourceFile.wav"></audio> </button> When the button is clicked, I want to play the audio object. Ideally, I would like to achieve ...

Struggling with setting up dynamic URL parameters in react-router

I'm working on generating dynamic URLs to display different content based on the URL parameters. When I include: <Route path="/example/:id" component={Example} /> and then visit /example/99 in my browser, I see an error message in th ...

Leveraging Axios within VueJS - the missing piece

When working with typescript and vuejs + axios, I have included the following .catch function on a post request to handle network errors and inform the user of the status: .catch(function(error) { console.error(error.response); ...

AngularJs Resource provides the functionality to pass optional parameters through the URL

Currently, I am utilizing this type of resource: var Products = $resource('companies/:companyId/products') However, the issue arises when I attempt to access the products from all companies via the URL companies/products. Instead of receiving the ...

Express npm dependency fails to start globally

I have recently reinstalled my operating system from Windows 8.1 to Windows 8.1, and I have been using npm for quite some time. Previously, it was working fine as mentioned here. After the reinstallation, I tried installing npm i -g express, but it does n ...

I am attempting to create a skybox, yet it seems like I am overlooking a crucial element

Currently, I am attempting to create a skybox but have encountered difficulties with various tutorials. Initially, I tried to use an array approach to pass parameters for the material based on a previous example, but it seems that the method has been updat ...

Form a triangle in order to prevent the inner content from spilling out

I'm currently attempting to design a triangle shape that prevents the inner content from overflowing while still allowing the inner content to be draggable. So far, I have experimented with various solutions such as polygons and canvas, but none of t ...

What are some ways to adjust red and green blocks using CSS?

One question that arises is how to create a version of a webpage where only the yellow block can slide up, while the red and green blocks remain fixed. Currently, the green block is treated with the following CSS: position:sticky; right:0px; top:100px; ...

Using vanilla JavaScript, make a Cross-Origin Resource Sharing (CORS) POST request to

I encountered a CORS issue while using the Google Speech API. I am trying to send an audio file (POST request) to https://www.google.com/speech-api/v2/recognize?xjerr=1&client=chromium&lang=en-US&maxresults=10&pfilter=0&xjerr=1&ke ...

Combining JSON array objects in Vanilla Javascript to create a nested array based on a shared value

I have been searching for a solution to address my specific issue but have not found an exact match. If there is a similar question, please provide a link to the solution. I am looking to merge an array of objects that share a common value using vanilla J ...

Escaping double quotes in dynamic string content in Javascript can prevent unexpected identifier errors

Need help with binding the login user's name from a portal to a JavaScript variable. The user's name sometimes contains either single or double quotes. I am facing an issue where my JavaScript code is unable to read strings with double quotes. ...

Retrieving and setting data in ReactJS

Currently utilizing Reactjs in tandem with MongoDB. Once a user makes a selection in Reactjs, that value is then sent over to MongoDB. addTodo(event) { event.preventDefault(); var roomID = this.state.selectedRoomID; console.log(Ro ...

Swap the comma for a period as you type out jQuery code

Hey there, I'm trying to figure out how to use jQuery to replace a comma with a dot while typing in a text input field. Currently, my code looks like this: $(document).on('change', '.unitprice', function() { $(this).val().replac ...

What are the best scenarios for utilizing (a)synchronous calls?

Currently, I am working on a project for my office as a learning exercise. We have a tradition of bringing food every Monday, so I decided to create a program that displays each person's turn. My webpage can generate a calendar with a spare color colu ...