Skip to content

Instantly share code, notes, and snippets.

@cigalecigales
Created February 22, 2015 05:44
Show Gist options
  • Save cigalecigales/4966ae21673b668ec987 to your computer and use it in GitHub Desktop.
Save cigalecigales/4966ae21673b668ec987 to your computer and use it in GitHub Desktop.
[*Rails*] 指定座標のGoogleMapを表示させたい ref: http://qiita.com/cigalecigales/items/bfdaa07a7fa29a4175cb
(省略)...
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require underscore
//= require gmaps/google
//= require_tree .
class Cicada < ActiveRecord::Base
reverse_geocoded_by :latitude, :longitude
after_validation :geocode
end
$ bundle install
$ rails c
irb(main):001:0> Cicada.create(title: "abura", address: "kobe station")
=> #<Cicada id: 13, title: "abura", description: nil, address: "kobe station", latitude: 34.679526, longitude: 135.178021, created_at: "2015-02-22 05:11:26", updated_at: "2015-02-22 05:11:26">
irb(main):001:0> Cicada.create(title: "abura", address: "tokyo station", latitude:10, longitude:140)
=> #<Cicada id: 15, title: "abura", description: nil, address: "tokyo station", latitude: 35.681382, longitude: 139.766084, created_at: "2015-02-22 05:14:58", updated_at: "2015-02-22 05:14:58">
irb(main):001:0> Cicada.create(title: "abura", address: "tokyo station", latitude:36.091521, longitude:139.372694)
=> #<Cicada id: 17, title: "abura", description: nil, address: "tokyo station", latitude: 36.091521, longitude: 139.372694, created_at: "2015-02-22 05:23:54", updated_at: "2015-02-22 05:23:54">
$ rails g model Cicada title:string description:string address:string latitude:float longitude:float
$ rake db:migrate
$ rails g controller map index
(省略)...
# Google map
gem 'gmaps4rails'
48 gem 'geocoder'
<script src="//maps.google.com/maps/api/js?v=3.13&amp;sensor=false&amp;libraries=geometry" type="text/javascript"></script>
<script src='//google-maps-utility-library-v3.googlecode.com/svn/tags/markerclustererplus/2.0.14/src/markerclusterer_packed.js' type='text/javascript'></script>
<div style='width: 800px;'>
<div id="map" style='width: 800px; height: 400px;'></div>
</div>
<script type="text/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();
});
</script>
class MapController < ApplicationController
def index
@cicadas = Cicada.all
@hash = Gmaps4rails.build_markers(@cicadas) do |cicada, marker|
marker.lat cicada.latitude
marker.lng cicada.longitude
marker.infowindow cicada.description
marker.json({ title: cicada.title })
end
end
end
Rails.application.routes.draw do
root 'map#index'
(省略)...
end
//(underscore.jsまたはunderscore-min.jsの中身を貼り付ける。)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment