只有在模态时,Google地图才会以标记为中心

时间:2013-07-15 12:24:37

标签: google-maps google-maps-markers

看看这个jsfiddle http://jsfiddle.net/CdRdd/2/。看看地图是如何偏离标记的中心的?现在,当它不在模态http://jsfiddle.net/CdRdd/4/中时,请查看相同的地图。发生了什么事?

function initialize() {
  var addresses = $('.tracking-map-marker-details');

  window.map = new google.maps.Map(document.getElementById('map_canvas_trackingmap'), {
    mapTypeId: google.maps.MapTypeId.HYBRID
  });

  var infowindow = new google.maps.InfoWindow(),
      bounds = new google.maps.LatLngBounds(),
      geocoder = new google.maps.Geocoder();

    $(addresses).each(function() {
        var address  = $(this).data('address'),
            letter   = $(this).data('letter'),
            status   = $(this).data('status');

      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          var marker = new google.maps.Marker({
            icon: "http://www.google.com/mapfiles/marker" + letter + ".png",
            shadow: 'http://www.google.com/mapfiles/shadow50.png',
            position: results[0].geometry.location,
            map: map
            });

            bounds.extend(results[0].geometry.location);
        }
      });
    });

  var listener = google.maps.event.addListenerOnce(map, "idle", function () {
    map.fitBounds(bounds);
    map.setZoom(5);

    $('#tracking_map_modal').modal('show').on('shown', function () {
      google.maps.event.trigger(map, 'resize');
    });
  });     
}

2 个答案:

答案 0 :(得分:1)

google.maps.Map fitBounds只会确保地图的视口包含给定的边界。

您希望拨打google.maps.Map setCenter,传递标记latLng

if (status == google.maps.GeocoderStatus.OK) {
    // var marker = ...;
    window.map.setCenter(results[0].geometry.location);
    // ...
}

答案 1 :(得分:1)

答案是在显示模态后设置中心

$('#tracking_map_modal').modal('show').on('shown', function () {
      google.maps.event.trigger(map, 'resize');
      map.setCenter(bounds.getCenter());
 });