Reputation: 17
I want to load 2 google maps using 1 initialize functions on the same page using division class. But the maps are not getting loaded. Can anyone help? Here is my code:
<!DOCTYPE html>
<html>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp">
</script>
<script>
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
var map = new google.maps.Map(document.getElementsByClassName('map-canvas'),
mapOptions);
}
</script>
<body>
<div class="map-canvas" style="height:200px;width:200px;border: 1px solid black;" >
<script>
initialize();
//google.maps.event.addDomListener(window,'load',initialize);
</script>
</div><!-- /.panel-body -->
<div class="map-canvas" style="height:200px;width:200px;border: 1px solid black;" >
<script>
initialize();
//google.maps.event.addDomListener(window,'load',initialize);
</script>
</div><!-- /.panel-body -->
</body>
</html>
Upvotes: 1
Views: 2150
Reputation: 1961
Ok there are some mayor problems in you source:
Your script has to be placed in the head
tag above the body
tag like:
<head>
<title></title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp">
</script>
<script>
var map;
var map2;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
map2 = new google.maps.Map(document.getElementById('map-canvas2'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
You can't initialize the google map by a container class name. All containers had to be unique. As you can see i am creating 2 individual maps 'mapand
map2` and therefore i need two seperate containers in the body tag like:
<div id="map-canvas"></div>
<div id="map-canvas2"></div>
You don't have to call the initialize function in your body tag because it will be called throught the eventListener on window - load
google.maps.event.addDomListener(window, 'load', initialize);
So lets bring it all together: FIDDLE
Upvotes: 5
Reputation: 161384
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
elems = document.getElementsByClassName('map-canvas');
for (var i = 0; i < elems.length; i++) {
var map = new google.maps.Map(elems[i],
mapOptions);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div class="map-canvas" style="height:200px;width:200px;border: 1px solid black;">
</div>
<!-- /.panel-body -->
<div class="map-canvas" style="height:200px;width:200px;border: 1px solid black;">
<script>
initialize();
//google.maps.event.addDomListener(window,'load',initialize);
</script>
</div>
<!-- /.panel-body -->
Upvotes: 1