0

GoogleマップAPIを使用して自分のエリアでゲームを見つけるレールアプリがあります。プレイスを使用してゲームを作成し、プレイしたい場所を設定することができます(私はそのビットを持っています)。しかし、今、ボタンをクリックすると、人々が作成した場所がマップ上に表示されるようにしています。Googleマップにデータを入力する

私はアドレス欄を持つゲームモデルを持っています。私はそのアドレス情報を取って、ユーザーがボタンを押すと地図上にポップアップ表示しようとしています。

どのようにすればいいですか?おかげ

答えて

1

私は2つの宝石の助けを借りてこれをアプローチします:あなたは確かにアドレスをプロットすることができますが

gem 'geocoder' 
gem 'gmaps4rails' 

が、私は「after_save」メソッドで長いと緯度の座標にそれらを変換したい(あなたが持っているでしょうゲームモデルに2つの列を追加する)。

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> 
関連する問題