2014-09-28 31 views
1

我想在一張地圖上顯示房子和城市/景點。在一張地圖上乘以模型?

我的控制器:

@house = House.friendly.find(params[:id]) 
    @city = City.find(1) 
    @location = @house.location 
    @location1 = @city.location 

    records = @location || @location1 

@hash = Gmaps4rails.build_markers(records) do |location, marker| 
     marker.lat location.latitude 
     marker.lng location.longitude 

    end 

查看

<header> 
    <h3 class='text'> 
    <%= t('navigation.sub_nav.location') %> 
    </h3> 
<div id="map" style='width: 100%; height: 400px; margin-top: 10px;' ></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(7); 
    }); 
</script> 

我只顯示在地圖上,而不是城市的房子。我在這裏做錯了什麼?

+0

您可能需要'records = @location + @ location1' – Santhosh 2014-09-28 07:41:42

回答

2

||裝置,所以records = @location || @location1手段分配@locationrecords,除非它是零,在這種情況下,分配給@location1records

因爲它看起來既可以是零,我會建議更換與該行:

records = [@location, @location1].compact,這將賦予他們兩人,並移除任何零值。現在,Gmaps4rails.build_markers(records)將爲records接收一個合適的數組。

你可以添加一些額外的檢查,如果你期望他們都可以是空白的(在這種情況下你會有一個空的數組)。

而且,取決於你的觀點其餘的樣子,@house@city@location,並@location1可能有過多的範圍,大概可以改成housecitylocationlocation1如果他們只使用控制器。

+0

謝謝!有用! – Remco 2014-09-28 09:37:16

+0

brad ...它在我收到1條記錄時有效...但是當@ location1有多個記錄(景點)時,我得到一個無方法錯誤...你知道嗎? – Remco 2014-09-29 13:40:42

+0

@Remco很難說沒有看到更多的代碼。這可能會更好一個新的問題,但我會考慮嘗試'[@location,@ location1] .flatten.compact'。 – 2014-09-29 16:05:38