Maplat Advent Calendar 3日目は、Maplat Coreをnpmから設定する方法です。
npmから設定すると言っても、相変わらず画像ファイルはローカルに配置するのですが...
今日の内容が動くバージョンは、CodeSandBoxのこちらで公開されています。 => CodeSandBox Maplat Advent Calendar day 3
npmを使うので、まずはpackage.jsonを設定しましょう。
{
"name": "maplat-advent-calendar-day3",
"version": "1.0.0",
"description": "",
"main": "index.html",
"scripts": {
"start": "parcel index.html --open",
"build": "parcel build index.html"
},
"dependencies": {
"@maplat/core": "0.6.2"
},
"devDependencies": {
"@babel/core": "7.2.0",
"parcel-bundler": "^1.6.1"
},
"keywords": []
}
dependenciesで@maplat/coreの0.6.2を読み込んでいます。
CodeSnadBoxでは変更かけるとすぐ反映してくれますが、ローカルでやる場合は当然package.jsonを変更するだけでなく、npm installなどが必要です。
続いて、index.html、app.cssなどはほぼ同じなので、大きく変わるのはapp.js。
import "@maplat/core/dist/maplat_core.css";
import { MaplatApp } from "@maplat/core";
var option = {
appid: "maplat_ac_day3",
setting: {
home_position: [139.5321, 36.249302],
default_zoom: 17,
start_from: "tatebayashi_ojozu",
sources: [
{
mapID: "tatebayashi_ojozu",
setting_file:
"https://s.maplat.jp/r/tatebayashimap/maps/tatebayashi_ojozu.json"
},
"osm"
]
}
};
var app = new MaplatApp(option);
app.waitReady.then(function() {
console.log("Maplat App Ready");
});
まず、importで@maplat/core/dist/maplat_core.cssを指定し、cssを読み込んでいます。
こんな構文はES6にはなく、完全にparcel環境依存なのですが、まあそれはいいでしょう。
続けてやはりimportで、@maplat/coreからMaplatAppクラスを読み込んでいます。
optionは昨日とほぼ一緒。
違うのはMaplat Coreのオブジェクトを作るところです。
npm呼び出しの場合は、new構文でMaplatAppのオブジェクトを作り、そのオブジェクトのプロパティwaitReadyがPromiseを返すので、それをthenやawaitで待ってオブジェクトを作ります。
これは、CDN呼び出しの方のインタフェースが、まだMaplatがモジュールシステムにrequire.jsを使っていた頃の名残なので、将来的にCDN呼び出しの場合もnpmの方のインタフェースに合わせる可能性があります。
もっとも、CDN呼び出し側の後方互換性も維持するつもりではあります。
そして最後に、昨日同様、partsフォルダ下の画像リソースをindex.htmlと同階層に配置すると、動作するようになります。
動作結果は昨日と同じなので省略。
明日は、このMaplat Core地図の設定を外部ファイルで指定する方法を試してみます。