ラベル tutorials の投稿を表示しています。 すべての投稿を表示
ラベル tutorials の投稿を表示しています。 すべての投稿を表示

2018年8月23日木曜日

OpenLayers5 Tutorials - 4 Raster Reprojection

Raster Reprojection
ラスタ再投影
(図は使用していないので、OpenLayers のホームページを参照してください。)

OpenLayers has an ability to display raster data from WMS, WMTS, static images and many other sources in a different coordinate system than delivered from the server. Transformation of the map projections of the image happens directly in a web browser. The view in any Proj4js supported coordinate reference system is possible and previously incompatible layers can now be combined and overlaid.

OpenLayers は、サーバから配信されるよりも、異なる座標系の WMS、WMTS、静的なイメージ、その他の多くのソースからラスタデータを表示する機能があります。イメージのマップ投影法の変換は、web ブラウザーで直接行われます。座標参照系がサポートされている Proj4js の view が可能で、以前は互換性のないレイヤが、現在、結合とオーバレイすることができます。


Usage
使い方

The API usage is very simple. Just specify proper projection (e.g. using EPSG code) on ol/View:

API の使用方法は非常に簡単です。ol/View で適切な投影法 (例えば、EPSG コードを使用) を指定するだけです。
import {Map, View} from 'ol';
import TileLayer from 'ol/layer/Tile';
import TileWMS from 'ol/source/TileWMS';

var map = new Map({
 target: 'map',
 view: new View({
  projection: 'EPSG:3857', //HERE IS THE VIEW PROJECTION
  center: [0, 0],
  zoom: 2
 }),
 layers: [
  new TileLayer({
   source: new TileWMS({
    projection: 'EPSG:4326', //HERE IS THE DATA SOURCE PROJECTION
    url: 'http://demo.boundlessgeo.com/geoserver/wms',
    params: {
     'LAYERS': 'ne:NE1_HR_LC_SR_W_DR'
    }
   })
  })
 ]
});
If a source (based on ol/source/TileImage or ol/source/Image) has a projection different from the current ol/View’s projection then the reprojection happens automatically under the hood.

(ol/source/TileImage または ol/source/Image に基づく) ソースが現在の ol/View の投影法と別の投影法である場合、再投影は「内部で」で自動的に行われます。

Examples
OpenLayers サイトの Examples にある例

● Raster reprojection demo
● OpenStreetMap to WGS84 reprojection
● Reprojection with EPSG.io database search
● Image reprojection

Custom projection
カスタム投影法

The easiest way to use a custom projection is to add the Proj4js library to your project and then define the projection using a proj4 definition string. It can be installed with

カスタム投影法を使用する最も簡単な方法は、Proj4js ライブラリをプロジェクトに追加し、それから、proj4 定義文字列を使用して投影法を定義することです。次のコマンドでインストールできます

npm install proj4

Following example shows definition of a British National Grid:

次の例は、British National Grid の定義を示しています。
import proj4 from 'proj4';
import {get as getProjection, register} from 'ol/proj';

proj4.defs('EPSG:27700', '+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 ' +
 '+x_0=400000 +y_0=-100000 +ellps=airy ' +
 '+towgs84=446.448,-125.157,542.06,0.15,0.247,0.842,-20.489 ' +
 '+units=m +no_defs');
register(proj4);
var proj27700 = getProjection('EPSG:27700');
proj27700.setExtent([0, 0, 700000, 1300000]);
Change of the view projection
view projection(ビュー投影法)の変更

To switch the projection used to display the map you have to set a new ol/View with selected projection on the ol/Map:br />
マップを表示するために使用される投影法を切り替えるために、ol.Map 上の選択される投影法を使用して、new ol.View を設定しなければなりません:
map.setView(new View({
 projection: 'EPSG:27700',
 center: [400000, 650000],
 zoom: 4
}));

TileGrid and Extents
TileGrid と範囲

When reprojection is needed, new tiles (in the target projection) are under the hood created from the original source tiles. The TileGrid of the reprojected tiles is by default internally constructed using ol/tilegrid~getForProjection(projection). The projection should have extent defined (see above) for this to work properly.

投影法が必要な場合、(ターゲット投影法の)新しいタイルは、「内部で」元のソースタイルから作成されます。再投影されたタイルの TileGrid は、デフォルトでは ol/tilegrid~getForProjection(projection) を使用して内部的に構築されています。投影は、これが正常に動作するために定義される(上記参照)範囲が必要です。

Alternatively, a custom target TileGrid can be constructed manually and set on the source instance using ol/source/TileImage~setTileGridForProjection(projection, tilegrid). This TileGrid will then be used when reprojecting to the specified projection instead of creating the default one. In certain cases, this can be used to optimize performance (by tweaking tile sizes) or visual quality (by specifying resolutions).

また、カスタムターゲット TileGrid は、手動で構成され、ol/source/TileImage~setTileGridForProjection (projection, tilegrid) を使用してソースインスタンスに設定されます。この TileGrid は、デフォルトのものを作成する代わりに指定された投影法で再投影するとき、使用されます。特定のケースで、これは(タイルサイズを調整することによる)パフォーマンスや(解像度を指定することによる)画質を最適化するために使用できます。


How it works
動作の仕方

The reprojection process is based on triangles -- the target raster is divided into a limited number of triangles with vertices transformed using ol/proj capabilities (proj4js is usually utilized to define custom transformations). The reprojection of pixels inside the triangle is approximated with an affine transformation (with rendering hardware-accelerated by the canvas 2d context):

再投影プロセはス三角形に基づいています--ターゲットラスタは、ol/proj 機能を使用する頂点変換を使用して、三角形の限られた数に分かれています。(proj4js は、カスタム変換の定義に通常利用されます。)三角形の内側のピクセルの再投影は、 (canvas 2d コンテキストによるハードウェア加速のレンダリングで) アフィン(affine)変換で近似されます。

図 How it works

This way we can support a wide range of projections from proj4js (or even custom transformation functions) on almost any hardware (with canvas 2d support) with a relatively small number of actual transformation calculations.

このように、実際の変換の計算の数が比較的少ない(canvas 2d をサポートする)ほぼすべてのハードウェアの proj4js (またはカスタム変換関数) からの投影の広い範囲をサポートできます。

The precision of the reprojection is then limited by the number of triangles.

再投影の精度は、そのとき、三角形の数によって制限されます。

The reprojection process preserves transparency on the raster data supplied from the source (png or gif) and the gaps and no-data pixels generated by reprojection are automatically transparent.

再投影プロセスは、ソース(png または gif)から供給されたラスタデータの透明度を維持し、再投影によって生成されたギャップとデータなしのピクセルは自動的に透明になります。

Dynamic triangulation
動的な三角形分割

The above image above shows a noticeable error (especially on the edges) when the original image (left; EPSG:27700) is transformed with only a limited number of triangles (right; EPSG:3857). The error can be minimized by increasing the number of triangles used.

上記の上のイメージは、元のイメージ(左;EPSG:27700)が限られた数の三角形だけで変換変換される(右のEPSG:3857)とき、顕著なエラー(特にエッジ上)を示します。エラーは、使用される三角形の数を増やすことで最小化できます。

Since some transformations require a more detail triangulation network, the dynamic triangulation process automatically measures reprojection error and iteratively subdivides to meet a specific error threshold:

いくつかの変換は、より詳細な三角分割ネットワークを必要とするので、動的な三角形分割プロセスは再投影誤差を自動的に測定し、特定のエラーしきい値に合わせて繰り返し細分化します:

図 Iterative triangulation

For debugging, rendering of the reprojection edges can be enabled by ol.source.TileImage#setRenderReprojectionEdges(true).

デバッグのため、再投影エッジのレンダリングは、ol/source/TileImage#setRenderReprojectionEdges(render) で有効にできます。


Advanced
上級

Triangulation precision threshold
三角形分割精度のしきい値

The default triangulation error threshold in pixels is given by ERROR_THRESHOLD (0.5 pixel). In case a different threshold needs to be defined for different sources, the reprojectionErrorThreshold option can be passed when constructing the tile image source.

ピクセル単位でデフォルトの三角形分割エラーしきい値は、ERROR_THRESHOLD (0.5 ピクセル) で与えられます。異なるしきい値が異なるソースに定義される必要がある場合は、タイルイメージソースを構築するとき reprojectionErrorThreshold オプションが渡されます。

Limiting visibility of reprojected map by extent
範囲による再投影されるマップの可視性の制限

The reprojection algorithm uses inverse transformation (from view projection to data projection). For certain coordinate systems this can result in a "double occurrence" of the source data on a map. For example, when reprojecting a map of Switzerland from EPSG:21781 to EPSG:3857, it is displayed twice: once at the proper place in Europe, but also in the Pacific Ocean near New Zealand, on the opposite side of the globe.

再投影アルゴリズムは、(view の投影法からデータの投影法への) 逆変換を使用します。特定の座標系では、これはマップのソースデータの「二重出現」をもたらす可能性があります。たとえば、EPSG:21781 から EPSG:3857 へスイス連邦共和国のマップを再投影するとき、ヨーロッパの適切な場所に1回、しかし、地球の反対側のニュージーランド近くの太平洋にもう1回、計2回表示されます。

図 Double occurrence of a reprojected map

Although this is mathematically correct behavior of the inverse transformation, visibility of the layer on multiple places is not expected by users. A possible general solution would be to calculate the forward transformation for every vertex as well - but this would significantly decrease performance (especially for computationally expensive transformations).

これは逆変換の数学的に正しい動作ですが、複数の場所でレイヤの表示はユーザに期待されていません。考えられる一般的な解決策は、すべての頂点の順変換を計算することですが、これは(特に計算コストの高い変換の場合)パフォーマンスを大幅に低下させます。

Therefore a recommended workaround is to define a proper visibility extent on the ol.layer.Tile in the view projection. Setting such a limit is demonstrated in the reprojection demo example.

したがって、推奨される回避策は、view projection(投影法)の ol/layer/Tile に適切な表示の範囲を定義します。このような制限再の設定は、再投影デモの例(Raster Reprojection[reprojection.html])に示します。

Resolution calculation
解像度計算

When determining source tiles to load, the ideal source resolution needs to be calculated. The ol/reproj~calculateSourceResolution(sourceProj, targetProj, targetCenter, targetResolution) function calculates the ideal value in order to achieve pixel mapping as close as possible to 1:1 during reprojection, which is then used to select proper zoom level from the source.

読み込むソースタイルを決定するときは、理想的なソースの解像度を計算する必要があります。ol/reproj-calculateSourceResolution(sourceProj、targetProj、targetCenter、targetResolution) 関数は、再投影の間に 1:1 にできるだけ近いピクセルマッピングを達成するために最適な値を計算し、そのときソースから適切なズームレベルを選択するために使用します。

It is, however, generally not practical to use the same source zoom level for the whole target zoom level -- different projections can have significantly different resolutions in different parts of the world (e.g. polar regions in EPSG:3857 vs EPSG:4326) and enforcing a single resolution for the whole zoom level would result in some tiles being scaled up/down, possibly requiring a huge number of source tiles to be loaded. Therefore, the resolution mapping is calculated separately for each reprojected tile (in the middle of the tile extent).

しかしながら、すべてのターゲットズームレベルのために同じソースのズームレベルを使うことは実用的ではありません--異なる投影法は、世界の異なる部分で大幅に異なる解像度を持つことができ(例えば極地 EPSG:3857 対 EPSG:4326 ) 、全体のズームレベルに単一の解像度を適用すると、いくつかのタイルが拡大/縮小され、ロードされる膨大な数のソースタイルを必要とする可能性があります。したがって、解像度マッピングは (タイル範囲の中央に) 再投影されたタイルごとに個別に計算されます。

OpenLayers5 Tutorials - 3 Some Background on OpenLayers

Introduction
Objectives
目的

OpenLayers is a modular, high-performance, feature-packed library for displaying and interacting with maps and geospatial data.

OpenLayers は、マップと地理空間データで表示とインタラクションのための、モジュール方式で高性能、機能をパッケージにしたライブラリです。

The library comes with built-in support for a wide range of commercial and free image and vector tile sources, and the most popular open and proprietary vector data formats. With OpenLayers's map projection support, data can be in any projection.

ライブラリは、商用やフリーの広い範囲のイメージやベクタタイルソース、および、最も一般的なオープンや著作権のあるベクタデータフォーマットのためのビルトインサポートを備えています。OpenLayers のマッププロジェクション(地図投影法)サポートで、データはすべてのプロジェクション(投影法)になることができます。

Public API
パブリック API

OpenLayers is available as ol npm package, which provides all modules of the officially supported API.

OpenLayers は、ol npm package として利用でき、公式にサポートされている API のモジュールがすべて提供されています。

Renderers and Browser Support
レンダラとブラウザのサポート

By default, OpenLayers uses a performance optimized Canvas renderer. An experimental WebGL renderer (without text rendering support) is also avaialble.

デフォルトでは、OpenLayers は、パフォーマンスに最適化された Canvas レンダラを使用します。実験的な WebGL レンダラ(テキスト描画サポートを除く)も利用できます。

OpenLayers runs on all modern browsers that support HTML5 and ECMAScript 5. This includes Chrome, Firefox, Safari and Edge. For older browsers and platforms like Internet Explorer (down to version 9) and Android 4.x, polyfills, the application bundle needs to be transpiled (e.g. using Babel) and bundled with polyfills for requestAnimationFrame, Element.prototype.classList and URL.

OpenLayers は、HTML5 や ECMAScript 5 をサポートするすべての近代的なブラウザで動作します。これには、Chrome、Firefox、Safari、Edge を含みます。Internet Explorer(バージョン9まで)や Android 4.x などの古いブラウザやプラットフォームのために、polyfills、アプリケーションバンドルは、(例えば、Babel を使用する)transpile(transcompile) され、requestAnimationFrame と Element.prototype.classList と URL のためのポリフィルでバンドルされることが必要です。

訳注:transpile transcompile の短縮形。(transitive) To compile (source code) by translating from one source programming language to another, producing translated source code in the other language.
あるプログラミング言語から他のものへ翻訳することによって(ソースコードを)コンパイルすること、他の言語でソースコードが翻訳された生成物。[Weblio より]

The library is intended for use on both desktop/laptop and mobile devices, and supports pointer and touch interactions.

ライブラリは、デスクトップ/ラップトップとモバイルデバイス両方に使用するために意図され、ポインタとタッチインタラクションをサポートします。

Module and Naming Conventions
モジュールと命名規則

OpenLayers modules with CamelCase names provide classes as default exports, and may contain additional constants or functions as named exports:

キャメルケース名を使用した OpenLayers モジュールは、default exports としてクラスを提供し、named exports として追加 constants 、または、functions を含めることができます:

import Map from 'ol/Map';
import View from 'ol/View';

Class hierarchies grouped by their parent are provided in a subfolder of the package, e.g. layer/.

親によってグループ化されたクラス階層は、パッケージのサブホルダ、例えば layer/、に提供されます。

For convenience, these are also available as named exports, e.g.

便宜上、これらは、例えば次のように、named exports として利用できます。

import {Map, View} from 'ol';
import {Tile, Vector} from 'ol/layer';

In addition to these re-exported classes, modules with lowercase names also provide constants or functions as named exports:

これらの再エクスポートクラスに加えて、小文字名のモジュールは named exports として constants、または、functions も提供します:

import {inherits} from 'ol';
import {fromLonLat} from 'ol/proj';

OpenLayers5 Tutorials - 2 Basic Concepts

Basic Concepts Map
マップ

The core component of OpenLayers is the map (ol/Map). It is rendered to a target container (e.g. a div element on the web page that contains the map). All map properties can either be configured at construction time, or by using setter methods, e.g. setTarget().

OpenLayers コアコンポーネントは、map (ol/Map) です。それは、target(ターゲット)コンテナ (map を含む web ページの div エレメントなど) に描画されます。すべての map プロパティは、構築時に、または、setTarget() などの setter(セッタ)メソッドを使用して設定できます。

The markup below could be used to create a that contains your map.

下記のマークアップは、map を含む 6lt;div> を作成するために使用されます。

6lt;div id="map" style="width: 100%, height: 400px">6lt;/div>

The script below constructs a map that is rendered in the 6lt;div> above, using the map id of the element as a selector.

下記のスクリプトは、セレクタとしてエレメントの map id を使用することによって、上記の 6lt;div> に描画されるマップを構築します。

import Map from 'ol/Map';

var map = new Map({target: 'map'});


View
ビュー

The map is not responsible for things like center, zoom level and projection of the map. Instead, these are properties of a ol/View instance.

map は、マップの中心、ズームレベル、投影法のようなものを担いません。代わりに、これらは、ol/View インスタンスのプロパティです。
import View from 'ol/View';

map.setView(new View({
 center: [0, 0],
 zoom: 2
}));
A View also has a projection. The projection determines the coordinate system of the center and the units for map resolution calculations. If not specified (like in the above snippet), the default projection is Spherical Mercator (EPSG:3857), with meters as map units.

View は、projection(投影法)もあります。projection は、中心と map 解像度計算のための単位の座標系を決定します。(上記のスニペットのように)指定されていない場合 、初期値の projection は、map(マップ)単位がメートルの球状メルカトル(EPSG:3857)です。

The zoom option is a convenient way to specify the map resolution. The available zoom levels are determined by maxZoom (default: 28), zoomFactor (default: 2) and maxResolution (default is calculated in such a way that the projection's validity extent fits in a 256x256 pixel tile). Starting at zoom level 0 with a resolution of maxResolution units per pixel, subsequent zoom levels are calculated by dividing the previous zoom level's resolution by zoomFactor, until zoom level maxZoom is reached.

zoom(ズーム)オプションは、map 解像度を指定する便利な方法です。使用可能なズームレベルは、maxZoom(初期値:28)、zoomFactor(初期値:2)、および maxResolution(初期値は投影の有効範囲が256x256ピクセルのタイルに収まるように計算されます)によって決まります。maxResolution ピクセル単位の解像度を持つズームレベル 0 から開始し、それ以降のズームレベルは、ズームレベル maxZoom に到達するまで、前のズームレベルの解像度を zoomFactor で割ることによって計算されます。


Source
ソース

To get remote data for a layer, OpenLayers uses ol/source/Source subclasses. These are available for free and commercial map tile services like OpenStreetMap or Bing, for OGC sources like WMS or WMTS, and for vector data in formats like GeoJSON or KML.

layer(レイヤ)のリモートデータを取得するために、OpenLayers は ol/source/Source のサブクラスを使用します。これらは、OpenStreetMap や Bing などの無料および商業地図タイルサービスで、WMS や WMTS などの OGC ソースで、 GeoJSON または KML などのフォーマットの ベクタデータが使用可能です。

import OSM from 'ol/source/OSM';

var osmSource = OSM();


Layer
レイヤ

A layer is a visual representation of data from a source. OpenLayers has four basic types of layers:

layer(レイヤ)は、source(ソース)からのデータの視覚的表現です。OpenLayers は、4つの基本的な種類の layer があります:

● ol/layer/Tile - Renders sources that provide tiled images in grids that are organized by zoom levels for specific resolutions.
● ol/layer/Image - Renders sources that provide map images at arbitrary extents and resolutions.
● ol/layer/Vector - Renders vector data client-side.
● ol/layer/VectorTile - Renders data that is provided as vector tiles.

● ol/layer/Tile - 指定の解像度の ズームレベルによって構成されたグリッドでタイルイメージ(画像)を提供するソース(source)を描画します。
● ol/layer/Image - 任意の範囲と解像度でマップイメージ(画像)を提供するソース(source)を描画します。
● ol/layer/Vector - クライアントサイドのベクタ(vector)データを描画します。
● ol/layer/VectorTile - ベクタ(vector)タイルとして提供されるデータを描画します。

import TileLayer from 'ol/layer/Tile';

var osmLayer = new TileLayer({source: osmSource});
map.addLayer(osmLayer);


Putting it all together
すべて一緒に配置

The above snippets can be combined into a single script that renders a map with a single tile layer:

上記のスニペットは、単一タイルレイヤでマップを描画する単一のスクリプトに結合できます:
import Map from 'ol/Map';
import View from 'ol/View';
import OSM from 'ol/source/OSM';
import TileLayer from 'ol/source/Tile';

new Map({
 layers: [
  new TileLayer({source: new OSM()})
 ],
 view: new View({
  center: [0, 0],
  zoom: 2
 }),
 target: 'map'
});

OpenLayers5 Tutorials - 1b Building an OpenLayers Application

Initial steps
最初の手順

Create a new empty directory for your project and navigate to it by running mkdir new-project && cd new-project. Initialize your project using npm init and answer the questions asked.

プロジェクト用に新しい空のディレクトリを作成し、mkdir new-project && cd new-project を実行して、そのディレクトリに移動します。npm init を使用してプロジェクトを初期化し、質問に回答します。

Add OpenLayers as dependency to your application with

OpenLayers を依存関係としてアプリケーションに追加します

npm install ol

At this point you can ask NPM to add required development dependencies by running

この時点で、実行によって必要とされる開発依存関係を追加するよう NPM に尋ねることができます。

npm install --save-dev parcel-bundler


■□ Debian9 で試します■□
mkdir new-project && cd new-project を実行します。

user@deb9-vmw:~$ mkdir new-project && cd new-project

プロジェクトディレクトリ new-project の依存関係を管理するために、npm init で package.json を作成します。

user@deb9-vmw:~/new-project$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install ` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (new-project) [以下すべて空欄でEnterキーを押す]
version: (1.0.0) 
description: 
entry point: (index.js) 
test command: 
git repository: 
keywords: 
author: 
license: (ISC) 
About to write to /home/nob61/new-project/package.json:

{
  "name": "new-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this ok? (yes) y

│   Update available 5.6.0 → 6.3.0    │
│     Run npm i -g npm to update      │
npm のアップデートを支持されたので実行します。

user@deb9-vmw:~/new-project$ ls
package.json
user@deb9-vmw:~/new-project$ npm -v
5.6.0
user@deb9-vmw:~/new-project$ su
パスワード:
root@deb9-vmw:/home/nob61/new-project# npm i -g npm
/usr/bin/npm -> /usr/lib/node_modules/npm/bin/npm-cli.js
/usr/bin/npx -> /usr/lib/node_modules/npm/bin/npx-cli.js
+ npm@6.3.0
added 283 packages, removed 363 packages and updated 41
packages in 13.391s
root@deb9-vmw:/home/nob61/new-project# exit
exit
user@deb9-vmw:~/new-project$ npm -v
6.3.0

npm install ol を実行します。

user@deb9-vmw:~/new-project$ npm install ol npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN new-project@1.0.0 No description
npm WARN new-project@1.0.0 No repository field.

+ ol@5.1.3
added 8 packages from 6 contributors and audited 8 packages in 3.083s
found 0 vulnerabilities

npm install --save-dev parcel-bundler を実行します。

user@deb9-vmw:~/new-project$ npm install --save-dev parcel-bundler
npm WARN deprecated browserslist@1.7.7: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.

> deasync@0.1.13 install /home/nob61/new-project/node_modules/deasync
> node ./build.js

`linux-x64-node-8` exists; testing
Binary is fine; exiting

> parcel-bundler@1.9.7 postinstall /home/nob61/new-project/node_modules/parcel-bundler
> node -e "console.log('\u001b[35m\u001b[1mLove Parcel? You can now donate to our open collective:\u001b[22m\u001b[39m\n > \u001b[34mhttps://opencollective.com/parcel/donate\u001b[0m')"

Love Parcel? You can now donate to our open collective:
> https://opencollective.com/parcel/donate
npm WARN new-project@1.0.0 No description
npm WARN new-project@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

+ parcel-bundler@1.9.7
added 680 packages from 534 contributors and audited 7354 packages in 47.215s
found 0 vulnerabilities
user@deb9-vmw:~/new-project$ ls
node_modules package-lock.json package.json

■□ここまで■□

Application code and index.html
アプリケーション コードと index.html

Place your application code in index.js. Here is a simple

starting point:index.js にアプリケーション コードを配置します。ここに簡単な出発点があります。
import 'ol/ol.css';
import {Map, View} from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';

const map = new Map({
 target: 'map',
 layers: [
  new TileLayer({
   source: new OSM()
  })
 ],
 view: new View({
  center: [0, 0],
  zoom: 0
 })
});
You will also need an ìndex.html file that will use your bundle. Here is a simple example:

バンドルを使用する ìndex.html ファイルも必要です。ここには簡単な例があります。
<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Using Parcel with OpenLayers</title>
  <style>
   #map {
    width: 400px;
    height: 250px;
   }
  </style>
 </head>
 <body>
  <div id="map"></div>
  <script src="./index.js"></script>
 <body>
</html>


■□ Debian9 で試します■□
次の内容で index.js を作成します。

user@deb9-vmw:~/new-project$ vim index.js
import 'ol/ol.css';
import {Map, View} from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';

const map = new Map({
 target: 'map',
 layers: [
  new TileLayer({
   source: new OSM()
  })
 ],
 view: new View({
  center: [0, 0],
  zoom: 0
 })
});
次の内容で index.html を作成します。

user@deb9-vmw:~/new-project$ vim index.html
<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Using Parcel with OpenLayers</title>
  <style>
   #map {
    width: 400px;
    height: 250px;
   }
  </style>
 </head>
 <body>
  <div id="map"></div>
  <script src="./index.js"></script>
 <body>
</html>
 ■□ここまで■□

Creating a bundle
バンドルの作成

With simple scripts you can introduce the commands npm run build and npm start to manually build your bundle and watch for changes, respectively. Add the following to the script section in package.json:

簡単なスクリプトで、バンドルと変更の監視を、それぞれ、手動でビルドするために、npm run build と npm start コマンドを導入することができます。package.json の script[スクリプト]セクションに次のものを追加します

"scripts": {
 "test": "echo \"Error: no test specified\" && exit 1",
 "start": "parcel index.html",
 "build": "parcel build --public-url . index.html"
}

That's it. Now to run your application, enter

これで終わりです。アプリケーションを実行するために、直ちに、

npm start

in your console. To test your application, open http://localhost:1234/ in your browser. Whenever you change something, the page will reload automatically to show the result of your changes.

とコンソールに入力します。アプリケーションをテストするために、ブラウザで http://localhost:1234/ を開きます。何かを変更するといつでも、変更の結果を表示するために、ページは自動的にリロードします。

Note that a single JavaScript file with all your application code and all dependencies used in your application has been created. From the OpenLayers package, it only contains the required components.

アプリケーションコードすべてとアプリケーションに使用されるすべての依存関係が一緒の単体の JavaScript ファイルが作成されることに注意してください。OpenLayers パッケージから、必要とされるコンポーネントだけ含まれます。

To create a production bundle of your application, simply type

アプリケーションの本番のバンドルを作成するために、単に

npm run build

and copy the dist/ folder to your production server.

とタイプし、本番サーバに dist/ ホルダをコピーます。

■□ Debian9 で試します■□
package.json に script セクションを次のように追加します。

user@deb9-vmw:~/public_html/new-project$ vim package.json
{
  "name": "browserify_demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "parcel index.html",
    "build": "parcel build --public-url . index.html"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ol": "^5.1.3"
  },
    "parcel-bundler": "^1.9.7"
  }
}
npm start と npm run build を実行します。

user@deb9-vmw:~/new-project$ npm start

> new-project@1.0.0 start /home/user/new-project
> parcel index.html

Server running at http://localhost:1234
✨ Built in 14.58s.

Webブラウザのアドレス欄に

http://localhost/:1234

と入力して Enter キーを押します。


index.js を編集(例えば、"zoom: 1" に修正)して index.html を再読込するとマップが拡大されます。


サーバを停止(Ctrl + c)して npm run build を実行します。

^Cuser@deb9-vmw:~/new-project$ user@deb9-vmw:~/new-project$ npm run build
> new-project@1.0.0 build /home/uer/new-project
> parcel build --public-url . index.html

✨  Built in 33.24s.

dist/new-project.72267420.map    ⚠️  2.38 MB     374ms
dist/new-project.72267420.js      608.47 KB    27.94s
dist/new-project.3e5e72c1.css        3.6 KB     6.87s
dist/index.html                       296 B     4.81s
user@deb9-vmw:~/new-project$ ls
dist  index.html  index.js  node_modules  package-lock.json  package.json
user@deb9-vmw:~/new-project$ ls -l dist/
合計 7804
-rw-r--r-- 1 user user     339  8月 16 11:09 index.html
-rw-r--r-- 1 user user    3688  8月 16 11:02 new-project.3e5e72c1.css
-rw-r--r-- 1 user user  623078  8月 16 11:02 new-project.72267420.js
-rw-r--r-- 1 user user 2497278  8月 16 11:02 new-project.72267420.map
-rw-r--r-- 1 user user    4478  8月 16 11:09 new-project.890281e4.css
-rw-r--r-- 1 user user 1907618  8月 16 11:20 new-project.890281e4.js
-rw-r--r-- 1 user user 2940632  8月 16 11:20 new-project.890281e4.map
■□ここまで■□

OpenLayers5 Tutorials - 1a Building an OpenLayers Application

Introduction
はじめに

Modern JavaScript works best when using and authoring modules. The recommended way of using OpenLayers is installing the ol package. This tutorial walks you through setting up a simple dev environment, which requires node for everything to work.

モダンな JavaScript は、モジュールを使用して編集するとき最高の動作をします。OpenLayers を使用する推奨される方法は、ol パッケージをインストールすることです。このチュートリアルは、動作するすべての node を必要とする簡単な開発環境を設定をします。

In this tutorial, we will be using Parcel to bundle our application. There are several other options, some of which are linked from the README.

このチュートリアルは、アプリケーションをパンドルするための Parcel を使用します。他にもいくつかのオプションがあり、README からリンクされたものもあります。


■□ Debian9 で試します■□
Debian9(stretch)に、最新の Node.js をインストールしてみます。Debian9.5 にアップデートしたとき、更新されなかった APT も修正しています。

「How to Install Latest NodeJs & NPM on Debian 9/8/7(https://tecadmin.net/install-latest-nodejs-npm-on-debian/)」と「パッケージマネージャを利用した Node.js のインストール(https://nodejs.org/ja/download/package-manager/)」、「NodeSource Node.js Binary Distributions(https://github.com/nodesource/distributions)」を参考にします。

最初に、「curl」をインストールします。「curl(https://curl.haxx.se/)」は、コマンドライン、または、スクリプトでデータを転送するために使用されます。

root@deb9-vmw:~# apt-cache policy curl
curl:
  インストールされているバージョン: (なし)
  候補:               7.52.1-5+deb9u6
  バージョンテーブル:
     7.52.1-5+deb9u6 500
        500 http://ftp.jp.debian.org/debian stretch/main amd64 Packages
user@deb9-vmw:~$ su -
パスワード:
root@deb9-vmw:~# apt-get install curl
root@deb9-vmw:~# apt-cache policy curl
curl:
  インストールされているバージョン: 7.52.1-5+deb9u6
  候補:               7.52.1-5+deb9u6
  バージョンテーブル:
 *** 7.52.1-5+deb9u6 500
        500 http://ftp.jp.debian.org/debian stretch/main amd64 Packages
        100 /var/lib/dpkg/status
次に、node.js をインストールします。一緒に NPM もインストールされます。「npm(https://www.npmjs.com/)」は、JavaScript と世界最大のソフトウェアレジストリのパッケージマネージャです。
root@deb9-vmw:~# curl -sL https://deb.nodesource.com/setup_8.x | bash -

## Installing the NodeSource Node.js 8.x LTS Carbon repo...


## Populating apt-get cache...

+ apt-get update
無視:1 http://ftp.jp.debian.org/debian stretch InRelease
---
無視:15 http://deb.debian.org/debian stretch/updates/main DEP-11 64x64 Icons
パッケージリストを読み込んでいます... 完了
W: http://ftp.jp.debian.org/debian/dists/stretch-updates/InRelease: The key(s) in the keyring /etc/apt/trusted.gpg are ignored as the file is not readable by user '_apt' executing apt-key.
W: http://ftp.jp.debian.org/debian/dists/stretch/Release.gpg: The key(s) in the keyring /etc/apt/trusted.gpg are ignored as the file is not readable by user '_apt' executing apt-key.
W: リポジトリ http://deb.debian.org/debian stretch/updates Release には Release ファイルがありません。
N: このようなリポジトリから取得したデータは認証できないので、データの使用は潜在的に危険です。
N: リポジトリの作成とユーザ設定の詳細は、apt-secure(8) man ページを参照してください。
E: http://deb.debian.org/debian/dists/stretch/updates/main/source/Sources の取得に失敗しました  404  Not Found [IP: 151.101.196.204 80]
E: いくつかのインデックスファイルのダウンロードに失敗しました。これらは無視されるか、古いものが代わりに使われます。
Error executing command, exiting

次に、node.js をインストールします。一緒に NPM もインストールされます。「npm(https://www.npmjs.com/)」は、JavaScript と世界最大のソフトウェアレジストリのパッケージマネージャです。

root@deb9-vmw:~# apt-get install -y nodejs
パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています                
状態情報を読み取っています... 完了
以下の追加パッケージがインストールされます:
  libuv1
以下のパッケージが新たにインストールされます:
  libuv1 nodejs
アップグレード: 0 個、新規インストール: 2 個、削除: 0 個、保留: 0 個。
3,524 kB 中 0 B のアーカイブを取得する必要があります。
この操作後に追加で 14.5 MB のディスク容量が消費されます。
以前に未選択のパッケージ libuv1:amd64 を選択しています。
(データベースを読み込んでいます ... 現在 174735 個のファイルとディレクトリがインストールされています。)
.../libuv1_1.9.1-3_amd64.deb を展開する準備をしています ...
libuv1:amd64 (1.9.1-3) を展開しています...
以前に未選択のパッケージ nodejs を選択しています。
.../nodejs_4.8.2~dfsg-1_amd64.deb を展開する準備をしています ...
nodejs (4.8.2~dfsg-1) を展開しています...
libuv1:amd64 (1.9.1-3) を設定しています ...
libc-bin (2.24-11+deb9u3) のトリガを処理しています ...
man-db (2.7.6.1-2) のトリガを処理しています ...
nodejs (4.8.2~dfsg-1) を設定しています ...
update-alternatives: /usr/bin/js (js) を提供するために自動モードで /usr/bin/nodejs を使います

それでは、node.js と npm のバージョンを確認します。

root@deb9-vmw:~# exit
ログアウト
user@deb9-vmw:~$ node -v
-su: node: コマンドが見つかりません
user@deb9-vmw:~$ npm -v
-su: npm: コマンドが見つかりません

インストールに失敗しているようです。nodejs のバージョンを見てみると古いバージョンがインストールされています。

root@deb9-vmw:~# nodejs -v
v4.8.2

色々メッセージが表示されていますが、「The key(s) in the keyring /etc/apt/trusted.gpg are ignored as the file is not readable by user '_apt' executing apt-key.」で検索した結果、aptが実行前にサーバが正しいかどうかを公開鍵でするチェックに問題があるようです。『Debian テスト版の「apt-get update時の警告メッセージ」(https://blogs.yahoo.co.jp/jeaou/40499468.html)』を参考に次のようにしました。
以前から Synaptic パッケージマネージャで「パッケージ情報の再読込」を実行すると同様のメッセージが表示されていました。

nodejs を削除します。

root@deb9-vmw:~# apt remove nodejs
root@deb9-vmw:~# apt autoremove

公開鍵を /etc/apt/trusted.gpg に変更します。

root@deb9-vmw:~# mv /etc/apt/trusted.gpg /etc/apt/trusted.gpg_org
root@deb9-vmw:~# cp /usr/share/keyrings/debian-archive-keyring.gpg /etc/apt/trusted.gpg

「W: リポジトリ http://deb.debian.org/debian stretch/updates Release には Release ファイルがありません。」で検索した結果、 /etc/apt/sources.list の「deb http://deb.debian.org/debian/ stretch/updates」に問題があるようです。「Debian: The repository does not have a Release file(https://unix.stackexchange.com/questions/371890/debian-the-repository-does-not-have-a-release-file)」を参考に /etc/apt/sources.list の次の行を修正します。

root@deb9-vmw:~# vim /etc/apt/sources.list
---
# deb http://deb.debian.org/debian/ stretch/updates main
# deb-src http://deb.debian.org/debian/ stretch/updates main

deb http://security.debian.org/debian-security stretch/updates main
deb-src http://security.debian.org/debian-security stretch/updates main
---

再度、node.js をインストールします。
root@deb9-vmw:~# curl -sL https://deb.nodesource.com/setup_8.x | bash -

## Installing the NodeSource Node.js 8.x LTS Carbon repo...


## Populating apt-get cache...

+ apt-get update
無視:1 http://ftp.jp.debian.org/debian stretch InRelease
ヒット:2 http://ftp.jp.debian.org/debian stretch-updates InRelease        
ヒット:3 http://ftp.jp.debian.org/debian stretch Release                       
ヒット:4 http://security.debian.org/debian-security stretch/updates InRelease  
パッケージリストを読み込んでいます... 完了                 

## Installing packages required for setup: apt-transport-https...

+ apt-get install -y apt-transport-https > /dev/null 2>&1

## Confirming "stretch" is supported...

+ curl -sLf -o /dev/null 'https://deb.nodesource.com/node_8.x/dists/stretch/Release'

## Adding the NodeSource signing key to your keyring...

+ curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -
OK

## Creating apt sources list file for the NodeSource Node.js 8.x LTS Carbon repo...

+ echo 'deb https://deb.nodesource.com/node_8.x stretch main' > /etc/apt/sources.list.d/nodesource.list
+ echo 'deb-src https://deb.nodesource.com/node_8.x stretch main' >> /etc/apt/sources.list.d/nodesource.list

## Running `apt-get update` for you...

+ apt-get update
無視:1 http://ftp.jp.debian.org/debian stretch InRelease
ヒット:2 http://ftp.jp.debian.org/debian stretch-updates InRelease             
ヒット:3 http://ftp.jp.debian.org/debian stretch Release                       
ヒット:4 http://security.debian.org/debian-security stretch/updates InRelease  
取得:6 https://deb.nodesource.com/node_8.x stretch InRelease [4,647 B]
取得:7 https://deb.nodesource.com/node_8.x stretch/main Sources [762 B]
取得:8 https://deb.nodesource.com/node_8.x stretch/main amd64 Packages [1,006 B]
6,415 B を 1秒 で取得しました (5,263 B/s)
パッケージリストを読み込んでいます... 完了

## Run `sudo apt-get install -y nodejs` to install Node.js 8.x LTS Carbon and npm
## You may also need development tools to build native addons:
     sudo apt-get install gcc g++ make
## To install the Yarn package manager, run:
     curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
     echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
     sudo apt-get update && sudo apt-get install yarn
root@deb9-vmw:~# apt-get install -y nodejs
パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています                
状態情報を読み取っています... 完了
以下のパッケージが新たにインストールされます:
  nodejs
アップグレード: 0 個、新規インストール: 1 個、削除: 0 個、保留: 0 個。
12.7 MB のアーカイブを取得する必要があります。
この操作後に追加で 61.4 MB のディスク容量が消費されます。
取得:1 https://deb.nodesource.com/node_8.x stretch/main amd64 nodejs amd64 8.11.3-1nodesource1 [12.7 MB]
12.7 MB を 9秒 で取得しました (1,380 kB/s)
以前に未選択のパッケージ nodejs を選択しています。
(データベースを読み込んでいます ... 現在 174743 個のファイルとディレクトリがインストールされています。)
.../nodejs_8.11.3-1nodesource1_amd64.deb を展開する準備をしています ...
nodejs (8.11.3-1nodesource1) を展開しています...
nodejs (8.11.3-1nodesource1) を設定しています ...
man-db (2.7.6.1-2) のトリガを処理しています ...
それでは、node.js と npm のバージョンを確認します。

root@deb9-vmw:~# exit
ログアウト
user@deb9-vmw:~$ node -v
v8.11.3
user@deb9-vmw:~$ npm -v
5.6.0

java のバージョンを確認します。(Debian 9 - 10 Eclipse 4.7 "Oxygen" の設定(2017年7月13日木曜日のブログ)で Java を設定しました。)

user@deb9-vmw:~$ java -version
java version "1.8.0_171"
OpenJDK Runtime Environment (build 1.8.0_171-8u171-b11-1~deb9u1-b11)
OpenJDK 64-Bit Server VM (build 25.171-b11, mixed mode)

node.js のインストールをテストするために、webサーバを作成します。次の内容で http_sever.js を作成します。

user@deb9-vmw:~$ vim http_server.js
var http = require('http');
http.createServer(function (req, res) {
 res.writeHead(200, {'Content-Type': 'text/plain'});
 res.end('Hello World\n');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');

次のコマンドで web サーバを起動します。

user@deb9-vmw:~$ node http_server.js
Server running at http://127.0.0.1:3000/

Webブラウザのアドレス欄に

http://127.0.0.1:3000/

と入力して Enter キーを押します。


■□ここまで■□

続く...

OpenLayers5 Tutorials - 0

Tutorials
チュートリアル

ここでは、OpenLayers の Docs(Documentation[http://openlayers.org/en/latest/doc/])の「For a more in-depth overview of OpenLayers core concepts, check out the tutorials.」のリンク先にある「Tutorials(http://openlayers.org/en/latest/doc/tutorials/)」の各項目


● Building an OpenLayers Application
OpenLayers アプリケーションの構築
● Basic Concepts
基本コンセプト
● Some Background on OpenLayers
OpenLayers に関わるバックグラウンド
● Raster Reprojection
ラスタの再投影

を訳してみました。サイトに搭載されている画像などは使用していません。

2018年6月9日土曜日

Leaflet 1.3 - 4-11 Showing video files

4-11 Showing video files

Leaflet can help you display videos somewhere on the map.

Leaflet は、マップ上のどこかのビデオを表示する支援をします。


Video on webpages
ウェブページのビデオ

Video used to be a hard task when building a webpage, until the <video> HTML element was made available.

ビデオは、<video%gt; HTML エレメントが利用されるようになるまで、ウェブページを構築するときかつては困難な仕事でした。

Nowadays, we can use the following HTML code:

今日、次の HTML コードを使用できます:
<video width="500" controls>
 <source src="https://www.mapbox.com/bites/00188/patricia_nasa.webm" type="video/webm">
  <source src="https://www.mapbox.com/bites/00188/patricia_nasa.mp4" type="video/mp4">
</video>
To display this video:

このビデオを表示:
(訳注:これは画像です)


If a video can be shown in a webpage in this way, then Leaflet can display it inside a map. It is important that the videos are prepared in such a way that they will fit the map: The video should have a “north-up” orientation, and its proportions should fit the map. If not, it will look out of place.

もし、ビデオがこの方法でウェブページに表示できるなら、Leaflet は、マップ内にそれを表示できます。マップにぴったりはめ込むような方法でビデオが準備されることは重要です:ビデオは「北上」方向を保持し、その形状はマップに合わなければなりません。そうでなければ、不適当に見えます。


Bounds of an image overlay

First of all, create a Leaflet map and add a background L.TileLayer in the usual way:

まず最初に、Leaflet マップを作成し、通常の方法で背景の L.TileLayer を追加します:
var map = L.map('map').setView([37.8, -96], 4);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=' + mapboxAccessToken, {
 id: 'mapbox.satellite',
 attribution: ...
}).addTo(map);
Then, we’ll define the geographical bounds that the video will cover. This is an instance of L.LatLngBounds, which is a rectangular shape:

それから、ビデオが覆う地理的境界を定義します。これは L.LatLngBounds インスタンスで、長方形です:
var bounds = L.latLngBounds([[ 32, -130], [ 13, -100]]);
If you want to see the area covered by a LatLngBounds, use a L.Rectangle:

もし、LatLngBounds によって覆われた地域を確認したいのなら、L.Rectangle を使用します:
L.rectangle(bounds).addTo(map);

map.fitBounds(bounds);


Adding the video overlay

Adding a video overlay works very similar to adding a image overlay. For just one image, L.ImageOverlays is used like this:

ビデオオーバレイを追加することは、イメージオーバレイを追加することにとても似ている作業です。ただ一つのイメージには、L.ImageOverlays はこのように使用されます:
var overlay = L.imageOverlay( imageUrl, bounds, options );
For a video overlay, just:
ビデオオーバレイには、ただ:

● Use L.videoOverlay instead of L.imageOverlay
● Instead of the image URL, specify one video URL or an array of video URLs

● L.imageOverlay の代わりに L.videoOverlay を使用
● イメージ URL の代わりに、一つのビデオ URL、または、ビデオ URLs の配列を指定
var videoUrls = [
 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
 'https://www.mapbox.com/bites/00188/patricia_nasa.mp4'
];
var bounds = L.latLngBounds([[ 32, -130], [ 13, -100]]);
var videoOverlay = L.videoOverlay( videoUrls, bounds, {
 opacity: 0.8
}).addTo(map);
And just like that, you’ll get the video on your map:

そしてこのように、マップ上のビデオを得られます:


Video overlays behave like any other Leaflet layer - you can add and remove them, let the user select from several videos using a layers control, etc.

ビデオオーバレイは、他の Leaflet レイヤのように動作します - それらの追加と削除ができ、ユーザにレイヤコントロールを使用していくつかのビデオから選択させる、などです。


A bit of control over the video

If you read the API documentation, you’ll notice that the L.VideoOverlay class does not have a play() or pause() method.

もし、API ドキュメントを読むなら、L.VideoOverlay クラスは play() または pause() メソッドがないことに注意してください。

For this, the getElement() method of the video overlay is useful. It returns the HTMLVideoElement (which inherits from HTMLMediaElement) for the overlay - and that has methods like play() and pause(), e.g.

このため、ビデオオーバレイの getElement() メソッドは便利です。それはオーバレイに(HTMLMediaElement から継承する)HTMLVideoElement を返します - そして、例えば play() と pause() のようなメッソドを持ちます。
videoOverlay.getElement().pause();
This allows us to build custom interfaces. For example, we can build a small subclass of L.Control to play/pause this video overlay once it’s loaded:

これは、カスタムインターフェイスを構築することを許可します。例えば、ロードするとこのビデオを 再生/一時停止 するために L.Control の小さいサブクラスを構築できます:
videoOverlay.on('load', function () {
 var MyPauseControl = L.Control.extend({
  onAdd: function() {
   var button = L.DomUtil.create('button');
   button.innerHTML = '⏸';
   L.DomEvent.on(button, 'click', function () {
    videoOverlay.getElement().pause();
   });
   return button;
  }
 });
 var MyPlayControl = L.Control.extend({
  onAdd: function() {
   var button = L.DomUtil.create('button');
   button.innerHTML = '⏵';
   L.DomEvent.on(button, 'click', function () {
    videoOverlay.getElement().play();
   });
   return button;
  }
 });
 var pauseControl = (new MyPauseControl()).addTo(map);
 var playControl = (new MyPlayControl()).addTo(map);
});

コード全体
<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="./leaflet13/leaflet.css" />
  <script src="./leaflet13/leaflet.js"></script>
  <title>Showing video files</title>
 </head>
 <body>
  <div id="map" style="width: 600px; height: 400px;"></div>
  <script>
   //Bounds of an image overlay
   var map = L.map('map').setView([37.8, -96], 4);
   var wmsLayer = L.tileLayer.wms('https://demo.boundlessgeo.com/geoserver/ows?', {
    layers: 'nasa:bluemarble'
   }).addTo(map);
   //Adding the video overlay
   var videoUrls = [
    'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
    'https://www.mapbox.com/bites/00188/patricia_nasa.mp4'
   ];
   var bounds = L.latLngBounds([[ 32, -130], [ 13, -100]]);
   //L.rectangle(bounds).addTo(map);
   map.fitBounds(bounds);
   //Adding the video overlay
   var videoOverlay = L.videoOverlay( videoUrls, bounds, {
    opacity: 0.8
   }).addTo(map);
   videoOverlay.on('load', function () {
    var MyPauseControl = L.Control.extend({
     onAdd: function() {
      var button = L.DomUtil.create('button');
      button.innerHTML = '⏸';
      L.DomEvent.on(button, 'click', function () {
       videoOverlay.getElement().pause();
      });
      return button;
     }
    });
    var MyPlayControl = L.Control.extend({
     onAdd: function() {
      var button = L.DomUtil.create('button');
      button.innerHTML = '⏵';
      L.DomEvent.on(button, 'click', function () {
       videoOverlay.getElement().play();
      });
      return button;
     }
    });
    var pauseControl = (new MyPauseControl()).addTo(map);
    var playControl = (new MyPlayControl()).addTo(map);
   });
  </script>
 </body>
</html>

2018年6月7日木曜日

Leaflet 1.3 - 4-10 Working with map panes

4-10 Working with map panes
How the default map panes work to display overlays on top of tiles, and how to override that.

デフォルトのマップペインが、タイルの前面にあるオーバレイを表示するために動作する方法とそれを上書きする方法。


What are panes?
ペインとは?

In Leaflet, map panes group layers together implicitly, without the developer knowing about it. This grouping allows web browsers to work with several layers at once in a more efficient way than working with layers individually.

Leaflet では、マップペインはレイヤを暗黙的に一纏めにし、それについて知っている開発者はいません。このグルーピングはウェブブラウザに、個々にレイヤを動作するより、もっと効果的な方法で一度にいくつかのレイヤを動作することを許可します。

Map panes use the z-index CSS property to always show some layers on top of others. The default order is:

マップペインは、いくつかのレイヤを他の前面にいつも表示するために、z-index CSS プロパティを使用します。

● TileLayers and GridLayers
● Paths, like lines, polylines, circles, or GeoJSON layers.
● Marker shadows
● Marker icons
● Popups

This is why, in Leaflet maps, popups always show “on top” of other layers, markers always show on top of tile layers, etc.

これは、Leaflet でポップアップがいつも他のレイヤの前面に表示し、マーカがいつもタイルレイヤの前面に表示されるなど、の理由です。

A new feature of Leaflet 1.0.0 (not present in 0.7.x) is custom map panes, which allows for customization of this order.

(今の 0.7.x ではなく)Leaflet 1.0.0 の新しい機能は、カスタムマップペインで、この命令のカスタマイズ(ユーザ改変)を許可します。


The default is not always right
デフォルトは常に正しくない

In some particular cases, the default order is not the right one for the map. We can demonstrate this with the Carto basemaps and labels:

いくつかの個々のケースで、デフォルトの順序がマップに対する正しいものではありません。これを Carto basemaps とラベルで説明できます:

Basemap tile with no labels
Transparent labels-only tile
Labels on top of basemap

If we create a Leaflet map with these two tile layers, any marker or polygon will show on top of both, but having the labels on top looks much nicer. How can we do that?

Leaflet マップをこれら2つのレイヤで作成する場合、いくつかのマーカまたはポリゴンが両方の前面に表示しますが、ラベルを前面に持ってくると見た目が良くなります。


Custom pane

We can use the defaults for the basemap tiles and some overlays like GeoJSON layers, but we have to define a custom pane for the labels, so they show on top of the GeoJSON data.

ベースマップタイルと GeoJSON レイヤのようないくつかのオーバレイのデフォルトを使用できますが、ラベルのカスタムペインを定義しなければならず、その結果 GeoJSON レイヤの前面に表示されます。

Custom map panes are created on a per-map basis, so first create an instance of L.Map and the pane:

カスタムマップペインは、マップごとの基準で作成され、それで最初に L.Map のインスタンスとペインを作成します。
var map = L.map('map');
map.createPane('labels');
The next step is setting the z-index of the pane. Looking at the defaults, a value of 650 will make the TileLayer with the labels show on top of markers but below pop-ups. By using getPane(), we have a reference to the HTMLElement representing the pane, and change its z-index:

次のステップは、ペインの z-index を設定します。デフォルトを見てみると、650 の値はマーカの前面ですがポップアップの後面に表示するラベルで TileLayer を生成します。getPane() を使うことによって、ペインを表示する HTMLElement を参照し、その z-index を変更します:
map.getPane('labels').style.zIndex = 650;
One of the problems of having image tiles on top of other map layers is that the tiles will capture clicks and touches. If a user clicks anywhere on the map, the web browser will assume she clicked on the labels tiles, and not on the GeoJSON or on the markers. This can be solved using the pointer-events CSS property:

他のマップレイヤの前面にイメージタイルを保持することの問題の一つは、タイルがクリックおよびタッチをキャプチャすることです。ユーザがマップ上のどこかでクリックした場合、GeoJSON 上またはマーカ上ではなく、ウェブブラウザはユーザがラベルタイルをクリックしたと仮定します。これは、pointer-events CSS プロパティを使用することで解決されます:
map.getPane('labels').style.pointerEvents = 'none';
With the pane now ready, we can add the layers, paying attention to use the pane option on the labels tiles:

これでペインを使う準備ができ、ラベルタイル上の pane オプションを使用することに注意を払いながら、レイヤを追加できます:
var positron = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', {
 attribution: '©OpenStreetMap, ©CartoDB'
}).addTo(map);
var positronLabels = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png', {
 attribution: '©OpenStreetMap, ©CartoDB',
 pane: 'labels'
}).addTo(map);
var geojson = L.geoJson(GeoJsonData, geoJsonOptions).addTo(map);
Finally, add some interaction to each feature on the GeoJSON layer:

最後に、GeoJSON 上の各々のフィーチャにいくつかのインタラクションを追加します:
geojson.eachLayer(function (layer) {
 layer.bindPopup(layer.feature.properties.name);
});
map.fitBounds(geojson.getBounds());
Now the example map is complete!

これで、example map は完成です!


今回は、GeoJSON データが取得できなかったためマップの確認ができませんでした。コード全体はexample map で確認してください。

2018年6月6日水曜日

Leaflet 1.3 - 4-9 WMS and TMS

4-9 WMS and TMS

How to integrate with WMS and TMS services from professional GIS software.

プロフェッショナル GIS ソフトウェアから WMS と TMS サービスを統合する方法


WMS, short for web map service, is a popular way of publishing maps by professional GIS software (and seldomly used by non-GISers). This format is similar to map tiles, but more generic and not so well optimized for use in web maps. A WMS image is defined by the coordinates of its corners - a calculation that Leaflet does under the hood.

web map service(ウェブマップサービス)の略である WMS は、プロフェッショナル GIS ソフトウェアマップを編集する一般的な方法です(そして、GIS使用者でないとめったに使われません)。このフォーマットはマップタイルに似ていますが、もっと一般的で、そして、ウェッブマップで使用するためにとてもよく最適化されているとは言えません。WMS 画像はその隅の座標 - Leaflet が見えないところでしている計算 - によって定義されます。

TMS stands for tiled map service, and is a map tiling standard more focused on web maps, very similar to the map tiles that Leaflet expects in a L.TileLayer.

TMS は、タイル(化された)マップサービスを表し、ウェッブマップにさらに焦点を当てたマップタイル基準であり、Leaflet が L.TileLayer で要求するマップタイルにとても似ています。


WMS in Leaflet

When somebody publishes a WMS service, most likely they link to something called a GetCapabilities document. For this tutorial, we’ll use the demo map services from GeoServer, at https://demo.boundlessgeo.com/geoserver/web/. As you can see in that page, “WMS” links to the following URL:

誰かが WMS サービスを編集するとき、おそらく GetCapabilities ドキュメントを呼び出すものにリンクします。このチュートリアルで、https://demo.boundlessgeo.com/geoserver/web/ の GeoServer からマップサービスを使います。このページに見られるように、「WMS」は次の URL でリンクします:
https://demo.boundlessgeo.com/geoserver/ows?service=wms&version=1.3.0&request=GetCapabilities
Leaflet does not understand WMS GetCapabilities documents. Instead, you have to create a L.TileLayer.WMS layer, provide the base WMS URL, and specify whatever WMS options you need.

Leaflet は、WMS GetCapabilities ドキュメントを理解しません。かわりに、L.TileLayer.WMS layer を作成し、ベース WMS URL を提供し、必要な WMS オプションを何でも指定しなければなりません。 The base WMS URL is simply the GetCapabilities URL, without any parameters, like so: ベース WMS URL は、単純な GetCapabilities URL で、パラメータはなく、このようになります:
https://demo.boundlessgeo.com/geoserver/ows?
And the way to use that in a Leaflet map is simply:

Leaflet でマップ(map)を使用する方法は簡単です:
var map = L.map(mapDiv, mapOptions);

var wmsLayer = L.tileLayer.wms('https://demo.boundlessgeo.com/geoserver/ows?', wmsOptions).addTo(map);
An instance of L.TileLayer.WMS needs at least one option: layers. Be careful, as the concept of “layer” in Leaflet is different from the concept of “layer” in WMS!

L.TileLayer.WMS の例では、少なくとも1つ option: layers が必要です。Leaflet での「layer」の概念は WMS での「layer」の概念と違うので、注意してください。

WMS servers define a set of layers in the service. These are defined in the GetCapabilities XML document, which most times is tedious and difficult to understand. Usually it’s a good idea to use software such as QGIS to see what layers are available in a WMS server to see the layer names available:

WMS サーバはサービスでレイヤ一式を定義します。これらは GetCapabilities XML ドキュメントで定義され、大抵の場合は大量の単語で理解が困難です。通常は、使えるレイヤ名を調べるために、WMS サービスでどのレイヤが有効か確認するため QGIS のようなソフトウェアを使用することは良い考えです:


We can see that the OpenGeo demo WMS has a WMS layer named ne:ne with a basemap. Let’s see how it looks:

OpenGeo demo WMS は、basemap で ne:ne と名付けられた WMS レイヤがあることを確認できます。それがどのように見えるか確認しましょう:
var wmsLayer = L.tileLayer.wms('https://demo.boundlessgeo.com/geoserver/ows?', {
 layers: 'ne:ne'
}).addTo(map);

Or we can try the nasa:bluemarble WMS layer:

または、nasa:bluemarble WMS レイヤを試すことができます。
var wmsLayer = L.tileLayer.wms('https://demo.boundlessgeo.com/geoserver/ows?', {
 layers: 'nasa:bluemarble'
}).addTo(map);

The layers option is a comma-separated list of layers. If a WMS service has defined several layers, then a request for a map image can refer to more than one layer.

layers オプションは、レイヤのカンマで区切られたリストです。もし WMS サーバがいくつかのレイヤで定義されているなら、マップ画像のリクエストは一つ以上のレイヤを参照できます。

For the example WMS server we’re using, there is a ne:ne_10m_admin_0_countries WMS layer showing country landmasses and country names, and a ne:ne_10m_admin_0_boundary_lines_land WMS layer showing country boundaries. The WMS server will compose both layers in one image if we request both, separated with a comma:

私達が使用している example WMS server のために、国土と国名を表示する ne:ne_10m_admin_0_countries WMS レイヤ、および、国境を表示する ne:ne_10m_admin_0_boundary_lines_land WMS レイヤがあります。WMS サーバは、もしカンマで区切られた両方リクエストするなら、両方のレイヤを一つの画像で構成します:
var countriesAndBoundaries = L.tileLayer.wms('https://demo.boundlessgeo.com/geoserver/ows?', {
 layers: 'ne:ne_10m_admin_0_countries,ne:ne_10m_admin_0_boundary_lines_land'
}).addTo(map);
Note this will request one image to the WMS server. This is different than creating a L.TileLayer.WMS for the countries, another one for the boundaries, and adding them both to the map. In the first case, there is one image request and it’s the WMS server who decides how to compose (put on top of each other) the image. In the second case, there would be two image requests and it’s the Leaflet code running in the web browser who decides how to compose them.

これは WMS サーバに一つの画像をリクエストしていることに注意してください。これは、国ともう一つの国境のために L.TileLayer.WMS を作成し、それらを両方マップに追加するのとは違います。最初のケースは、1つの画像リクエストがあり、画像を構成(お互いを前面に配置)する方法を決定するのは WMS サーバです。2番めのケースは、2つの画像リクエストがあり、それらを構成する方法を決定するのはウェッブブラウザで実行する Leaflet コードです。

If we combine this with the layers control, then we can build a simple map to see the difference:

もし layers control(レイヤコントロール)でこれを組み合わせるなら、相違を確認するために単純なマップを構築できます:
var basemaps = {
 Countries: L.tileLayer.wms('https://demo.boundlessgeo.com/geoserver/ows?', {
  layers: 'ne:ne_10m_admin_0_countries'
 }),
 Boundaries: L.tileLayer.wms('https://demo.boundlessgeo.com/geoserver/ows?', {
  layers: 'ne:ne_10m_admin_0_boundary_lines_land'
 }),
 'Countries, then boundaries': L.tileLayer.wms('https://demo.boundlessgeo.com/geoserver/ows?', {
  layers: 'ne:ne_10m_admin_0_countries,ne:ne_10m_admin_0_boundary_lines_land'
 }),
 'Boundaries, then countries': L.tileLayer.wms('https://demo.boundlessgeo.com/geoserver/ows?', {
  layers: 'ne:ne_10m_admin_0_boundary_lines_land,ne:ne_10m_admin_0_countries'
 })
};
L.control.layers(basemaps).addTo(map);

basemaps.Countries.addTo(map);
Change to the “Countries, then boundaries” option, so you can see the boundaries “on top” of the landmasses, but the WMS server is clever enough to display building labels on top of that. It’s up to the WMS server how to compose layers when asked for many.

「Countries、それから boundaries」オプションを変えると、国土の前面に国境を確認できますが、WMS は、その前面に構築するラベルを表示するほど優秀です。たくさん尋ねられたとき、レイヤを構成する方法を WMS が決定します。





Notes to GIS users of WMS services
WMS サーバの GIS ユーザへの注意事項

From a GIS point of view, WMS handling in Leaflet is quite basic. There’s no GetCapabilities support, no legend support, and no GetFeatureInfo support.

GIS の観点から、Leaflet であつかう WMS は全く基本的です。GetCapabilities サポートと legend(凡例)サポート、GetFeatureInfo サポートはありません。

L.TileLayer.WMS has extra options, which can be found in Leaflet’s API documentation. Any option not described there will be passed to the WMS server in the getImage URLs.

L.TileLayer.WMS は、特別なオプションがあり、 Leaflet API ドキュメントで見つけられます。そこの記述がないいくつかのオプションは、getImage URLs で WMS に渡されます。

Also note that Leaflet supports very few coordinate systems: CRS:3857, CRS:3395 and CRS:4326 (See the documentation for L.CRS). If your WMS service doesn’t serve images in those coordinate systems, you might need to use Proj4Leaflet to use a different coordinate system in Leaflet. Other than that, just use the right CRS when initializing your map, and any WMS layers added will use it:

Leaflet はとても僅かな座標系システム:CRS:3857、CRS:3395、CRS:4326(L.CRS ドキュメントを参照)しかサポートしていないことに注意してください。もし WMS サービスがそれらの座標系システムで画像を供給しない場合、Leaflet で異なる座標系システムを使用するために Proj4Leaflet を使う必要があります。それ以外は、マップを初期化するとき正しい CRS を使うだけで、追加されたWMS レイヤはそれを使います。
var map = L.map('map', {
 crs: L.CRS.EPSG4326
});

var wmsLayer = L.tileLayer.wms('https://demo.boundlessgeo.com/geoserver/ows?', {
 layers: 'nasa:bluemarble'
}).addTo(map);


TMS in Leaflet

Leaflet doesn’t have explicit support for TMS services, but the tile naming structure is so similar to the common L.TileLayer naming scheme, that displaying a TMS service is almost trivial.

Leaflet は、TMS サービスの明示的なサポートはありませんが、タイルネーミング構造は、ごく普通の TMS サービスを表示する、通常の L.TileLayer ネーミングスキーム(体系)にとても似ています。

Using the same OpenGeo WMS/TMS server demo, we can see there’s a TMS endpoint at:

同じ OpenGeo WMS/TMS サーバデモを使用するとき、終点があることを確認できます:
https://demo.boundlessgeo.com/geoserver/gwc/service/tms/1.0.0
Checking the MapCache help about TMS and the TMS specification you can see that the URL for a map tile in TMS looks like:

TMS と TMS 使用について MapCache ヘルプを確かめると、TMS のマップタイルの URL が次のようであることを確認できます:
http://base_url/tms/1.0.0/ {tileset} / {z} / {x} / {y} .png
To use the OpenGeo TMS services as a L.TileLayer, we can check the capabilities document (the same as the base endpoint, in our case https://demo.boundlessgeo.com/geoserver/gwc/service/tms/1.0.0) to see what tilesets are available, and build our base URLs:

L.TileLayer として OpenGeo TMS サービスを使用するために、タイルセットが有効であることを確認するために capabilities ドキュメント(ベース終了点と同じで、この場合 https://demo.boundlessgeo.com/geoserver/gwc/service/tms/1.0.0)を確かめ、ベース URLs を構築できます。

訳注:このリンク先で次のように表示され、penGeo TMS サービスのタイルセットが無効になっていました。
400: Could not locate a layer or layer group with id LayerInfoImpl-27d2b3a0:15c6507c77c:-7ff5 within GeoServer configuration, the GWC configuration seems to be out of synch

https://demo.boundlessgeo.com/geoserver/gwc/service/tms/1.0.0/ne:ne@EPSG:900913@png/{z}/{x}/{y}.png
https://demo.boundlessgeo.com/geoserver/gwc/service/tms/1.0.0/nasa:bluemarble@EPSG:900913@jpg/{z}/{x}/{y}.jpg
And use the tms:true option when instantiating the layers, like so:

そして、レイヤのインスタンスを生成するとき、次のように、tms:true オプションを使います:
var tms_ne = L.tileLayer('https://demo.boundlessgeo.com/geoserver/gwc/service/tms/1.0.0/ne:ne@EPSG:900913@png/{z}/{x}/{y}.png', {
 tms: true
}).addTo(map);
var tms_bluemarble = L.tileLayer('https://demo.boundlessgeo.com/geoserver/gwc/service/tms/1.0.0/nasa:bluemarble@EPSG:900913@jpg/{z}/{x}/{y}.jpg', {
 tms: true
});

A new feature in Leaflet 1.0 is the ability to use {-y} in the URL instead of a tms: true option, e.g.:

Leaflet 1.0 での新しい機能は、tms: true オプションの代わりに、 URL に {-y} を使用する機能です。
var layer = L.tileLayer('http://base_url/tms/1.0.0/tileset/{z}/{x}/{-y}.png');
The tms: true option (in Leaflet 0.7) or {-y} (in Leaflet 1.0) are needed because the origin of coordinates of vanilla L.TileLayers is the top left corner, so the Y coordinate goes down. In TMS, the origin of coordinates is the bottom left corner so the Y coordinate goes up.

普通の L.TileLayers の座標の原点が左上隅なので、(Leaflet 0.7 での)tms: true オプション、または、(Leaflet 1.0 での){-y} が必要とされ、Y 座標は下に下がります。TMS では、座標の原点は左下隅で、Y 座標は上に上がります。

Besides the difference in the y coordinate and the discovery of tilesets, TMS services serve tiles exactly in the way that L.TileLayer expects.

Y 座標の相違とタイルセットの発見を除いて、TMS サービスは、 L.TileLayer が要求する方法で正確にタイルを供給します。


TMS については、地理院タイルを使用してみました。「地理院タイルを用いたサイト構築サンプル集(http://maps.gsi.go.jp/development/sample.html)」を参考にしました。



コード全体
<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="./leaflet13/leaflet.css" />
  <script src="./leaflet13/leaflet.js"></script>
  <title>WMS and TMS</title>
 </head>
 <body>
  <div id="map" style="width: 600px; height: 400px;"></div>
  <script>
   //WMS in Leaflet
   /*
   var map = L.map('map', {
 center: [-17, -67],
 zoom: 3
   });
   */
   /*
   var wmsLayer = L.tileLayer.wms('https://demo.boundlessgeo.com/geoserver/ows?', {
    // layers: 'ne:ne'
    layers: 'nasa:bluemarble'
   }).addTo(map);
   */
   /*
   var basemaps = {
    Countries: L.tileLayer.wms('https://demo.boundlessgeo.com/geoserver/ows?', {
     layers: 'ne:ne_10m_admin_0_countries'
    }),
    Boundaries: L.tileLayer.wms('https://demo.boundlessgeo.com/geoserver/ows?', {
     layers: 'ne:ne_10m_admin_0_boundary_lines_land'
    }),
    'Countries, then boundaries': L.tileLayer.wms('https://demo.boundlessgeo.com/geoserver/ows?', {
     layers: 'ne:ne_10m_admin_0_countries,ne:ne_10m_admin_0_boundary_lines_land'
    }),
    'Boundaries, then countries': L.tileLayer.wms('https://demo.boundlessgeo.com/geoserver/ows?', {
     layers: 'ne:ne_10m_admin_0_boundary_lines_land,ne:ne_10m_admin_0_countries'
    })
   };
   L.control.layers(basemaps).addTo(map);

   basemaps.Countries.addTo(map);
   */
   //Notes to GIS users of WMS services
   /*
   var map = L.map('map', {
    center: [0, 0],
    zoom: 1,
    crs: L.CRS.EPSG4326
   });
   var wmsLayer = L.tileLayer.wms('https://demo.boundlessgeo.com/geoserver/ows?', {
    layers: 'nasa:bluemarble'
   }).addTo(map);
   */
   //TMS in Leaflet
   /*
   var map = L.map('map', {
    center: [-17, -67],
    zoom: 3
   });
   var tms_ne = L.tileLayer('https://demo.boundlessgeo.com/geoserver/gwc/service/tms/1.0.0/ne:ne@EPSG:900913@png/{z}/{x}/{y}.png', {
    tms: true
   }).addTo(map);
   var tms_bluemarble = L.tileLayer('https://demo.boundlessgeo.com/geoserver/gwc/service/tms/1.0.0/nasa:bluemarble@EPSG:900913@jpg/{z}/{x}/{y}.jpg', {
    tms: true
   });
   var basemaps = {
    'Natural Earth': tms_ne,
    'NASA Blue Marble': tms_bluemarble
   };
   L.control.layers(basemaps, {}, {collapsed: false}).addTo(map);
   basemaps.Countries.addTo(map);
   */
   var map = L.map('map', {
    center: [35.3622222, 138.7313889],
    zoom: 5
   });
    var tms_std = L.tileLayer('https://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png', {
    attribution: "<a href='https://maps.gsi.go.jp/development/ichiran.html' target='_blank'>地理院タイル</a>"
   }).addTo(map);
   var tms_pale = L.tileLayer('https://cyberjapandata.gsi.go.jp/xyz/pale/{z}/{x}/{y}.png', {
    attribution: "<a href='https://maps.gsi.go.jp/development/ichiran.html' target='_blank'>地理院タイル</a>"
   });
   var basemaps = {
    'Japan STD Map': tms_std,
    'Japan Pale Map': tms_pale
   };
   L.control.layers(basemaps, {}, {collapsed: false}).addTo(map);

   basemaps.Countries.addTo(map);
  </script>
 </body>
</html>

2018年5月29日火曜日

Leaflet 1.3 - 4-8 Non-geographical maps

4-8 Non-geographical maps
A primer on L.CRS.Simple, how to make maps with no concept of “latitude” or “longitude”.

L.CRS.Simple 入門で、緯度と経度の概念のないマップを作成する方法です。


Not of this earth
この地球ではない

Sometimes, maps do not represent things on the surface of the earth and, as such, do not have a concept of geographical latitude and geographical longitude. Most times this refers to big scanned images, such as game maps.

ときには、マップは地球の表面上のものを要求しませんが、そのため、地理的な緯度と経度を持ちません。ほとんどの場合、これは、ゲームマップのような、大きなスキャン画像に関連します。

For this tutorial we’ve picked a starmap from Star Control II, a game that is now available as the open-source project The Ur-Quan Masters. These maps were made with a tool to read the open-source data files of the game, and look like this:

このチュートリアルのために、オープンソースプロジェクト The Ur-Quan Masters として現在利用できるゲーム、Star Control II から starmap を取り上げています。これらのマップは、ゲームのオープンソースデータファイルを読み込むツールで作成され、このように見えます:


(訳注:画像は、「Star Control」の 「starmaps(http://www.star-control.com/starmaps.php)」の「Name」の「07」を加工し使用します。)



The game has a built-in square coordinate system, as can be seen in the corners. This will allow us to establish a coordinate system.

ゲームは、角に見られるように、組み込み正方形座標システムがあります。これは座標システムを設置することを許可します。


CRS.Simple

CRS stands for coordinate reference system, a term used by geographers to explain what the coordinates mean in a coordinate vector. For example, [15, 60] represents a point in the Indian Ocean if using latitude-longitude on the earth, or the solar system Krueger-Z in our starmap.

coordinate reference system(座標参照系)を表す CRS、用語は、コーディネート(座標)はコーディネートベクタで意味することを説明するために地理学者によって使用されます。例えば、[15, 60] は、地球の緯度経度、または、starmap で solar system Krueger-Z を使用しているなら、インド洋にあるポイントを表します。

A Leaflet map has one CRS (and one CRS only), that can be changed when creating the map. For our game map we’ll use CRS.Simple, which represents a square grid:

Leaflet マップが一つの CRS (そして CRS ひとつだけ) 持っていますが、これはマップを作成するとき変えられます。ゲームマップのために、正方形グリッドを表す、CRS.Simple を使います:
var map = L.map('map', {
 crs: L.CRS.Simple
});
Then we can just add a L.ImageOverlay with the starmap image and its approximate bounds:

次に、starmap 画像とそのおおよその境界(bounds)で L.ImageOverlay をすぐ(下)に追加します。
var bounds = [[0,0], [1000,1000]];
var image = L.imageOverlay('uqm_map_full.png', bounds).addTo(map);
And show the whole map:

そして、マップ全体を表示します:
map.fitBounds(bounds);

This example doesn’t quite work, as we cannot see the whole map after doing a fitBounds().

この例はうまく動作しないので、fitBounds() を実行した後にマップ全体を見られません。


Common gotchas in CRS.Simple maps
CRS.Simple マップの一般的な了解事項

In the default Leaflet CRS, CRS.Earth, 360 degrees of longitude are mapped to 256 horizontal pixels (at zoom level 0) and approximately 170 degrees of latitude are mapped to 256 vertical pixels (at zoom level 0).

デフォルト Leaflet CRS、CRS.Earth、360度の経度は、(ズームレベル0で)256水平ピクセルにマップし、そして、おおよそ170度の緯度は、(ズームレベル0で)256垂直ピクセルにマップします。

In a CRS.Simple, one horizontal map unit is mapped to one horizontal pixel, and idem with vertical. This means that the whole map is about 1000x1000 pixels big and won’t fit in our HTML container. Luckily, we can set minZoom to values lower than zero:

CRS.Simple では、1水平マップ単位は1水平ピクセルでマップされ、垂直も同じです。これは、マップ全体はおよそ 1000x1000 ピクセルの大きさで、HTML コンテナにぴったり合いません。幸いに、minZoom を0以下に値を設定できます:
var map = L.map('map', {
 crs: L.CRS.Simple,
 minZoom: -5
});

Pixels vs. map units

One common mistake when using CRS.Simple is assuming that the map units equal image pixels. In this case, the map covers 1000x1000 units, but the image is 2315x2315 pixels big. Different cases will call for one pixel = one map unit, or 64 pixels = one map unit, or anything. Think in map units in a grid, and then add your layers (L.ImageOverlays, L.Markers and so on) accordingly.

CRS.Simple を使用するとき一つの一般的な間違いは、マップ単位が画像ピクセルと等しいと仮定することです。この場合、マップは 1000x1000 単位でカバーしますが、画像は 2315x2315 ピクセルの大きさです。別の場合は、1ピクセル=1マップユニット、または、64ピクセル=1マップ単位などです。1グリッド内でマップ単位を考え、それから、それに応じて(L.ImageOverlays、L.Markers などの)レイヤを追加します。

In fact, the image we’re using covers more than 1000 map units - there is a sizable margin. Measuring how many pixels there are between the 0 and 1000 coordinates, and extrapolating, we can have the right coordinate bounds for this image:

実際に、使用する画像は、1000 マップ単位以上をカバーし - 相当の大きさの余白があります。0 と 1000 座標の間に何ピクセルあるか測定し、そして推測し、この画像の右座標境界を持つことができます:

var bounds = [[-26.5,-25], [1021.5,1023]];
var image = L.imageOverlay('uqm_map_full.png', bounds).addTo(map);

(訳注:07.png を加工した画像は、3168x3168 ピクセルで、y軸の0から1000の間のピクセル数は2942です。

y 3062[y0]-120[y1000]=2942, 2942/1000=2.942

0から画像の下端までのピクセル数とy軸値は、

y0 3168-3062=104, 104/2.942=35.4

0から画像の上端までのピクセル数とy軸値は、

y1 3062/2.942=1040.8

y軸の0から1000の間のピクセル数も2942です。

x 3064[x1000]-122[x0]=2942, 2942/1000=2.942

0から画像の左端までのピクセル数とx軸値は、

x0 122/2.942=41.5

0から画像の右端までのピクセル数とx軸値は、

x1 3168-122=3046, 3046/2.942=1035.4

var bounds = [[-35.4,-41.5], [1040.8,1035.4]];





While we’re at it, let’s add some markers:

それをいじくる間、いくつかマーカを追加しましょう。
var sol = L.latLng([ 145, 175.2 ]);
L.marker(sol).addTo(map);
map.setView( [70, 120], 1);

This is not the LatLng you’re looking for
これはあなたが探している LatLng ではありません

You’ll notice that Sol is at coordinates [145,175] instead of [175,145], and the same happens with the map center. Coordinates in CRS.Simple take the form of [y, x] instead of [x, y], in the same way Leaflet uses [lat, lng] instead of [lng, lat].

Sol は、座標 [175,145] の替わりに [145,175] にあり、同じことはマップの中心(center)で起こります。CRS.Simple で座標は、[x, y] の替わりに [y, x] の形式をとり、同じように、Leaflet は、[lng, lat] の替わりに [lat, lng] を使います。

(In technical terms, Leaflet prefers to use [northing, easting] over [easting, northing] - the first coordinate in a coordinate pair points “north” and the second points “east”)

(専門用語では、[easting(東距), northing(北距)] に優先して [northing, easting] を使う方がよく、座標対で最初の座標は「北(北緯)」を示し、2番めは、「東(東経)」を示します。)

The debate about whether [lng, lat] or [lat, lng] or [y, x] or [x, y] is not new, and there is no clear consensus. This lack of consensus is why Leaflet has a class named L.LatLng instead of the more confusion-prone L.Coordinate.

[lng, lat] か [lat, lng]、または、 [y, x] か [x, y] についての論争は、新しいものではありません、そして、はっきりしたコンセンサスはありません。このコンセンサスの欠如は、Leaflet がより混乱傾向のある L.Coordinate の替わりに L.LatLng という名前のクラスがある理由です。

If working with [y, x] coordinates with something named L.LatLng doesn’t make much sense to you, you can easily create wrappers for them:

もし、L.LatLng という名前のもので [y, x] 座標で実行することが納得できないなら、それらのラッパーを簡単に作成できます:
var yx = L.latLng;

var xy = function(x, y) {
 if (L.Util.isArray(x)) {    // When doing xy([x, y]);
  return yx(x[1], x[0]);
 }
 return yx(y, x);  // When doing xy(x, y);
};
Now we can add a few stars and even a navigation line with [x, y] coordinates:

では、2、3個の星と [x, y] 座標のナビゲーションラインを追加します:
var sol      = xy(175.2, 145.0);
var mizar    = xy( 41.6, 130.1);
var kruegerZ = xy( 13.4,  56.5);
var deneb    = xy(218.7,   8.3);
L.marker(     sol).addTo(map).bindPopup(      'Sol');
L.marker(   mizar).addTo(map).bindPopup(    'Mizar');
L.marker(kruegerZ).addTo(map).bindPopup('Krueger-Z');
L.marker(   deneb).addTo(map).bindPopup(    'Deneb');
var travel = L.polyline([sol, deneb]).addTo(map);
The map looks pretty much the same, but the code is a bit more readable:

マップは全く同じように見えますが、コードはもう少し読みやすくなっています。



コード全体
<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="./leaflet13/leaflet.css" />
  <script src="./leaflet13/leaflet.js"></script>
  <title>Non-geographical maps</title>
 </head>
 <body>
  <div id="map" style="width: 600px; height: 400px;"></div>
  <script>
   //CRS.Simple
   var map = L.map('map', {
    crs: L.CRS.Simple,
    minZoom: -5 //Common gotchas in CRS.Simple maps
   });
   // var bounds = [[0,0], [1000,1000]];
   //Pixels vs. map units
   var bounds = [[-35.4,-41.5], [1040.8,1035.4]];
   var image = L.imageOverlay('uqm_map_07.png', bounds).addTo(map);
   /*
   map.fitBounds(bounds);
   
   var sol = L.latLng([ 145, 175.2 ]);
   L.marker(sol).addTo(map);
   map.setView( [70, 120], 1);
   */
   //This is not the LatLng you’re looking for
   var yx = L.latLng;

   var xy = function(x, y) {
    if (L.Util.isArray(x)) {  // When doing xy([x, y]);
     return yx(x[1], x[0]);
    }
    return yx(y, x);  // When doing xy(x, y);
   };
   var sol      = xy(175.2, 145.0);
   var mizar    = xy( 41.6, 130.1);
   var kruegerZ = xy( 13.4,  56.5);
   var deneb    = xy(218.7,   8.3);
   L.marker(     sol).addTo(map).bindPopup(      'Sol');
   L.marker(   mizar).addTo(map).bindPopup(    'Mizar');
   L.marker(kruegerZ).addTo(map).bindPopup('Krueger-Z');
   L.marker(   deneb).addTo(map).bindPopup(    'Deneb');
   var travel = L.polyline([sol, deneb]).addTo(map);
   map.setView( [70, 120], 1);
  </script>
 </body>
</html>