Хорошо, терпите меня ... Я немного новичок.
Я могу выполнить поиск в своей базе данных и отобразить результаты на карте Google, используя Graps 4rails, но не могу добавить в «информационное окно». Поэтому я решил использовать другой метод поиска, где я могу отобразить файл, но он отображает гораздо больше, чем просто то, что я ищу. По сути, мне нужно выполнить поиск в моей базе данных и автоматически отобразить результаты в Картах Google, а затем поместить данные этих объектов в маркер информационного окна.
MY Первый метод поиска в моем файле Search.html.erb, который работает с графиками, но я не могу передать данные в информационное окно из-за ошибок json, я полагаю.
<div class="container page-content">
<div class="row">
<div class="span12">
<div class="row">
<% if @businesses.blank? %>
<h3>Couldn't find a business with your search criteria</h3>
<% else %>
<% @businesses.each do |business| %>
<div class="mapx">
<div id="map" style='width: 350px; height: 250px;'></div>
</div>
<script type="text/javascript">
handler = Gmaps.build('Google');
handler.buildMap({ provider: { Zoom: 12}, internal: {id: 'map'}}, function(){
markers = handler.addMarkers([
{
"lat": <%= business.latitude %>,
"lng": <%= business.longitude %>,
"picture": {
"width": 32,
"height": 32
},
"infowindow": "SUJU"
}
]);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
handler.getMap().setZoom(19);
});
</script>
<div class="span4 box-container">
<div class="holder">
<a class="overlay" href="#" title="property title">
<span class="more"></span>
<% if business.image_url.present? %>
<%= link_to image_tag(business.image_url.to_s), business %>
<% else %>
<%= link_to image_tag("http://placehold.it/300x190"), business %>
<% end %>
</a>
<span class="prop-tag">For Sale</span>
<div class="prop-info">
<h3 class="prop-title"><%= link_to business.name, business %></h3>
<ul class="more-info clearfix">
<li class="info-label clearfix"><span class="pull-left">Phone:</span>
<span class="qty pull-right"><%= business.phone %></span></li>
<li class="info-label clearfix"><span class="pull-left">Location:</span>
<span class="qty pull-right"><%= business.city.capitalize %>, <%= business.state.upcase %></span></li>
</ul>
</div>
</div>
</div>
<% end %>
<% end %>
</div>
</div>
</div>
</div>
My second method for the search .html .erb file, where I can pass the info window, but it plots more then my search results, so If I search for four items it will plot 30 since that is my limit for will_paginate.
<div class="container page-content">
<div class="row">
<div class="span12">
<div class="row">
<% if @businesses.blank? %>
<h3>Couldn't find a business with your search criteria</h3>
<% else %>
<% @businesses.each do |business| %>
<div class="mapx">
<div id="map" style='width: 350px; height: 250px;'></div>
</div>
<script type="text/javascript">
handler = Gmaps.build('Google');
handler.buildMap({ provider: { Zoom: 12 }, internal: {id: 'map'}}, function(){
markers = handler.addMarkers(<%=raw @businessz_default.to_json %>);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
handler.getMap().setZoom(18);
}); </script>
<div class="span4 box-container">
<div class="holder">
<a class="overlay" href="#" title="property title">
<span class="more"></span>
<% if business.image_url.present? %>
<%= link_to image_tag(business.image_url.to_s), business %>
<% else %>
<%= link_to image_tag("http://placehold.it/300x190"), business %>
<% end %>
</a>
<span class="prop-tag">For Sale</span>
<div class="prop-info">
<h3 class="prop-title"><%= link_to business.name, business %></h3>
<ul class="more-info clearfix">
<li class="info-label clearfix"><span class="pull-left">Phone:</span>
<span class="qty pull-right"><%= business.phone %></span></li>
<li class="info-label clearfix"><span class="pull-left">Location:</span>
<span class="qty pull-right"><%= business.city.capitalize %>, <%= business.state.upcase %></span></li>
</ul>
</div>
</div>
</div>
<% end %>
<% end %>
</div>
</div>
</div>
</div>
Вот мой контроллер:
class BusinessesController < ApplicationController
before_action :logged_in_user, only: [:index, :edit, :update, :destroy]
before_action :set_business, only: [:show, :edit, :update, :destroy]
def index
load_businesses
@businesses = Business.paginate(page: params[:page])
respond_to do |format|
format.html
format.csv { send_data @businesses.to_csv(['name', 'city', 'state', 'zipcode', 'address1', 'address2', 'category1_id', 'category2_id', 'category3_id', 'category1', 'category2', 'category3', 'phone', 'website', 'latitude', 'longitude']) }
end
# if params[:search]
# @businesses = Business.search(params[:search]).order("created_at DESC")
# else
# @businesses = Business.all.order("created_at DESC")
#end
end
def import
Business.import(params[:file])
redirect_to root_url, notice: "Businesses imported."
end
def new
@business = Business.new
#@experience = Experience.new
end
def create
@business = Business.new(business_params)
#if @business.save
# flash[:success] = "Business saved!"
#redirect_to @business
# else
# flash[:alert] = "Business not saved!"
# render 'new'
#end
respond_to do |format|
if @business.save
format.html { redirect_to @business, notice: 'Business was successfully created.' }
format.json { render :show, status: :created, location: @business }
else
format.html { render :new }
format.json { render json: @business.errors, status: :unprocessable_entity }
end
end
end
def show
load_businessz
@businessz = Business.paginate(page: params[:page])
#redirect_to root_url and return unless @user.activated?
@experiences = Experience.where(business_id: @business)
@reviews = Review.where(business_id: @business)
#@experiences = @user.experiences.paginate(page: params[:page])
#@reviews = @user.reviews.paginate(page: params[:page])
end
def search
#@businessz = Business.search(params)
@businesses = Business.search(params)
load_businessz
end
def load_businesses
@businesses_default = Gmaps4rails.build_markers(Business.paginate(page: params[:page])) do |plot, marker|
marker.lat plot.latitude
marker.lng plot.longitude
@status = rand(1..4)
@battery = rand(10..90)
@ip = "192.168."+rand(0..255).to_s+"."+rand(15..250).to_s
@connected = rand(50..100)
if @status == 1
url_alert = "/assets/good.png"
@status == "Normal"
else
url_alert = "/assets/alert.png"
end
marker.picture({:picture => "http://mapicons.nicolasmollet.com/ wp-content/uploads/mapicons/shape-default/color-3875d7/shapeco lor-color/shadow-1/border-dark/symbolstyle-contrast/symbolshad owstyle-dark/gradient-iphone/information.png",
:width => 32,
:height => 32})
marker.infowindow render_to_string(:partial => "/businesses/info",
:locals => {:name => plot.name, :battery => @battery, :date => rand(6.months.ago..Time.now), :ip => @ip, :connected => @connected, :address1 => plot.address1, :city => plot.city })
end
end
def load_businessz
@businessz_default = Gmaps4rails.build_markers(Business.paginate(page: params[:page])) do |plot, marker|
marker.lat plot.latitude
marker.lng plot.longitude
@status = rand(1..4)
@battery = rand(10..90)
@ip = "192.168."+rand(0..255).to_s+"."+rand(15..250).to_s
@connected = rand(50..100)
if @status == 1
url_alert = "/assets/good.png"
@status == "Normal"
else
url_alert = "/assets/alert.png"
end
marker.picture({:picture => "http://mapicons.nicolasmollet.com/ wp-content/uploads/mapicons/shape-default/color-3875d7/shapeco lor-color/shadow-1/border-dark/symbolstyle-contrast/symbolshad owstyle-dark/gradient-iphone/information.png",
:width => 32,
:height => 32})
marker.infowindow render_to_string(:partial => "/businesses/infoz",
:locals => {:name => plot.name, :battery => @battery, :date => rand(6.months.ago..Time.now), :ip => @ip, :connected => @connected, :city => plot.city })
end
end
private
def set_business
@business = Business.find(params[:id])
end
def mapping_params
params.require(:business).permit(:name, :full_address, :address1, :city, :state, :zipcode, :latitude, :longitude)
end
def business_params
params.require(:business).permit(:name, :city, :state, :zipcode, :address1, :address2, :category1_id, :category2_id, :category3_id, :category1, :category2, :category3, :phone, :website, :latitude, :longitude)
end
# added correct user admin user for business 4 29 18
def correct_user
@user = User.find(params[:id])
redirect_to(root_url) unless current_user?(@user)
end
# Confirms an admin user.
def admin_user
redirect_to(root_url) unless current_user.admin?
end
#def logged_in_user
# unless logged_in?
# store_location
# flash[:danger] = "Please log in."
# redirect_to login_url
# end
#end
end
Вот мой контроллер поиска:
class SearchController < ApplicationController
def search
if params[:term].nil?
@businesses = []
else
@businesses = Article.search params[:term]
end
end
end
Страница моего бизнеса infoz для окна маркера, которое работает во втором примере:
<b>Name:</b> <%= name %><br>
<b>City:</b> <%= city %><br>
Есть ли способ просто передать некоторые данные в это информационное окно, к сожалению, я перепробовал все, но могу передавать только строки. Спасибо.