leaflet-realtimeは@perliedman氏が提供するleafletJsのサードパーティ拡張です。
サーバ上に置いたGeoJSONを呼び出して、「ピザ配達状況」めいたマップアプリをつくる事ができます。
実際のところ
とりあえず、公式から持ってきましょう。
$ git clone https://github.com/perliedman/leaflet-realtime.git
とれたら、サンプルを起動してみます。
$ cd leaflet-realtime/example $ open trail.html
三秒ごとにトークンが移動し、数回分の移動軌跡が残るサンプルが表示される筈。
ここで表示されるデータは
https://wanderdrone.appspot.com/
にあり、三秒ごとに一回更新されているようです。
中身はこんな感じ。
{"geometry": {"type": "Point", "coordinates": [111.19591175057819, -4.9534701779661079]}, "type": "Feature", "properties": {}}
自前のをやる
では、trailを参考に少し改造してみましょう。
trail.jsを以下のようにします。
var map = L.map('map'), trail = { type: 'Feature', properties: { id: 1 }, geometry: { type: 'LineString', coordinates: [] } }, realtime = L.realtime(function(success, error) { L.Realtime.reqwest({ url: 'http://localhost:8080/api/status', type: 'json' }) .then(function(data) { var trailCoords = trail.geometry.coordinates; trailCoords.push(data.geometry.coordinates); trailCoords.splice(0, Math.max(0, trailCoords.length - 5)); success({ type: 'FeatureCollection', features: [data, trail] }); }) .catch(error); }, { interval: 3 * 1000 }).addTo(map); L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); realtime.on('update', function() { map.fitBounds(realtime.getBounds(), {maxZoom: 3}); });
次に、localhostにGeoJSONを吐く鯖を用意します。
私はbottleでやっつけてます。
shuzo-kino.hateblo.jp
本当に最小構成でこんな感じ
from bottle import get, run @get('/api/status') def api_status(): return {"geometry": {"type": "Point", "coordinates": [111.19591175057819, -4.9534701779661079]}, "type": "Feature", "properties": {}} run(host='localhost', port=8080)
データ鯖を立ち上げつつ、CORSを無効化できるブラウザで起動します。
OS Xなら、Safariですね。
ちゃんと行けば、こんな感じでボ〜っとトークンが突っ立っている絵がでます。
動かしても3秒毎に中心が変わるので、更新が掛かっている事は確認できます。