0

我对 Rails 很陌生,不知道如何生成正确的 javascript 以在 gmaps4rails 中创建多边形。我能够显示带有标记的谷歌地图,但我迷失了如何生成匹配的 json 代码,如https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Polygons中所示。我想通过 rails 生成所有内容,而不是对任何 javascript 进行硬编码。

这是我的测试代码,用于仅绘制 location_data 模型中的第一个多边形。纬度和经度属性是序列化的。

控制器

class HomeController < ApplicationController
skip_load_and_authorize_resource
 skip_before_filter :authenticate_user!
def index

LocationData.find_each do |location|

@polygons = Array.new(LocationData.count,Array.new)

location.latitude.each_index do |index|
@polygons[0] << { :lat => location.latitude[index], :lng =>location.longitude[index]}
end


    end
#@polygons.to_json

respond_to do |format|
format.html
format.json { render json: @polygons }   

end
end
end

生成的 Javascript 看起来像

Gmaps.map = new Gmaps4RailsGoogle();
Gmaps.load_map = function() {
Gmaps.map.initialize();
Gmaps.map.polygons = [[{"lat"=>42.31276, "lng"=>-71.03645}, {"lat"=>42.35653, "lng"=>-71.06754}, {"lat"=>42.45453, "lng"=>-71.7856}]];
Gmaps.map.polygons_conf.fillColor = "#000";
Gmaps.map.create_polygons();
Gmaps.map.adjustMapToBounds();
Gmaps.map.callback();
};
Gmaps.oldOnload = window.onload;
 window.onload = function() { Gmaps.triggerOldOnload(); Gmaps.loadMaps(); };

看法

<%= gmaps({
       "polygons"    => { "data" => @polygons    , "options" => { "fillColor" => "#000" } }
     })
 %>

将它与 wiki 上的代码进行比较,我注意到由于某些奇怪的原因,javascript 中有 =>。

更新

我的代码中缺少一行

@polygons = @polygons.to_json
4

1 回答 1

0

我的控制器中缺少一行代码。

@polygons = @polygons.to_json
于 2013-04-08T18:02:33.540 回答