少於 1 分鐘閱讀

本文使用 Ruby 2.3.1 / Rails 5.0.0

前言

此專案簡易介紹google map座標及網頁顯示的產生。主要功能如下:

  1. 可以只打地址(address欄位),存檔時會自動產生經緯度
  2. 清單上的地址,分別以marker列在地圖上
  3. 點選marker可以顯示地址

相關gem

步驟

1)把gem全部加入並bundle

gem 'bootstrap-generators', '~> 3.3.4'
gem 'gmaps4rails'
gem 'geocoder'

2)安裝bootstrap-generators(需要再重開rails s或執行spring stop,頁面才會生效)

rails generate bootstrap:install

3)建立一個名為gmap的scaffold,並去route把首頁指過去

rails g scaffold gmap latitude:float longitude:float address
root 'gmap#index'

4)安裝Google-Maps-for-Rails

gmap (注意[your API key]要到google api申請一組map用的並填上自己的API key)

<!-- [path] application.html.erb -->
<script src="//maps.google.com/maps/api/js?v=3.23&key=[your API key]"></script>
<script src="//cdn.rawgit.com/mahnunchik/markerclustererplus/master/dist/markerclusterer.min.js"></script>
<script src='//cdn.rawgit.com/printercu/google-maps-utility-library-v3-read-only/master/infobox/src/infobox_packed.js' type='text/javascript'></script> <!-- only if you need custom infoboxes -->

須使用 undersore.js (可至http://underscorejs.org/ 下載) 把undersore-min放在 vendor/assets/javascripts/underscore-min.js

javascript

// [path] application.js
//= require underscore
//= require gmaps/google

在要顯示的網頁最下方加入

<!-- [path] /app/views/gmaps/index.html.erb -->
<div id="map" style="width:100%;height:400px">地圖預留</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>

5)安裝geocoder

# [path] gmap.rb
geocoded_by :address        #從address欄位取出地址
after_validation :geocode   #將取出的地址自動轉為經緯度分別存在 latitude、longitude 欄位

6)設定產生的json

# [path] gmaps_controller.rb
def index
   @gmaps = Gmap.all
   @hash = Gmaps4rails.build_markers(@gmaps) do |gmap, marker|
     marker.lat gmap.latitude
     marker.lng gmap.longitude
     marker.infowindow gmap.address
  end
end

7)打完收工,成品如下

螢幕快照 2016-07-17 下午4.30.20.png

參考

  1. https://www.youtube.com/watch?v=oi3yxYs8Y4Q
  2. Google MAP API
  3. Gmap4rails

更新時間:

留言