Openlayersを使ってデータを作成して、それをFusion Tablesに保存する方法を紹介します。
データをFusion Tablesにアップロードするためには、まずOauth2.0を使ってGoogleのアカウントにログインする必要があります。
それから、取得したアクセストークを使って、Fusion Tables にアクセスします。
その際に以下の2通りの方法があります。
Client-side Applications
- 認証やfusion tablesとのやり取りを、ブラウザから直接行います。
今回は、Web Server Applicationsでの方法を簡単にご紹介します。
詳細な手順はこちらを御覧ください。https://developers.google.com/accounts/docs/OAuth2?hl=ja
1.APIを使用するためにサービスを登録する
こちらでサービスを登録します。
https://code.google.com/apis/console/
2.Oauth認証するためのライブラリを用意する
Oauthのライブラリは色々ありますので、お好きなものを用意してください。例えばこれなど(私の場合は、違うものを利用しました。)
https://code.google.com/p/google-api-php-client/
ライブラリの使用方法通りに1.で取得したKeyなどを設定してサーバーに置いてください。
3.クライアント側(Openlayers)のコードを書く
Oauthの認証は、サーバー側のプログラムにアクセスします。
location.href = "auth.php"
Openlayersの作図機能で書いたデータは、geojson形式やKMLなどに変換して取り出します。
edit_layer = new OpenLayers.Layer.Vector("Editable"); geojson = new OpenLayers.Format.GeoJSON(); geojson.write(edit_layer.features)
fusion tablesに入れたいデータを、一旦Webサーバーに送ります。
var fd = new FormData(); fd.append("table", _table); fd.append("mdata", _marker); fd.append("tdata", _track); fd.append("pdata", feature_point); fd.append("ldata", feature_line); fd.append("ydata", feature_polygon); var xhr = new XMLHttpRequest(); xhr.open("POST", "export.php", true); xhr.send(fd); xhr.onload = function(e) { alert(e.target.responseText); }
4.サーバー側(php)のコードを書く
サーバー側ではクライアントから送られてきたデータを加工して、Oauth認証で得たアクセストークと共に、Fusion Tables APIを呼び出しデータを送ります。
例えば、こんな感じ。
for ($i = 0; $i < count($mdata); $i++) { $m = explode("/", $mdata[$i]); $query = "INSERT INTO " . $tableid . " (type, id , name , memo , location) VALUES ('" . $m[0] . "' , '" . $m[1] . "' , '" . $m[2] . "' , '" . $m[3] . "' , " . "'<Point> <coordinates>" . $m[4] . "</coordinates></Point>')"; $response = doPost($url, array('sql' => $query)); error_log("{$query}",0); }
位置データをFusion Tablesに送る場合は、KML形式にする必要があります。詳細はこちら
https://developers.google.com/fusiontables/docs/v1/using#KML
できあがり
コードは、こちらに置いてあります。(素人コードでごめんなさい。)
位置データは、一旦ローカルストレージに保存する関係で、geojsonにしています。
https://github.com/tmizu23/mobilemap
動作確認はこちら
http://www.ecoris.co.jp/map/
Client-side Applicationsの場合
Client-side Applications でのOpenlayresとの連携はサーバーサイドでの処理がいらないので非常に興味深いですが、まだ試していません。こちらに良い例があったので、参考にしてください。これをOpenlayersのコードと組み合わせれば、連携できるはずです。
http://gmaps-samples.googlecode.com/svn/trunk/fusiontables/javascript-api.html
https://code.google.com/p/google-api-javascript-client/
参考
http://gmaps-samples.googlecode.com/svn/trunk/fusiontables/javascript-api.html
https://developers.google.com/fusiontables/docs/v1/using
https://developers.google.com/accounts/docs/OAuth2?hl=ja
http://stackoverflow.com/questions/11595122/google-fusion-table-api-v1-properly-composed-rest-format-to-post-an-update
http://stackoverflow.com/questions/11798488/how-does-gapi-client-library-actually-use-returned-oauth-access-token-with-fusio