【问题标题】:Populating data onto Google Map with rails使用 rails 将数据填充到 Google Map 上
【发布时间】:2016-12-21 06:08:03
【问题描述】:

我有一个使用 Google Maps API 查找您所在地区的接送游戏的 rails 应用程序。您可以使用 Places 库创建游戏并设置您想玩的地方(我有一点)。但是,现在我正在努力做到这一点,以便当您单击一个按钮时,它会获取人们创建的那些位置并将它们填充到地图上。

我有一个带有地址列的游戏模型,我正在尝试获取该地址信息并在用户按下按钮时让它在地图上弹出。

有人对我如何做到这一点有提示吗?谢谢

【问题讨论】:

    标签: javascript ruby-on-rails google-maps google-maps-markers


    【解决方案1】:

    我会借助两颗宝石来解决这个问题:

    gem 'geocoder'
    gem 'gmaps4rails'
    

    虽然您当然可以绘制地址,但我喜欢使用“after_save”方法将它们转换为经纬度坐标(您必须在游戏模型中添加两​​列)。

    class Game < ActiveRecord::Base
    
      after_save :cache_coordinates
    
      def cache_coordinates
        loc = Geocoder.coordinates(address)
        return if loc.nil?
        update_column(:latitude,  loc[0])
        update_column(:longitude, loc[1])
      end
    end
    

    确保遵循此处列出的说明以使 Gmaps 正常工作: Google-Maps-for-Rails

    您的地图控制器可能看起来像这样(不要忘记添加到路线...)

    class MapsController < ApplicationController
      respond_to :html, :js
    
      def index
        @geolocations = Game.all
        @hash = Gmaps4rails.build_markers(@geolocations) do |geolocation, marker|
          marker.lat geolocation.latitude
          marker.lng geolocation.longitude
        end
      end
    end
    

    一个简单的视图应该是这样的:

    // use your API key here...
    <%= javascript_include_tag "//maps.google.com/maps/api/js?v=3.23&amp;sensor=false&amp;libraries=geometry&key=YOURKEY" %>
    <%= javascript_include_tag "//cdn.rawgit.com/mahnunchik/markerclustererplus/master/dist/markerclusterer.min.js" %>
    <script>
        var mapStyle = [];
        var mapOptions = {};
        var handler = Gmaps.build('Google',
                {markers:
                {clusterer: {
                    gridSize: 20,
                    maxZoom: 13
                }}});
        handler.buildMap({
            internal: {id: 'multi_markers'},
            provider: {
                scrollwheel: true,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
    
        }, function(){
            var markers = handler.addMarkers(<%=raw @hash.to_json %>);
            // some options you may or may not want to use
            handler.map.centerOn([40.397, -95.644]);
            handler.fitMapToBounds();
            handler.getMap().setZoom(4)
        });
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 2020-01-17
      • 2013-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多