Reputation: 93
I'm using the Google Maps Javascript API. I'm setting the content of an InfoWindow to be a div. I then try to use document.getElementById() to get the div element in the InfoWindow.
var contentString = '<div id="content" style="width:200px;height:200px;"></div>';
var infowindow = new google.maps.InfoWindow({
position: map.getCenter(),
content: contentString
});
infowindow.open(map);
console.log(document.getElementById('content'));
The InfoWindow shows up at the center of the map as I expect. However, the last line of my code here logs 'null' to the console. If I execute the same line of code within a different function after this code completes, an element is returned from getElementById('content') and info about the element is logged to the console. I don't understand what is happening here. I'd think that immediately after the code lines that create the InfoWindow and open it on the map that the 'content' div is part of the DOM. But running my code says otherwise. Anyone understand what's going wrong?
Upvotes: 0
Views: 301
Reputation: 161334
The infowindow content is added to the DOM asynchronously. It is not available to get using .getElementById
until after it is in the DOM. To detect when it has been added to the DOM use the domready
event on the infowindow:
domready Arguments: None
This event is fired when the containing the InfoWindow's content is attached to the DOM. You may wish to monitor this event if you are building out your info window content dynamically.
var contentString = '<div id="content" style="width:200px;height:200px;">14</div>';
var infowindow = new google.maps.InfoWindow({
position: map.getCenter(),
content: contentString
});
infowindow.open(map);
google.maps.event.addListener(infowindow, 'domready', function() {
console.log(document.getElementById('content'));
});
code snippet:
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var contentString = '<div id="content" style="width:200px;height:200px;">14</div>';
var infowindow = new google.maps.InfoWindow({
position: map.getCenter(),
content: contentString
});
infowindow.open(map);
google.maps.event.addListener(infowindow, 'domready', function() {
console.log(document.getElementById('content'));
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>
Upvotes: 2