Reputation: 413
I'm in brain dead mode. I'm trying to use google maps and i'm just starting out with my dummy html. The following code works, but if i put the map div into a container or simply change the name it fails not finding the ID
<body>
<!--
<section id="container">
<div id="map"></div>
</section>
-->
<div id="map"></div>
<script>
function initMap() {
'use strict';
var myLatLng = {lat: 14.79445, lng: 120.271364};
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 6,
center: myLatLng
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOURKEY&callback=initMap">
</script>
</body>
If i take out the comments and run this with the container div, the getElementByID fails.
If i change the id from map to map2 (in both places) the getelement fails.
I know i'm doing something very stupid, but i just don't see it.
Dev environment is brackets, pushing a chrome browser. (my key removed from the API call)
Upvotes: 3
Views: 871
Reputation: 113906
If i change the id from map to map2 (in both places)
This is your problem.
In any DOM (HTML, SVG, XML etc.) an id MUST BE UNIQUE. By unique I mean that only one element must have a specific id. If two or more elements have the same id that's considered an error.
HTML, being a very lenient language, does not throw error messages when developers make mistakes. Instead browsers automatically try to guess what you mean.
There is no standard that specifies what a browser should do if there are two or more identical ids. So getElementById
can do whatever it wants in such cases. Different browsers may do different things.
The failure is not getElementById
. The failure is two elements having the same id.
For what you are trying to do use class
and getElementsByClassName
instead. Take note: it's elementS
by class name, plural.
Upvotes: 1
Reputation: 2153
In a Google example, you will find that you need to set map's height to be 100% of its container. Here's the CSS from their own example:
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
By wrapping it in a container you caused map's 100% to be 0
which is height of its parent div (#container
). The simplest fix here is:
#container, #map {
height: 100%;
}
Here is a working fiddle: https://jsfiddle.net/5bg9gkL9/2/.
Upvotes: 2