railsでgooglemapを表示
Gemfileに以下を追加して、bundle install
gem 'gmaps4rails' gem 'geocoder'
application.html.slimのhead内に以下を記述
script src="//maps.google.com/maps/api/js?v=3.23&key=[API_KEY]"
script src="//cdn.rawgit.com/mahnunchik/markerclustererplus/master/dist/markerclusterer.min.js"
script src='//cdn.rawgit.com/printercu/google-maps-utility-library-v3-read-only/master/infobox/src/infobox_packed.js' type='text/javascript'
[API_KEY]には、Google Maps APIのキーを取得して入れてください
以下urlより
Get API Key | Google Maps JavaScript API | Google Developers
application.jsに以下を追加
//= require gmaps/google //= require underscore
underscore.jsはこちらからコピーし
http://underscorejs.org/underscore-min.js
app/assets/javascript/underscore.jsに記述
googlemapを表示したいview側に以下を追加
#map style="width: 800px; height: 400px;"
javascript: handler = Gmaps.build('Google'); handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){ markers = handler.addMarkers(#{raw @hash.to_json}); handler.bounds.extendWith(markers); handler.fitMapToBounds(); });
controller側に以下を記述
@places = Place.all address = 住所 lati_long = Geocoder.coordinates(address) @hash = Gmaps4rails.build_markers(@places) do |place, marker| marker.lat lati_long[0] marker.lng lati_long[1] end
Geocoder.coordinates(address)のaddress部分に住所を入れると
緯度と経度を取得してくれます。