Ruby on Railsでleaflet-routing-machineを使う
Railsでleafleのプラグインleaflet-routing-machineを動かす。
まずはデモ
http://workshops.ddns.net/routes/new
環境
Rails: 4.1.8
ruby: 2.1.5p273 (2014-11-13 revision 48405) [x86_64-linux]
leaflet: v0.7.7
ソース
まずはrails
maps/show.html.erb
<%= stylesheet_link_tag 'leaflet/leaflet' %> <%= stylesheet_link_tag 'leaflet-routing-machine/leaflet-routing-machine' %> <div id="map" class="map"> </div> <%= javascript_include_tag 'leaflet/leaflet' %> <%= javascript_include_tag 'leaflet-routing-machine/leaflet-routing-machine' %> <%= javascript_include_tag 'leaflet-routing-machine/Control.Geocoder' %>
読み込んでいるcssとjsはleafletとleaflet-routing-plugin 以下からダウンロードできる。
leaflet http://leafletjs.com/
leaflet-routing-machine http://www.liedman.net/leaflet-routing-machine/
次にCSS 地図とルーティングの表示領域を定義
.map { height: 500px; width:100%; } .results { background-color: white; opacity: 0.8; position: absolute; top: 12px; right: 12px; width: 320px; height: 480px; overflow-y: scroll; }
最後にjavascript
leaflet-routing-pluginで表示されるピン画像がデフォルトではうまく表示されないため 設定を変更する必要がある。
以下の例では、public/images/leaflet以下にピン画像がある場合を記載している。
var map = L.map('map'); L.Icon.Default.imagePath = (function () { var scripts = document.getElementsByTagName('script'), leafletRe = /[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/; var i, len, src, matches, path; for (i = 0, len = scripts.length; i < len; i++) { src = scripts[i].src; matches = src.match(leafletRe); if (matches) { path = src.split(leafletRe)[0]; return '/' + 'images/leaflet'; /* ピン画像へのパス */ } } }()); //ここからはチュートリアル通り L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); var control = L.Routing.control({ createMarker: function(i, wp) { var options = { draggable: this.draggableWaypoints }, marker = L.marker(wp.latLng, options); return marker; }, waypoints: [ L.latLng(35.46222222, 139.62444444), L.latLng(35.681298, 139.766247) ], geocoder: L.Control.Geocoder.nominatim(), routeWhileDragging: true, reverseWaypoints: true, showAlternatives: true, altLineOptions: { styles: [ {color: 'black', opacity: 0.15, weight: 9}, {color: 'white', opacity: 0.8, weight: 6}, {color: 'blue', opacity: 0.5, weight: 2} ] } }).addTo(map); L.Routing.errorControl(control).addTo(map);
以上