Rails:Gmaps4Rails&地理编码器 - 设置

时间:2015-10-16 09:48:03

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

试图弄清楚如何在我的rails 4 app show page中显示地图。

我有一个名为地址的模型。这是address.rb文件:

class Address < ActiveRecord::Base

  geocoded_by :full_address   # can also be an IP address
  before_save :capitalise_address
  before_save :upcase_zip


  # --------------- associations

  belongs_to :addressable, :polymorphic => true

  # --------------- scopes

  # --------------- validations

  validates_presence_of :unit, :street, :zip, :country 

  # --------------- class methods

  def first_line
    [unit, street].join(' ')
  end

  def middle_line
    if self.building.present? 
    end
  end

  def last_line
    [city, region, zip].join('   ')
  end

  def country_name
    self.country = ISO3166::Country[country]
    country.translations[I18n.locale.to_s] || country.name
  end

  def address_without_country
    [self.first_line, middle_line, last_line].compact.join(" ")
  end

  def full_address
    [self.first_line, middle_line, last_line, country_name.upcase].compact.join("\n")
  end


  # --------------- callbacks

  # after_validation :geocode, if  self.full_address.changed? 

  # --------------- instance methods

  # --------------- private methods

  protected

    def upcase_zip
      zip.upcase
    end

    def capitalise_address
      ["building", "street", "city", "region", "country" ].each do | name |
        self.attributes[name] = self.attributes[name].capitalize
      end
    end

end

我已将geocoded,gmap4rails,下划线gems添加到我的gem文件中。

在我的地址控制器中,我有:

class AddressesController < ApplicationController
  before_action :set_address, only: [:show, :edit, :update, :destroy]
  respond_to :html, :xml, :json

  def index
    @addresses = Address.all
    respond_with(@addresses)
  end



  def show
    respond_with(@address)
  end

  def new
    @address = Address.new
    respond_with(@address)
  end

  def edit
  end

  def create
    @address = Address.new(address_params)
    @address.save
    respond_with(@address)
  end

  def update
    @address.update(address_params)
    respond_with(@address)
  end

  def destroy
    @address.destroy
    respond_with(@address)
  end

  private
    def set_address
      @address = Address.find(params[:id])
    end

    def address_params
      params[:address].permit(:unit, :building, :street, :city, :region, :zip, :country)

    end
end

在我的地址显示页面中,我有:

<script src="//maps.google.com/maps/api/js?v=3.13&sensor=false&libraries=geometry" type="text/javascript"></script>
<script src="//google-maps-utility-library-v3.googlecode.com/svn/tags/markerclustererplus/2.0.14/src/markerclusterer_packed.js" type="text/javascript"></script>

<div class="containerfluid">
    <div class="row">
        <div class="col-md-12">

                <div style='width: 800px;'>
                     <div id="map" style='width: 800px; height: 400px;'>

                     </div>
                </div>
                <div class="addressbacking"> 
                    <%=  @address.full_address %>
                    <div style='width: 800px;'>
  <div id="one_marker" style='width: 800px; height: 400px; z-index:1'></div>
</div>
                </div>
            </div>
        </div>
    </div>
</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();
    });
</script>

我正在尝试按照此设置教程,建议将此添加到我的控制器:

  def index
    @users = User.all
    @hash = Gmaps4rails.build_markers(@users) do |user, marker|
      marker.lat user.latitude
      marker.lng user.longitude
      marker.title user.title
    end
  end

我做了什么(虽然我不知道它的含义或是否是我的问题的原因),所以我在控制器中的索引操作是:

  def index
    @addresses = Address.all
    respond_with(@addresses)
    @hash = Gmaps4rails.build_markers(@users) do |user, marker|
      marker.lat user.latitude
      marker.lng user.longitude
      marker.title user.title
    end

  end

我的视图中有一个部分表单,其中包含显示在控制器底部的每个强参数的输入元素。

当我尝试这个时,地图呈现,但它不是我在表单中输入的地址。

我该如何解决这个问题?我的地址表中没有经度和纬度属性。

2 个答案:

答案 0 :(得分:0)

您对地址进行了地理编码,因此它具有纬度和经度方法。用户类是否也进行了地理编码?

def index
  @addresses = Address.all
  @hash = Gmaps4rails.build_markers(@addresses) do |address, marker|
    marker.lat address.latitude
    marker.lng address.longitude
  end
end

请务必在地址中添加参数:

class AddLatitudeAndLongitudeToAddress < ActiveRecord::Migration
  def change
    add_column :addresses, :latitude, :float
    add_column :addresses, :longitude, :float
  end
end

答案 1 :(得分:0)

让我们检查 app / assets / javascripts / addresses.coffee 例如:

class RichMarkerBuilder extends Gmaps.Google.Builders.Marker
  create_marker: ->
    options = _.extend @marker_options(), @rich_marker_options()
    @serviceObject = new RichMarker options 
  rich_marker_options: ->
    marker = document.createElement("div")
    marker.setAttribute 'class', 'marker_container'
    marker.innerHTML = @args.marker
    { content: marker }

handler = Gmaps.build 'Google', { builders: { Marker: RichMarkerBuilder} } 
handler.buildMap { provider: {}, internal: {id: 'map'} }, ->
  markers = handler.addMarkers([
    {"lat": 0, "lng": 0, 'marker': '<span>Here!</span>'}
  ])
handler.bounds.extendWith(markers)
handler.fitMapToBounds()

在您的模型中添加

 geocoded_by :full_address
 after_validation :geocode