0

I'm trying to follow a tutorial on using the Google Maps API. I believe I have followed the tutorial exactly, but for whatever reason, the map is not rendering. I'm not getting any error messages in the console, so I'm not too sure where to look for more error info.

The following is my HTML:

<body>
<div class="content">
    <div id="map" style="width: 100%;"></div>
</div>

<script type="text/javascript" src="https://maps.google.com/maps/api/js?v=3&key=[THE KEY]"></script>
<script type="text/javascript" src="js/scripts.js"></script>

And the JS:

var map;
function loadMap(){
var mapOptions = {
    center: new google.maps.LatLng(28.39404819, -91.38743867),
    zoom: 7,
    mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map"),mapOptions);
}
google.maps.event.addDomListener(window, "load", loadMap());

Finally, the CSS:

#map {
height: 75%;
}

html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}

It's gotta be something small that I'm missing. Any help is greatly appreciated. Thank you!

1 Answer 1

3

You have two problems with the posted code:

  1. google.maps.event.addDomListener(window, "load", loadMap()); executes the loadMap function immediately and assigns the return value as the function to be executed on window load. It should be:
google.maps.event.addDomListener(window, "load", loadMap);
  1. your map doesn't have a size. It is 100% of the div with class="content" which doesn't have a size.
<div class="content">
  <div id="map" style="width: 100%;"></div>
</div>

The CSS should be:

#map {
height: 75%;
}

html, body, .content {
    height: 100%;
    margin: 0;
    padding: 0;
}

(or whatever matches your layout and gives a height to the div with `class="content")

proof of concept fiddle

code snippet:

var map;

function loadMap() {
  var mapOptions = {
    center: new google.maps.LatLng(28.39404819, -91.38743867),
    zoom: 7,
    mapTypeId: google.maps.MapTypeId.HYBRID
  };
  map = new google.maps.Map(document.getElementById("map"), mapOptions);
}
google.maps.event.addDomListener(window, "load", loadMap);
#map {
  height: 75%;
}

html,
body,
.content {
  height: 100%;
  margin: 0;
  padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div class="content">
  <div id="map" style="width: 100%;"></div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.