2016-01-04 73 views
1

我在我的應用程序上使用了Google-Maps-for-Rails。我的house對象獲得了latitudelongitude屬性。我的操控者將這種東西放進一個數組並將其傳遞給在我看來,的javascript:使用Google-Maps-for-Rails和Rails的標記中心圖4

def show 
    @hash = Gmaps4rails.build_markers(@house) do |house, marker| 
    marker.lat house.latitude 
    marker.lng house.longitude 
    end 
end 

的看法是這樣的:

<div style='width: 800px;'> 
    <div id="map" style='width: 800px; height: 400px;'></div> 
</div> 

<script type="text/javascript"> 
    handler = Gmaps.build('Google'); 
    handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){ 
    markers = handler.addMarkers(<%=raw @hash.to_json %>); 
    handler.bounds.extendWith(markers); 
    handler.fitMapToBounds(); 
    handler.getMap().setZoom(10); 
    }); 
</script> 

現在工作完全正常。但在首次地圖視圖中,我的標記始終位於左上角。我希望它明顯地位於地圖的中間。

我試着將它添加此行的腳本,並沒有做任何事情:

handler.map.centerOn({ lat: markers[0].lat, lng: markers[0].lng }); 

我有什麼做的就是中間的標記?

編輯: 好的,感謝Zsolt,我發現加載地圖時,標籤的不活動導致了問題。我現在想要做的是在用戶點擊標籤後立即重新映射地圖。由於我的JavaScript非常糟糕,所以我需要一些幫助。這就是我直到現在:

$('#tab_location').on('shown.bs.tab', function (e) { 
    var myLatlng = {lat: gon.lat, lng: gon.lng}; 
    var map = document.getElementById('map'); 
    map.setCenter(myLatlng); 
}); 

正如你看到我使用得到正確的座標的JavaScript。追趕的座標運作良好,但其餘的將導致此錯誤:

TypeError: a is undefined 

一個是某種變量內的谷歌地圖腳本。

回答

0

我有非常類似的問題(左上角的標記集羣)。寶石的筆者建議:

"You should create the map after its div is made visible"

here

希望這可以幫助你,我與JS一個小白。如果你找出解決方案,請讓我知道!

+0

謝謝隊友!似乎是對的,但我的JavaScript是非常糟糕的。在主帖中張貼我的想法,但它還沒有工作! – Syk