在一张地图中乘以模型?

时间:2014-09-28 07:11:46

标签: ruby-on-rails ruby-on-rails-4 gmaps4rails

我想在一张地图上展示一所房子和一个城市/景点。

我的控制员:

@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>

我只显示地图中的房子而不是城市。我在这做错了什么?

1 个答案:

答案 0 :(得分:2)

||表示,因此records = @location || @location1表示将@location分配给records,除非它为零,在这种情况下指定{{1}转到@location1

由于看起来两者都可以为零,我建议用以下代码替换该行:

records,将两者分配,并删除任何nil值。现在,records = [@location, @location1].compact将收到Gmaps4rails.build_markers(records)的正确数组。

您可以添加一些额外的检查,如果您希望它们都可以为空(在这种情况下,您将有一个空数组)。

另外,根据视图的其余部分,records@house@city@location的范围可能过大,并且可能会更改如果仅在控制器中使用,则@location1housecitylocation