Barek Barek - 7 months ago 79
Javascript Question

Can't add multiple google maps in one page?

This is my entire code, and I don't know why it doesn't work. I know that this question was asked before, but I still haven't found the solution to this code. I need to put multiple google maps... I can do it with one, however when I try to initialize more, it does not work:

<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Best Bikeparks</title>
<style>
html, body {
height:100%
margin: 0;
padding: 0;
}
#map1 {
width: 175px;
height: 120px;
background-color: #CCC;
}
#map2 {
width: 175px;
height: 120px;
background-color: #CCC;
}
#map3 {
width: 175px;
height: 120px;
background-color: #CCC;
}
</style>
</head>
<body>
<div id="map1"></div>
<div id="map2"></div>
<div id="map3"></div>
<script>
function initialize() {
var myLatlng1 = new google.maps.LatLng(39.630159,-84.175937);
var myLatlng2 = new google.maps.LatLng(33.677705,-117.852974);
var myLatlng3 = new google.maps.LatLng(51.520614,-0.121825);
var mapOptions1 = {
zoom: 15,
center: myLatlng1,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: 0
}
var mapOptions2 = {
zoom: 15,
center: myLatlng2,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: 0
}
var mapOptions3 = {
zoom: 15,
center: myLatlng3,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: 0
}
var map1= new google.maps.Map(document.getElementById('map1'),mapOptions1);
var map2 = new google.maps.Map(document.getElementById('map2'), mapOptions2);
var map3 = new google.maps.Map(document.getElementById('map3'), mapOptions3);

var marker1 = new google.maps.Marker({
position: myLatlng1,
map: map1,
title: 'Herastrau'
});
var marker2 = new google.maps.Marker({
position: myLatlng2,
map: map2,
title: 'Insbruck'
});
var marker3 = new google.maps.Marker({
position: myLatlng3,
map: map3,
title: 'Blala'
});
}
</script>


<script async defer
src="https://maps.googleapis.com/maps/api/js?key= MyAPI">
</script>
</body>
</html>

Answer

Remove the reference to the google maps javascript file on line 3 (you're adding it at the bottom) and change your api key reference to have the call back "&callback=initialize"

<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=initialize"></script>

Comments