简体   繁体   中英

Google Maps with multiple markers in Bootstrap Modal

I'm trying to display a Google map in a Bootstrap modal with multiple markers. I have found several posts where people were having problems displaying the map on the modal with just one marker, but none with multiple markers. This is what I currently have, but my map is just showing up gray.

var locations = [...]

var complexMap = new google.maps.Map(document.getElementById('complexes-modal-map-canvas'), {
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

//create empty LatLngBounds object
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();

for (i = 0; i < locations.length; i++) {
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        icon: locations[i][3],
        map: complexMap
    });

    //extend the bounds to include each marker's position
    bounds.extend(marker.position);

    google.maps.event.addListener(marker, 'click', (function (marker, i) {
        return function () {
            infowindow.setContent(locations[i][0]);
            infowindow.open(complexMap, marker);
         }
     })(marker, i));
 }

$("#complexes-modal-map-canvas").on("shown.bs.modal", function () {
    var currentCenter = complexMap.getCenter();
    google.maps.event.trigger(complexMap, "resize");
    complexMap.setCenter(currentCenter);
    complexMap.fitBounds(bounds);
});

There are 2 things I had to do to make this work. The first thing was an obvious mistake - I was selecting the incorrect element on the "shown.bs.modal" method. I needed to select my Bootstrap modal, not the Google Map. The second thing was to call the "fitBounds" method before calling the "resize" event and setting the center.

$("#complexes-modal").on("shown.bs.modal", function () {
    complexMap.fitBounds(bounds);
    var currentCenter = complexMap.getCenter();
    google.maps.event.trigger(complexMap, "resize");
    complexMap.setCenter(currentCenter);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM