Reputation: 884
Im trying to display multiple Google Maps on a single page. It is a results page that is dynamically generated per locations in the area. Each div has a map class that I want to run the Google Map off of. As of right now I can only get it to process the information for one div.
I understand that I need to somehow pass Google Maps an array. But I am confused as to how to do this given the uses for my implementation.
HTML
<div class="map" data-address="123 easy st city st zip" data-title="location"></div>
<div class="map" data-address="456 easy st city st zip" data-title="location 2"></div>
jQuery
$('.map').each(function() {
var geoCode = new google.maps.Geocoder(),
container = this;
geoCode.geocode({'address': $(container).data('address')}, function(results, status) {
var start_options = 0;
if (status == google.maps.GeocoderStatus.OK) {
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()),
zoomControl: true,
scaleControl: false,
scrollwheel: false,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
if (navigator.userAgent.match(/(iPod|iPhone|iPad|Android|Blackberry|Windows Phone|Nokia|HTC|webOS)/)) {
mapOptions.draggable=false;
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: results[0].geometry.location,
animation: google.maps.Animation.DROP,
map: map,
title: $(this).data('itemTitle')
});
google.maps.event.addListener(marker, 'click', toggleBounce);
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
var center;
function calculateCenter() {
center = map.getCenter();
}
google.maps.event.addDomListener(map, 'idle', function() {
calculateCenter();
});
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(center);
});
} else {
$(this).parent().hide();
}
});
});
Upvotes: 0
Views: 1645
Reputation: 644
function getGoogleMap(container) { //google code //use the container parameter like so geoCode.geocode({'address': $("#" + container).data('address')}); //or so var map = new google.maps.Map(document.getElementById(container), mapOptions); } getGoogleMap("map1");
Upvotes: 1
Reputation: 3552
Inside your forEach loop you are using document.getElementById("map")
.
This is wrong for a couple of reasons, firstly because the map doesnt have an id, it has a class, and secondly because the map will be attached to the same element each time.
What you want to do is attach the map to the current map in the loop. In your jQuery loop this will be the this
variable.
Conveniently (as this
can often change inside nested functions), the first line of your loop stores this
in a variable called container
.
So simply replace document.getElementById("map")
with container
, and you should get a different map attached to each instance of the .map
element.
Upvotes: 3