2014-09-28 84 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