2015年4月20日月曜日

2 - ol3.4ex 116b - Geolocation tracking with orientation example 2

「geolocation-orientation.js(2116-ol3ex.js)」は、マップを表示するための JavaScript ファイルです。

「2116-ol3ex.js」
// creating the view
var view = new ol.View({
 center: ol.proj.transform([5.8713, 45.6452], 'EPSG:4326', 'EPSG:3857'),
 zoom: 19
});
// creating the map
var map = new ol.Map({
 layers: [
  new ol.layer.Tile({
   source: new ol.source.OSM()
   /** ol.source.OSM 
    * Layer source for the OpenStreetMap tile server.
    * OpenStreetMap タイルサーバのレイヤソース。(ol3 API)
    */
 })
 ],
 target: 'map',
 controls: ol.control.defaults({
 /** controls
  * Controls initially added to the map. 
  * If not specified, ol.control.defaults() is used.
  * 初期設定で、マップに追加されたコントロール。
  * 明示されていなければ、ol.control.defaults() が使用されます。
  * (ol3 API)
  */
 /** ol.control.defaults()
  * デフォルトでは、マップに含まコントロールのセット。
  * 特に設定しない限り、これは、以下の各コントロールの
  * インスタンスを含むコレクションを返します。(ol3 API)
  * ol.control.Zoom, ol.control.Rotate, ol.control.Attribution
  */
  attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
  /** @type 
   * 値のタイプ(型)の説明 - 式などで表示
   * (@use JSDoc[http://usejsdoc.org/]より)
   */
   collapsible: false // 折りたたみ
  })
 }),
 view: view
});
// Geolocation marker
var markerEl = document.getElementById('geolocation_marker');
var marker = new ol.Overlay({
/** ol.Overlay 
 * Like ol.control.Control, Overlays are visible widgets. 
 * Unlike Controls, they are not in a fixed position on 
 * the screen, but are tied to a geographical coordinate, 
 * so panning the map will move an Overlay but not a Control.
 * ol.control.Controlと同じように、オーバーレイは、目に見える
 * ウィジェットです。コントロールとは異なり、それらは画面上の
 * 固定された位置にありませんが、地理座標に関連付けられている
 * ので、オーバーレイを移動しますが、コントロールできない
 * マップをパンします。(ol3 API)
 */
 positioning: 'center-center',
 /** positioning
  * Defines how the overlay is actually positioned with 
  * respect to its position property. 
  * オーバーレイが実際にその位置プロパティを考慮して位置決めされ
  * る方法を定義します。(ol3 API)
  */
 element: markerEl,
 /** element
  * The overlay element.(ol3 API)
  */
 stopEvent: false
 /** stopEvent
  * Whether event propagation to the map viewport should 
  * be stopped. Default is true. If true the overlay is 
  * placed in the same container as that of the controls 
  * (CSS class name ol-overlaycontainer-stopevent); if 
  * false it is placed in the container with CSS class 
  * name ol-overlaycontainer.
  * マップビューポートにイベントの伝達を停止する必要がするかどう
  * か。デフォルトは true です。trueの場合、オーバーレイは(CSS
  * クラス名の ol-overlaycontainer-stopevent)コントロールと同
  * 様のコンテナに配置され、false の場合、CSSクラス名の 
  * ol-overlaycontainer によってコンテナに配置されます。
  * (ol3 API)
  */
});
map.addOverlay(marker);
/** addOverlay()
 * Add the given overlay to the map.
 * 与えられたオーバーレイをマップに追加します。(ol3 API)
 */
/** LineString to store the different geolocation positions. 
 * This LineString is time aware.
 * The Z dimension is actually used to store the rotation 
 * (heading).
 * 異なる地理位置を保存するためのラインストリング。このラインスト
 * リングは、時間を認識しています。 Z次元は、実際の回転(方角)を
 * 格納するために使用されます。
 */
var positions = new ol.geom.LineString([],
/** ol.geom.LineString
 * Linestring geometry.(ol3 API)
 */
 /** @type {ol.geom.GeometryLayout} */ ('XYZM'));
 /** @type 
  * 値のタイプ(型)の説明 - 式などで表示
  * (@use JSDoc[http://usejsdoc.org/]より)
  */
// Geolocation Control
var geolocation = new ol.Geolocation(/** @type {olx.GeolocationOptions} */ ({
/** ol.Geolocation
 * Helper class for providing HTML5 Geolocation capabilities. 
 * The Geolocation API is used to locate a user's position.
 * HTML5 Geolocation 機能を提供するためのヘルパークラス。
 * Geolocation API は、ユーザの位置を特定するために使用されます。
 * (ol3 API)
 */
 projection: view.getProjection(),
 /** projection
  * The projection the position is reported in.
  * 位置が報告されている投影。(ol3 API)
  */
 /** getProjection()
  * Get the projection associated with the position.
  * 位置をともなった投影を取得します。(ol3 API)
  */
 trackingOptions: {
 /** trackingOptions
  * Tracking options. See http://www.w3.org/TR/
  * geolocation-API/#position_options_interface.(ol3 API)
  */
  maximumAge: 10000,
  /** maximumAge
   * The maximumAge attribute indicates that the application 
   * is willing to accept a cached position whose age is no 
   * greater than the specified time in milliseconds.
   * maximumAge 属性は、アプリケーションが、その寿命をミリ秒単位
   * で指定された時間よりも大きくない、キャッシュされた位置を受け
   * 入れることを示しています。
   * (http://www.w3.org/TR/geolocation-API/
   * #position_options_interface) 
   * (ページ下部も参照してください。)
   */
  enableHighAccuracy: true,
  /** enableHighAccuracy
   * The enableHighAccuracy attribute provides a hint that 
   * the application would like to receive the best possible 
   * results.
   * enableHighAccuracy 属性は、アプリケーションが可能な限り最
   * 高の結果を受信したいというヒントを提供します。 
   * (http://www.w3.org/TR/geolocation-API/
   * #position_options_interface) 
   * (ページ下部も参照してください。)
   */
  timeout: 600000
  /** timeout
   * The timeout attribute denotes the maximum length of time 
   * (expressed in milliseconds) that is allowed to pass from 
   * the call to getCurrentPosition() or watchPosition() 
   * until the corresponding successCallback is invoked. 
   * timeout 属性は、対応する successCallback が呼び出されるま
   * で、getCurrentPosition()もしくは watchPosition()の呼
   * び出しから渡される(ミリ秒単位で表される)時間の最大長さ
   * を示します。(http://www.w3.org/TR/geolocation-API/
   * #position_options_interface) 
   * (ページ下部も参照してください。)
   */
 }
}));
var deltaMean = 500; // the geolocation sampling period mean in ms
// Listen to position changes
geolocation.on('change', function(evt) {
/** on
 * Listen for a certain type of event.
 * あるタイプのイベントをリッスンします。(ol3 API)
 */
 var position = geolocation.getPosition();
 /** getPosition()
  * Get the position of the device.
  * デバイスの位置を取得します。(ol3 API)
  * Returns:      The current position of the device 
  * reported in the current projection.
  */
 var accuracy = geolocation.getAccuracy();
 /** getAccuracy()
  * Get the accuracy of the position in meters.
  * メートル単位で位置の精度を取得します。
  * Return: The accuracy of the position measurement 
  * in meters.(ol3 API)
  */
 var heading = geolocation.getHeading() || 0;
 /** getHeading()
  * Get the heading as radians clockwise from North.
  * 北からラジアン時計回りとして方角を取得します。
  * Return: The heading of the device in radians from 
  * north.(ol3 API)
  */
 var speed = geolocation.getSpeed() || 0;
 /** getSpeed()
  * Get the speed in meters per second.
  * メートル毎秒で速度を取得します。
  * Return: The instantaneous speed of the device in 
  * meters per second.(ol3 API)
  */
 var m = Date.now();
 /** Date.now()
  * UTC(協定世界時)での 1970 年 1 月 1 日 00 時 00 分 00 秒 
  * から現在までの経過ミリ秒を数値で返します。
  * (MDN[https://developer.mozilla.org/ja/docs/Web/
  * JavaScript/Reference/Global_Objects/Date/now])
  */
 addPosition(position, heading, m, speed);
 var coords = positions.getCoordinates();
 /** getCoordinates()
  * Returns: Coordinates.(ol3 API)
  */
 var len = coords.length;
 if (len >= 2) {
  deltaMean = (coords[len - 1][3] - coords[0][3]) / (len - 1);
 }
 var html = [
  'Position: ' + position[0].toFixed(2) + ', ' + position[1].toFixed(2),
  /** Number.prototype.toFixed()
   * The toFixed() method formats a number using fixed-point 
   * notation.
   * toFixed() メソッドは、固定小数点表記を使用して数値をフォー
   * マットします。
   * (MDN[https://developer.mozilla.org/en-US/docs/Web/
   * JavaScript/Reference/Global_Objects/Number/toFixed])
   */
  'Accuracy: ' + accuracy,
  'Heading: ' + Math.round(radToDeg(heading)) + '°',
  /** Math.round()
   * 引数として与えた数を四捨五入して、最も近似の整数を返します。
   * (MDN[https://developer.mozilla.org/ja/docs/Web/
   * JavaScript/Reference/Global_Objects/Math/round])
   */
  'Speed: ' + (speed * 3.6).toFixed(1) + ' km/h',
  'Delta: ' + Math.round(deltaMean) + 'ms'
 ].join('<br />');
 /** Array.join
  * 配列の全ての要素を繋いで文字列にします。
  * (MDN [https://developer.mozilla.org/ja/docs/Web/
  * JavaScript/Reference/Global_Objects/Array/join])
  */
 document.getElementById('info').innerHTML = html;
 /** element.innerHTML
  * innerHTML は、与えられた要素に含まれる全てのマークアップ
  * と内容を設定または取得します。
  * (MDN[https://developer.mozilla.org/ja/docs/Web/
  * API/element.innerHTML])
  */
});
geolocation.on('error', function() {
  alert('geolocation error');
  // FIXME we should remove the coordinates in positions
});
// convert radians to degrees
function radToDeg(rad) {
 return rad * 360 / (Math.PI * 2);
 /** Math.PI()
  * 円周率。約 3.14159 です。
  * (MDN[https://developer.mozilla.org/ja/docs/Web
  * /JavaScript/Reference/Global_Objects/Math/PI])
  */
}
// convert degrees to radians
function degToRad(deg) {
 return deg * Math.PI * 2 / 360;
}
// modulo for negative values
function mod(n) {
 return ((n % (2 * Math.PI)) + (2 * Math.PI)) % (2 * Math.PI);
}
function addPosition(position, heading, m, speed) {
 var x = position[0];
 var y = position[1];
 var fCoords = positions.getCoordinates();
 var previous = fCoords[fCoords.length - 1];
 var prevHeading = previous && previous[2];
 if (prevHeading) {
  var headingDiff = heading - mod(prevHeading);

  // force the rotation change to be less than 180°
  if (Math.abs(headingDiff) > Math.PI) {
  /** Math.abs()
   * 引数として与えた数の絶対値を返します。
   * https://developer.mozilla.org/ja/docs/Web/JavaScript/
   * Reference/Global_Objects/Math/abs
   */
   var sign = (headingDiff >= 0) ? 1 : -1;
   /** 条件演算子 condition ? expr1 : expr2 
    * condition: true か false かを評価する条件文です。
    * expr1, expr2: 各々の値の場合に実行する式です。
    * condition が true の場合、演算子は expr1 の値を選択します。
    * そうでない場合は expr2 の値を選択します。
    * (MDN[https://developer.mozilla.org/ja/docs/Web/
    * JavaScript/Guide/Expressions_and_Operators])
    */
   headingDiff = - sign * (2 * Math.PI - Math.abs(headingDiff));
  }
  heading = prevHeading + headingDiff;
 }
 positions.appendCoordinate([x, y, heading, m]);
 /** appendCoordinate()
  * appendCoordinate(coordinates) [Type: ol.Coordinate, 
  * Description: Coordinate](ol3 API)
  */
 // only keep the 20 last coordinates
 positions.setCoordinates(positions.getCoordinates().slice(-20));
 /** setCoordinates()
  * setCoordinates(coordinates) [Type: ol.Coordinate, 
  * Description: Coordinates](ol3 API)
  */
 /** Array.prototype.slice()
  * The slice() method returns a shallow copy of a portion
  * of an array into a new array object.
  * slice()メソッドは、配列の一部の簡易コピーを新しい配列オブジェ
  * クトに返します。
  * (MDN[https://developer.mozilla.org/ja/docs/Web/
  * JavaScript/Reference/Global_Objects/Array/slice])
  */
 // FIXME use speed instead
 if (heading && speed) {
  // markerEl.src = 'data/geolocation_marker_heading.png';
  markerEl.src = 'v3.4.0/examples/data/geolocation_marker_heading.png';
 } else {
  // markerEl.src = 'data/geolocation_marker.png';
  markerEl.src = 'v3.4.0/examples/data/geolocation_marker.png';
 }
}
var previousM = 0;
// change center and rotation before render
map.beforeRender(function(map, frameState) {
/** beforeRender()
 * Add functions to be called before rendering. 
 * This can be used for attaching animations before 
 * updating the map's view. The ol.animation namespace 
 * provides several static methods for creating 
 * prerender functions.
 * レンダリングの前に呼び出される関数を追加します。これは、
 * マップのビューを更新する前にアニメーションを取り付ける
 * ために使用することができます。 ol.animation名前空間は、
 * 事前レンダリング機能を作成するためのいくつかの静的メソッ
 * ドを提供します。
 * (ol3 API[説明は Stable Only のチェックを外すと表示])
 */
/** frameState
 * olx.FrameState{Object}
 * properties:
 * [Name] -[Type]
 * pixelRatio - number
 * time - number
 * viewState - olx.viewState
 * (ol3 API[説明は Stable Only のチェックを外すと表示])
 */
 if (frameState !== null) {
  // use sampling period to get a smooth transition
  var m = frameState.time - deltaMean * 1.5;
  m = Math.max(m, previousM);
  /** Math.max() 
   * 引数として与えた複数の数の中で最大の数を返します。
   * (MDN [https://developer.mozilla.org/ja/docs/Web/
   * JavaScript/Reference/Global_Objects/Math/max])
   */
  previousM = m;
  // interpolate position along positions LineString
  var c = positions.getCoordinateAtM(m, true);
  /** getCoordinateAtM()
   * Returns the coordinate at m using linear interpolation, 
   * or null if no such coordinate exists.
   * 線形補間を使用する m で座標を、または、そのような座標が存在
   * しない場合は null を返します。(ol3 API)
   */
  var view = frameState.viewState;
  /** viewState
   * olx.viewState
   * properties:
   * [Name] -[Type]
   * center - ol.Coordinate
   * projection - ol.proj.Projection
   * resolution - number
   * rotation - number
   * (ol3 API[説明は Stable Only のチェックを外すと表示])
   */
  if (c) {
   view.center = getCenterWithHeading(c, -c[2], view.resolution);
   view.rotation = -c[2];
   marker.setPosition(c);
   /** setPosition(position)
    * Set the position for this overlay. If the position is 
    * undefined the overlay is hidden.
    * このオーバーレイの位置を設定します。位置が定義されていない
    * 場合、オーバーレイは表示されません。(ol3 API)
    */
  }
 }
 return true; // Force animation to continue
});
/** recenters the view by putting the given coordinates at 
 * 3/4 from the top or the screen
 * 上部、または、スクリーンから4分の3に、与えられた座標を配置
 * することによってビューを中央に再位置づけします。(ol3 API)
 */
function getCenterWithHeading(position, rotation, resolution) {
 var size = map.getSize();
 /** getSize()
  * Get the size of this map.
  * Returns: The size in pixels of the map in the DOM.
  * マップのサイズを取得。(ol3 API)
  */
 var height = size[1];
 return [
  position[0] - Math.sin(rotation) * height * resolution * 1 / 4,
  position[1] + Math.cos(rotation) * height * resolution * 1 / 4
 ];
}
// postcompose callback
function render() {
 map.render();
 /** render()
  * Requests a render frame; rendering will effectively occur
  * at the next browser animation frame.
  * レンダーフレームをを要求します。すなわち、レンダリングは、
  * 次のブラウザのアニメーションフレームで、効果的に発生します。
  * (ol3 API)
  */
}
// geolocate device
var geolocateBtn = document.getElementById('geolocate');
geolocateBtn.addEventListener('click', function() {
/** EventTarget.addEventListener
 * addEventListener は、 1 つのイベントターゲットにイベント 
 * リスナーを1つ登録します。イベントターゲットは、ドキュメント
 * 上の単一のノード、ドキュメント自身、ウィンドウ、あるいは、
 * XMLHttpRequest です。
 *(MDN[https://developer.mozilla.org/ja/docs/Web/API/
 * EventTarget.addEventListener])
 */
 geolocation.setTracking(true); // Start position tracking
 /** setTracking(tracking)
  * Enable or disable tracking of DeviceOrientation events.
  * DeviceOrientation イベントのトラッキングを有効または無効
  * にします。
  * Name: tracking, Type: boolean, Description:
  * The status of tracking changes to alpha, beta and gamma. 
  * If true, changes are tracked and reported immediately.
  * トラッキングのステータスはα、βおよびγに変わります。 true の
  * 場合、変更はすぐにトラッキングされ、報告されます。
  * (ol3 API[説明は Stable Only のチェックを外すと表示])
  */
  map.on('postcompose', render);
  map.render();

  disableButtons();
}, false);
// simulate device move
var simulationData;
// $.getJSON('data/geolocation-orientation.json', function(data) {
$.getJSON('v3.4.0/examples/data/geolocation-orientation.json', function(data) {
/** jQuery.getJSON()
 * Load JSON-encoded data from the server using a GET HTTP 
 * request.
 * GET HTTP リクエストを使用してサーバからの JSON-encoded データ
 * をロードします。
 * (jQuery[http://api.jquery.com/jquery.getjson/])
 */
 simulationData = data.data;
});
var simulateBtn = document.getElementById('simulate');
simulateBtn.addEventListener('click', function() {
 var coordinates = simulationData;
 var first = coordinates.shift();
 /** Array.prototype.shift()
  * 配列から最初の要素を取り除き、その要素を返します。このメソッ
  * ドは配列の長さを変えます。
  * (MDN[https://developer.mozilla.org/ja/docs/Web/
  * JavaScript/Reference/Global_Objects/Array/shift])
  */
 simulatePositionChange(first);

 var prevDate = first.timestamp;
 function geolocate() {
  var position = coordinates.shift();
  if (!position) {
   return;
  }
  var newDate = position.timestamp;
  simulatePositionChange(position);
  window.setTimeout(function() {
  /** setTimeout(func, dylay)
   * 指定された遅延の後に、コードの断片または関数を実行します。
   * func : delay ミリ秒後に実行したい関数。
   * delay : 関数呼び出しを遅延させるミリ秒(1/1000 秒)。
   * (MDN[https://developer.mozilla.org/ja/docs/Web/
   * API/Window/setTimeout])
   */
   prevDate = newDate;
   geolocate();
  }, (newDate - prevDate) / 0.5);
 }
 geolocate();
 map.on('postcompose', render);
 /** postcompose イベント
  * レイヤを描画した後に発生するイベント。
  * (「Layer spy example」参照)
  */
 map.render();

 disableButtons();
}, false);
function simulatePositionChange(position) {
 var coords = position.coords;
 geolocation.set('accuracy', coords.accuracy);
 /** set(key, value)
  * Sets a value.
  * (ol3 API[説明は Stable Only のチェックを外すと表示])
  */
 geolocation.set('heading', degToRad(coords.heading));
 var position_ = [coords.longitude, coords.latitude];
 var projectedPosition = ol.proj.transform(position_, 'EPSG:4326',
  'EPSG:3857');
 geolocation.set('position', projectedPosition);
 geolocation.set('speed', coords.speed);
 geolocation.changed();
 /** changed() 
  * Increases the revision counter and disptches a 'change' 
  * event.
  * リビジョンカウンタを増加し、'change' イベントを送出します。
  * (ol3 API[説明は Stable Only のチェックを外すと表示])
  */
}

function disableButtons() {
 geolocateBtn.disabled = 'disabled';
 simulateBtn.disabled = 'disabled';
}




maximumAge

The maximumAge attribute indicates that the application is willing to accept a cached position whose age is no greater than the specified time in milliseconds. If maximumAge is set to 0, the implementation must immediately attempt to acquire a new position object. Setting the maximumAge to Infinity must determine the implementation to return a cached position regardless of its age. If an implementation does not have a cached position available whose age is no greater than the specified maximumAge, then it must acquire a new position object. In case of a watchPosition(), the maximumAge refers to the first position object returned by the implementation.

maximumAge 属性は、アプリケーションが、その寿命をミリ秒単位で指定された時間よりも大きくない、キャッシュされた位置を受け入れることを示しています。maximumAge を 0 に設定した場合、実装は直ちに新しい位置オブジェクトを取得しなければならなりません。maximumAge を Infinity に設定することは、その寿命に関係なく、キャッシュされた位置を返すように実装を決定するしなければならなりません。実装が、指定された maximumAge より大きくない寿命の利用可能なキャッシュされた位置を持っていない場合、それは新しい位置オブジェクトを取得しなければならなりません。 watchPosition()の場合は、maximumAge は、実装によって返される最初の位置オブジェクトを参照します。


enableHighAccuracy

The enableHighAccuracy attribute provides a hint that the application would like to receive the best possible results. This may result in slower response times or increased power consumption. The user might also deny this capability, or the device might not be able to provide more accurate results than if the flag wasn't specified. The intended purpose of this attribute is to allow applications to inform the implementation that they do not require high accuracy geolocation fixes and, therefore, the implementation can avoid using geolocation providers that consume a significant amount of power (e.g. GPS). This is especially useful for applications running on battery-powered devices, such as mobile phones.

enableHighAccuracy 属性は、アプリケーションが可能な限り最高の結果を受信したいというヒントを提供します。これは、遅い応答時間や消費電力の増大をもたらします。フラグが指定されていない場合、ユーザーがこの能力を否定するか、または、デバイスがより正確な結果を提供することができない場合があります。この属性の本来の目的は、アプリケーションが、高精度な位置情報の修正を必要としない実装、したがって、実装がかなりの量の電力(例えば、GPS)を消費するジオロケーションプロバイダの使用を避けることができる、を通知できるようにすることです。これは携帯電話などのバッテリ駆動デバイス上で実行されるアプリケーションのために特に有用です。


timeout

The timeout attribute denotes the maximum length of time (expressed in milliseconds) that is allowed to pass from the call to getCurrentPosition() or watchPosition() until the corresponding successCallback is invoked. If the implementation is unable to successfully acquire a new Position before the given timeout elapses, and no other errors have occurred in this interval, then the corresponding errorCallback must be invoked with a PositionError object whose code attribute is set to TIMEOUT. Note that the time that is spent obtaining the user permission is not included in the period covered by the timeout attribute. The timeout attribute only applies to the location acquisition operation.

timeout 属性は、対応する successCallback が呼び出されるまで、getCurrentPosition()もしくは watchPosition()の呼び出しから渡される(ミリ秒単位で表される)時間の最大長さを示します。実装が、与えられた timeout が経過する前に新しい Position を取得することができず、他のエラーがこの間隔で発生していない場合は、対応する errorCallback は、コード属性が TIMEOUT に設定されている PositionError オブジェクトで呼び出されなければなりません。ユーザー権限の取得に費やされる時間は timeout 属性の対象期間に含まれないことに注意してください。timeout 属性は、位置取得動作に適用されるだけです。


disabled Type: boolean

Indicates whether the element is disabled or not. If this attribute is set to true the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely as opposed to setting the value to false. Visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state.

要素が無効化されているかどうかを示します。この属性が true に設定されている場合は要素が無効になっています。無効化された要素は通常グレイ表示のテキストで描画されています。要素が無効になっている場合は、ユーザのアクションには応答せず、フォーカスが当てられず、コマンドイベントは発生しません。 要素は、しかしながら、まだマウスイベントに応答します。要素を有効にするには、値をfalseに設定することとは対照的に、完全にこの属性を削除します。 表示されるコントロールは、メニューおよびメニュー項目を除いて、追加の状態を更新する必要があるために、通常は属性に使用される disabled 属性を有します。

0 件のコメント: