谷歌地图不会居中

时间:2012-12-17 22:08:52

标签: jquery google-maps google-maps-api-3 google-maps-markers centering

我正在使用Twitter Bootstrap并在模式中实现了Google地图,动态显示了制作人的位置。一切都很好,除了标记不会居中的事实。相反,它总是位于左上角(仅在滚动时才会看到)。

我在这里尝试过很多东西但却无法让它发挥作用。有人可以帮帮我吗?

HTML:

  <div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
      <h3 id="myModalLabel">Test</h3>
    </div>
    <div id="modal-left" class="modal-body left">
    </div>
    <div class="modal-body right">
      <div id="map"></div>
    </div>
  </div>
</div>
<div class="row span12">
  <div id="allProducers"></div>
</div>

相关的css:

#map {
  height: 300px;
  width: 300px;
}

.hide {
  display: none;
}

JS:

function largeMap(latitude, longitude){
    var Latlng = new google.maps.LatLng(latitude, longitude);

    var Options = {
        zoom: 10,
        center: Latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var Map = new google.maps.Map(document.getElementById("map"), Options);

    var Marker = new google.maps.Marker({
        position: Latlng,
        map:Map,
        title:"The Map"
    });

    Marker.setMap(Map);
}

$('.modal-btn').click(function(){

    var producerId = $(this).attr('id');

    GetProducer(producerId, function(data) {
        var titel = data.name;

        $('#myModalLabel').html(titel);

        $('#myModal').on('shown', function () {
          google.maps.event.trigger(map, 'resize');
          map.setCenter(new google.maps.LatLng(data.longitude, data.latitude));
        })
    });
});

注意:我很乐意创建一个jsFiddle,但因为我使用的是一个模态(包含在Twitter Bootstrap中),这可能是问题的一部分,不起作用。 < / p>

2 个答案:

答案 0 :(得分:4)

基本上你需要访问Map对象(强烈建议只重用你的LatLng对象),你可以这样做:

var Map; 
var Markerlatlng

function largeMap(latitude, longitude){
  Markerlatlng= new google.maps.LatLng(latitude, longitude);

  var Options = {
    zoom: 10,
    center: Markerlatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  Map = new google.maps.Map(document.getElementById("map"), Options);

  var Marker = new google.maps.Marker({
    position: Markerlatlng,
    map:Map,
    title:"The Map"
  });

  Marker.setMap(Map);
}



$('.modal-btn').click(function(){

  var producerId = $(this).attr('id');

  GetProducer(producerId, function(data) {
    var titel = data.name;

    $('#myModalLabel').html(titel);

    $('#myModal').on('shown', function () {
      google.maps.event.trigger(Map, 'resize');
      Map.setCenter(Markerlatlng);
    })
  });
});

答案 1 :(得分:1)

我认为你混淆了这些案件:

 var Map = new google.maps.Map(document.getElementById("map"), Options);

 map.setCenter(new google.maps.LatLng(data.longitude, data.latitude));

试试这个

 map = new google.maps.Map(document.getElementById("map"), Options);

你的firebug / chrome控制台没有任何问题吗?

相关问题