Search code examples
ruby-on-railsruby-on-rails-4gmaps4rails

Multiply models in one map?


I want to show a house and a city/sights in one map.

my controller:

@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

View

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

i shows only the house in the map and not the city. What am i doing wrong here?


Solution

  • || means or , so records = @location || @location1 means assign @location to records, unless it is nil, in which case assign @location1 to records.

    As it appears that either can be nil, I would recommend replacing that line with:

    records = [@location, @location1].compact, which will assign them both, and remove any nil values. Now, Gmaps4rails.build_markers(records) will recieve a proper array for records.

    You could add some additional checking, if you expect they could ever both be blank (in which case you would have an empty array).

    Also, depending on what the rest of your view looks like, @house, @city, @location, and @location1 may have excessive scope, and can probably be changed to house, city, location, and location1 if they are only used in the controller.