Search code examples
ruby-on-rails-3google-maps-api-3gmaps4rails

Gmaps4Rails and Custom/Nested Points Model


I have been using gmaps4 rails to build out a site and the gem is a super addition to my project. I am having some trouble however, with nested models and polygons.

I too would like to do something like this: Gmaps4rails custom info window with javascript content

Models:

  class Zone < ActiveRecord::Base
    acts_as_gmappable

    has_many :points, :as => :pointable
    accepts_nested_attributes_for :points

    def self.create_with_points(name, points)
      zone = Zone.create(:name => name)
      points.map { |point| zone.points.create(:latitude => point[0],
                                              :longitude => point[1]) }
      zone
    end

    def as_polygon_data
      points.collect { |point| { "lat" => point.latitude.to_f,
                                 "lng" => point.longitude.to_f,
                                 "strokeColor" => "#EBAC2A",
                                 "strokeOpacity" => 0.65,
                                 "strokeWeight" => 2,
                                 "fillColor" => "#606F81",
                                 "fillOpacity" => 0.4
                               } }
    end

    def self.all_as_polygon_data
      Zone.all.collect { |zone| zone.as_polygon_data }
    end
  end

  class Point < ActiveRecord::Base
    belongs_to :pointable, :polymorphic => :true
    acts_as_gmappable
  end

To invoke the Zone in the controller I have to call it with to_json instead of to_gmaps4rails:

@polygon_json = Zone.all_as_polygon_data.to_json

The polygons render on the map perfectly, but I can't add an info window to them. I tried the click event callback in the above-mentioned post, but it did not work for me.

I would also like to know how I can get a handle to these polygons so I can hide them using a checkbox.

Thank you for your time. Hopefully I have provided enough information.


Solution

  • but it did not work for me is not a very useful statement.

    I can't know what's your problem: do you have any js error?

    You can use the whole google js api, the gem is not a brake, it's just a wrapper.

    If you want to interact with polygons:

    • the data you pass in the view are stored in the array of objects: Gmaps.map.polygons

    • on page load, the google's polygons are created and are stored in an object I call serviceObject.

    To sum up, Gmaps.map.polygons[0].serviceObject is a google polygon object you can interact with freely.

    To be sure the google's object are created, insert your custom methods in the gmaps4rails js callback.