2018年9月26日水曜日

OpenLayers5 Workshop - 1.2 Zooming to your location

1.2 Zooming to your location
現在位置にズーム

Browsers provide an API to get the current location of the user. We want to use this feature to zoom the map to where the user currently is. To make it easier for the user to see what is going on on the map, we want to animate the zoom.

ブラウザはユーザの現在の位置を取得する API を提供します。ユーザが現在いるマップにズームするこの機能をします。ユーザがマップ上で進行していること確認するのを容易にするために、ズームをアニメーションします。

Application changes
アプリケーション変更

First of all, we need to assign the map to a constant, so we can access it from other components we're going to add in this exercise:

まず第一に、map に定数(constant)を割り当て、この演習に追加する他のコンポーネントからアクセスできるようにします。

const map = new Map({

To add the geolocation functionality, we append a short code block to our main.js file:

geolocation 関数を追加するために、main.js に短いコードブロックを追加します:
navigator.geolocation.getCurrentPosition(function(pos) {
 const coords = fromLonLat([pos.coords.longitude, pos.coords.latitude]);
 map.getView().animate({center: coords, zoom: 10});
});
This requires a new import for the fromLonLat() function, which converts longitude/latitude coordinates into the coordinate system OpenLayers uses by default for the map view (Web Mercator, EPSG:3857).

これは、fromLonLat() ファンクションのための新しい import が必要で、OpenLayers が map view のデフォルトで使用する座標システム(Web Mercator, EPSG:3857)に変換します。

import {fromLonLat} from 'ol/proj';


View the result
結果を眺める

When we look at the map in the web browser (http://localhost:3000/), we will probably get asked whether we want to give the page access to our location. After answering 'Yes', an animated zoom should take us to our current location.

ウェブブラウザ(http://localhost:3000/)でマップを見るとき、おそらく現在位置へページにアクセスさせるかどうか尋ねられます。「はい」と答えた後、アニメーションズームが現在の位置へ案内します。

■□ Debian9 で試します■□
main.js のコードに次のように追加します。

user@deb9-vmw:~/openlayers-workshop-en$ vim main.js
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZSource from 'ol/source/XYZ';
const map = new Map({ // 修正
 target: 'map-container',
 layers: [
  new TileLayer({
   source: new XYZSource({
    url: 'http://tile.stamen.com/terrain/{z}/{x}/{y}.jpg'
   })
  })
 ], 
 view: new View({
  center: [0, 0],
  zoom: 2
 })
});
// ここから追加
navigator.geolocation.getCurrentPosition(function(pos) {
 const coords = fromLonLat([pos.coords.longitude,  pos.coords.latitude]);
 map.getView().animate({center: coords, zoom: 10});
});
http://localhost:3000/ とブラウザで演習マップを開きます。(もし開かなければ、'npm start' を実行してください。
現在位置へページにアクセスさせるかどうか尋ねられます。「許可」ボタンを押すと、アニメーションズームが現在の位置へ案内します。



■□ここまで■□

0 件のコメント: