Why isn't Google Map showing up in my HTML <div> section?

I am currently working on a web page that consists of two containers. The mainmapdiv container covers the entire page, while the mainhomediv container is positioned on top of the mainmapdiv. My goal is to hide the mainhomediv container and show a Google Map on the mainmapdiv when a user clicks on an image with the id of 'mapbutton'. Here is the code:

<script type="text/javascript">
var map;
function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(-34.397, 150.644),
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("mainmapdiv"), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

<script>
var map;
$(document).ready(function(){
    
    //Click on button to display map
    $('#mapbutton').click(function(){
        $('#mainhomediv').fadeTo("slow",0);
        $('#mainhomediv').css({opacity: 0});
        initialize();
    });
    
    //Click on Home to get back home div
    $('#home').click(function(){
        $('#mainhomediv').fadeTo("slow",1);
        $('#mainhomediv').css({opacity: 1});
    });
});

HTML CODE

<body>
<!--This is the primary container-->
<div id='#mainmapdiv' class='mainmapdiv'>
    <div id='#mainhomediv' class='mainhomediv'>
    .
    //There is an image with id='mapbutton' somewhere in this section
    .
    .
    </div>
</div>
</body>

When I click the image, the mainhomediv container is hidden perfectly, but the map does not display on the mainmapdiv.

I have included the following scripts:

<script src="jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/apijs?sensor=false"></script>

Answer №1

Not sure if this is the solution, but there are some corrections needed:

The JS link you provided is incorrect: http://maps.googleapis.com/maps/apijs?sensor=false

Also, there are extra '#' symbols in your div IDs:

<div id='#mainmapdiv' class='mainmapdiv'>
<div id='#mainhomediv' class='mainhomediv'>

You have multiple instances of var map; in your script.

Answer №2

It is important to specify the dimensions of #mainhomediv

For example:

#mainhomediv {
  width:600px;
  height:400px;
}

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

Could not locate module: Issue: Unable to resolve './Firebase'

I'm a beginner with React and I've been working on setting up Firebase in my React application. import firebase from 'firebase/compat/app'; import 'firebase/compat/auth'; import 'firebase/compat/firestore'; var fire ...

I'm having trouble getting my JavaScript code to run, can anyone offer any advice on what

Can you provide assistance with this code? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv=" ...

Obtain specific information from custom fields on the product page

What am I trying to achieve? I want to create a single product page that displays custom fields which need to be filled out before the item can be added to the cart. Additionally, I have implemented a button that should take all the values entered in the ...

Ionic: setInterval/setTimer not functioning after 5 minutes in the background

In need of a timer that can send notifications via the OneSignal API after a user-defined time period is reached. Users can set the timer for any value between 1-59 minutes. Despite attempts to use the background mode plugin, specifically setInterval and s ...

Once the data is retrieved and the old image is deleted, attempting to upload the new image still results in the old image being displayed in the Next.js application with React Query

async function fetchTour() { const response = await api.get(`/tour/${router.query.slug}`); return response.data; } const { data: tourData, isLoading, isFetching, isTourError: isError, } = useQuery(['fetchTour', router.que ...

Struggling to keep the footer anchored at the bottom of the page

When the content on an HTML page is minimal, the footer may end up positioned halfway up the page, creating a blank space below. This can be unappealing, especially on larger screens. Designers are frequently tasked with moving footers to the bottom of the ...

Resetting the internal state in Material UI React Autocomplete: A step-by-step guide

My objective is to refresh the internal state of Autocomplete, a component in Material-UI. My custom component gets rendered N number of times in each cycle. {branches.map((branch, index) => { return ( <BranchSetting key={ind ...

Conceal the unstyled element and reveal its adjacent sibling?

I have come across some HTML code that I am unable to modify. Instead of using JS/jQuery, I prefer a solution with cross-browser compatible CSS. The structure of the HTML is as follows: <ul class="list"> <li class="item"> <a hr ...

Ensuring a radio button is pre-selected by default in React by passing in a prop

Assume I have a React function similar to this function Stars({handleStarClick, starClicked}) { if (starClicked === 3) { document.getElementById('star3').checked = true } return ( <div className="rate"> ...

Sending data from Node.JS to an HTML document

Currently, I am working on parsing an array fetched from an API using Node.js. My goal is to pass this array as a parameter to an HTML file in order to plot some points on a map based on the API data. Despite searching through various answers, none of them ...

Display a division upon clicking a button using AngularJS and HTML

Looking to implement a functionality in my HTML page using angularJS. I am currently learning angularJs and experimenting with a feature where clicking on a button will display a specific div (EmployeeInfoDiv) on the webpage. The idea is to fill out some t ...

Passing parameters to an external function in order to display a message is proving difficult. An error of type TypeError is being encountered, specifying that the Class constructor AlertMessage cannot be called without using the

Every time I attempt to pass a message as an argument to the showAlert() function, an error is triggered: Error: An instance of the AlertMessage class cannot be created without using 'new' image: I am simply trying to send the message as a para ...

How to Vertically Center a Span in a Mat-Header-Cell with Angular 5 Material

In my angular5 application, I am utilizing a material table to showcase some data. Within a mat-header-cell, I have a combination of a span and an img, and I'm attempting to align them correctly. This is how it currently appears: Below is the snipp ...

Transforming the file name in real time while uploading with jQuery uploadify

Currently, I am using uploadify, which is a jQuery plugin, to facilitate the uploading of files while adding clients to my database. One challenge I encountered was attaching files to new clients who have not yet been added to the database. To address thi ...

Encountering a problem with ajax when using the "show" action

I have the following action: def out_team if params[:user] @user = User.find_by(id: params[:user]) @user.update(team_id: nil) render nothing: true respond_to do |format| format.json { render :json => 'teste' } ...

Assign a unique value to every line in a JSON string within the Vue.js hierarchy of components

I created a Vue component that initializes an empty list and an object like this: data: function(){ return { list: [], newThing: { body: '', }, }; }, The list is then populated with JSON data fetched ...

Troubleshooting Next.js and NextAuth.js Authentication Redirect Issue

I am experiencing a problem with authentication in my Next.js application using NextAuth.js. The issue specifically pertains to the redirection after successful login. Here is an overview of my setup: NextAuth.js Configuration (app/api/auth/[...nextauth.js ...

Display a modal when clicking on a bootstrap glyph icon

I tried following a tutorial on how to create a Bootstrap modal at https://www.w3schools.com/bootstrap/bootstrap_modal.asp However, I would like to use a glyph icon in the code snippet like this: <span class="glyphicon glyphicon-pencil" class="btn btn ...

Preventing jQuery from removing child elements while inserting data through ajax

When I try to insert data into an HTML structure using the code below, only one of the elements displays at a time. It seems like when I use Ajax to insert data, the child elements are being removed. How can I prevent this without having to change the stru ...

Proceed with the next AJAX request only when the previous one has successfully completed

Currently, I am working on a process where PDFs are generated in the background using AJAX calls. The generation of these PDF files usually takes around one second each. Although the process is functional, I have encountered an issue with memory depletion ...