从地理编码器输入附近的轨道模型信息到gmaps4rails

时间:2014-02-25 15:43:01

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

我正在使用较新的gmaps4rails,我似乎无法弄清楚如何让附近的商店位于gmaps4rails中。在展会页面中,我有我附近的商店代码。

我在.js代码上放置了信息,我相信rails代码应该是,但它无法正常工作。我尝试了<%= storeuser.latitude %><%= storeuser.longitude %>,但这些都无效。我宁愿它映射我的所有商店,并允许我专注于gmaps上特定半径内的近处。

我的代码如下:

显示页面

<body onload = 'getLocation()'>

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

    <div class= "test"></div>
    <h3>Nearby locations</h3>
    <ul id="nearby_locations">
        <% @nearby_stores.each do |storeuser| %>
        <li><%= link_to storeuser.storename, profile_path(storeuser) %>(<%= storeuser.distance.round(2) %> miles) </li>
        <% end %>
    </ul>
</body>

的application.js

var x = document.getElementById("map");
        function getLocation()
        {
            if (navigator.geolocation)
            {
                navigator.geolocation.getCurrentPosition(showPosition);
            }
            else{x.innerHTML = "Geolocation is not supported by this browser.";}
        }
        function showPosition(position)
        {
            function createSidebarLi(json){
              return ("<li><a>" + json.name + "</a></li>");
            };

            function bindLiToMarker($li, marker){
              $li.on('click', function(){
                handler.getMap().setZoom(14);
                marker.setMap(handler.getMap()); //because clusterer removes map property from marker
                marker.panTo();
                google.maps.event.trigger(marker.getServiceObject(), 'click');
              })
            };

            function createSidebar(json_array){
              _.each(json_array, function(json){
                var $li = $( createSidebarLi(json) );
                $li.appendTo('#sidebar_container');
                bindLiToMarker($li, json.marker);
              });
            };

            handler = Gmaps.build('Google', { markers: { maxRandomDistance: null } });
            handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
                var json_array = [
                    {
                        "lat": position.coords.latitude,
                        "lng": position.coords.longitude,
                        "name": 'You!',
                        "picture": {
                            "url": "https://addons.cdn.mozilla.net/img/uploads/addon_icons/13/13028-64.png",
                            "width":  36,
                            "height": 36
                        },
                        "infowindow": "You!"
                    },
                    {
                        "lat": Do I put rails code here and how should it look?,
                        "lng": "",
                        "name": 'Store!',
                        "picture": {
                            "url": "https://addons.cdn.mozilla.net/img/uploads/addon_icons/13/13028-64.png",
                            "width":  36,
                            "height": 36
                        },
                        "infowindow": "You!"
                    }
                ];

                var markers = handler.addMarkers(json_array);

                _.each(json_array, function(json, index){
                    json.marker = markers[index];
                });
                createSidebar(json_array);
                handler.bounds.extendWith(markers);
                handler.fitMapToBounds();
            });
            var lat = position.coords.latitude
            var lon = position.coords.longitude
            var parsed_data = {location: {lat: lat, lon: lon}}
            if (!window.location.search) {
                window.location = ('/findme?lat=' + lat + '&lon=' + lon);    
            }

        }

展示页面的位置控制器

def show2
    @nearby_stores = (params[:lat].present? && params[:lon].present?) ? Storeuser.near([params[:lat], params[:lon]], 50) : []
    respond_to do |format|
      format.html
    end
  end 

Storeuser模型

class Storeuser < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_attached_file :avatar, :styles => { :small => "200x200", :semismall => "250x250", :medium => "300x300>", :large => "400x400", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
  validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/


  def full_address
    [address, city, state, zipcode].compact.join(', ')
  end

  geocoded_by :full_address
  after_validation :geocode



end

* 迁移表(虽然我不确定这有何帮助)

class DeviseCreateStoreusers < ActiveRecord::Migration
  def change
    create_table(:storeusers) do |t|
      ## Database authenticatable
      t.string :email,              :null => false, :default => ""
      t.string :encrypted_password, :null => false, :default => ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, :default => 0, :null => false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, :default => 0, :null => false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at

      t.string :username
      t.string :ownerfirstname
      t.string :ownerlastname
      t.string :address
      t.string :city
      t.string :state
      t.string :zipcode
      t.string :storename

      t.timestamps
    end

    add_index :storeusers, :email,                :unique => true
    add_index :storeusers, :reset_password_token, :unique => true
    # add_index :storeusers, :confirmation_token,   :unique => true
    # add_index :storeusers, :unlock_token,         :unique => true
  end
end

现在我得到了“未定义的局部变量或方法`gon'for#”我放置了

位置控制器:     @nearby_stores =(params [:lat] .present?&amp;&amp; params [:lon] .present?)? Storeuser.near([params [:lat],params [:lon]],50):[]         respond_to do | format |           format.html         结束         gon.nearby_stores_lat = @ nearby_stores.latitude         gon.nearby_stores_lon = @ nearby_stores.longitude         gon.nearby_stores_name = @ nearby_stores.truckname

更新了application.js

var x = document.getElementById("map");
        function getLocation()
        {
            if (navigator.geolocation)
            {
                navigator.geolocation.getCurrentPosition(showPosition);
            }
            else{x.innerHTML = "Geolocation is not supported by this browser.";}
        }
        function showPosition(position)
        {
            function createSidebarLi(json){
              return ("<li><a>" + json.name + "</a></li>");
            };

            function bindLiToMarker($li, marker){
              $li.on('click', function(){
                handler.getMap().setZoom(14);
                marker.setMap(handler.getMap()); //because clusterer removes map property from marker
                marker.panTo();
                google.maps.event.trigger(marker.getServiceObject(), 'click');
              })
            };

            function createSidebar(json_array){
              _.each(json_array, function(json){
                var $li = $( createSidebarLi(json) );
                $li.appendTo('#sidebar_container');
                bindLiToMarker($li, json.marker);
              });
            };

            handler = Gmaps.build('Google', { markers: { maxRandomDistance: null } });
            handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
                var json_array = [
                    {
                        "lat": position.coords.latitude,
                        "lng": position.coords.longitude,
                        "name": 'You!',
                        "picture": {
                            "url": "https://addons.cdn.mozilla.net/img/uploads/addon_icons/13/13028-64.png",
                            "width":  36,
                            "height": 36
                        },
                        "infowindow": "You!"
                    },
                    {
                        "lat": gon.nearby_trucks_lat,
                        "lng": gon.nearby_trucks_lon,
                        "name": gon.nearby_trucks_name,
                        "picture": {
                            "url": "https://addons.cdn.mozilla.net/img/uploads/addon_icons/13/13028-64.png",
                            "width":  36,
                            "height": 36
                        },
                        "infowindow": gon.nearby_trucks_name
                    }
                ];

                var markers = handler.addMarkers(json_array);

                _.each(json_array, function(json, index){
                    json.marker = markers[index];
                });
                createSidebar(json_array);
                handler.bounds.extendWith(markers);
                handler.fitMapToBounds();
            });
            var lat = position.coords.latitude
            var lon = position.coords.longitude
            var parsed_data = {location: {lat: lat, lon: lon}}
            if (!window.location.search) {
                window.location = ('/findme?lat=' + lat + '&lon=' + lon);    
            }

        }

0 个答案:

没有答案