Reputation: 25
I want to insert 3 different google maps into a page on a website and also include markers.
The following script places the google map with marker in a div named #william_harvey. I then want two additional and different maps to display with markers in other divs named #chaucer and #kims but can't get this to work. Any advice?
<script>
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map1 = new google.maps.Map(document.getElementById('william_harvey'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?signed_in=true&callback=initMap"></script>
Upvotes: 0
Views: 4333
Reputation: 161324
Make 3 separate google.maps.Map
objects, three separate google.maps.Marker
objects and add each marker to its associated map.
code snippet:
var william_harvey = {
lat: 51.143183,
lng: 0.915349
};
var chaucer = {
lat: 51.261797,
lng: 1.087446
};
var kims = {
lat: 51.286869,
lng: 0.556317
};
function initMap() {
var myLatLng = {
lat: -25.363,
lng: 131.044
};
var map1 = new google.maps.Map(document.getElementById('william_harvey'), {
zoom: 14,
center: william_harvey
});
var marker1 = new google.maps.Marker({
position: william_harvey,
map: map1,
title: 'Hello World!'
});
var map2 = new google.maps.Map(document.getElementById('chaucer'), {
zoom: 14,
center: chaucer
});
var marker2 = new google.maps.Marker({
position: chaucer,
map: map2,
title: 'Hello World!'
});
var map3 = new google.maps.Map(document.getElementById('kims'), {
zoom: 14,
center: kims
});
var marker2 = new google.maps.Marker({
position: kims,
map: map3,
title: 'Hello World!'
});
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body,
#william_harvey,
#chaucer,
#kims {
height: 300px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="william_harvey" style="border: 2px solid #3872ac;"></div>
<div id="chaucer" style="border: 2px solid #3872ac;"></div>
<div id="kims" style="border: 2px solid #3872ac;"></div>
Upvotes: 2
Reputation: 984
initMap convert function with parameter mapId. Then call the function with div id. Like this:
function mapCreate(id)
{
var myLatLng = {lat: -25.363, lng: 131.044};
var map1 = new google.maps.Map(document.getElementById(id), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map1,
title: 'Hello World!'
});
}
mapCreate('chaucer');
mapCreate('kims');
If you different behave maps, use arrays.
Upvotes: 3