motoradk motoradk - 1 year ago 72
Javascript Question

Get an DOM element in the map google div

it's possible to get template text from 'childDiv' id when I initialize a Google Map? My code looks like this:



function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
myOptions);
}
google.maps.event.addDomListener(window, "load", initialize());

#map {
height: 450px;
width: 450px;
}

<script src="https://maps.googleapis.com/maps/api/js"></script>

<div id="map">
<div id="childDiv">testes</div>
</div>





When I debug this code after initialize map function, that my childDiv gone.




Jsfiddle: https://jsfiddle.net/ce4bpzhh/

Answer Source

That is the default way the gogole maps works. It will overwrite the contents of the div you specify for it.

There is an option, however, to tell it to keep the existing contents.

The option is noClear and you must set it to true.


From the Google maps documentation about mapOptions

noClear - Type: boolean
If true, do not clear the contents of the Map div.


Working example

function initialize() {
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var myOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    noClear:true // ADD THIS OPTION
  };
  var map = new google.maps.Map(document.getElementById("map"),
    myOptions);
}
google.maps.event.addDomListener(window, "load", initialize());
#map {
  height: 450px;
  width: 450px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>

<div id="map">
  <div id="childDiv">testes</div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download