お問い合わせ

ブログ

これまでに経験してきたプロジェクトで気になる技術の情報を紹介していきます。

Vue3でMapboxを使用する - 空に太陽を反映編 -

okuda Okuda 2 years

「Vue3でMapboxを使用する - レイヤ、ソース編 -」で追加したskyレイヤをブラッシュアップ

suncalcというモジュールを使用することで以下のようなことがskyレイヤに表現できる

skyレイヤに太陽の位置を座標と年月日から割り出し表示
日の出、日没には朝焼け、夕焼けも表現して太陽も確認可能
空の明るさが設定日時に合わせて変化

太陽のいちを計算するモジュール suncalc をインストール

https://www.npmjs.com/package/suncalc

npm i suncalc

トップレベルに以下を追加してインポート

import SunCalc from 'suncalc';

空のレイヤをセットする

以下のように変更する

onMounted のなかの map on load イベントで空レイヤを追加

        // 空のレイヤをセット
        map.addLayer({
            'id': 'sky',
            'type': 'sky',
            'paint': {
                // 透明度
                'sky-opacity': [
                    'interpolate',
                    ['exponential', 0.1],
                    ['zoom'],
                    5,
                    0,
                    22,
                    1
                ],
                // 大気散乱用の空のレイヤー
                'sky-type': 'atmosphere',
                // 太陽の強度を光源として設定します(0-100、高い値は明るい空)
                'sky-atmosphere-sun-intensity': 5,
                // 太陽の位置を座標と時間で設定
                'sky-atmosphere-sun': getSunPosition(),
            }
        });

太陽の位置を計算するメソッドの追加

トップレベルに以下を追加

// 表示する時間、デフォルトで現在時を入力
const now = new Date();
// htmlに入寮句できる形に変更
now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
let displayTime = ref(now.toISOString().substr(0, 16));

//...

// 太陽の位置を時間から取得
const getSunPosition = (date = null) => {
    // 現在の座標を取得
    const center = map.getCenter();
    // 座標と年月日から太陽の位置を計算
    const sunPos = SunCalc.getPosition(
        date || Date.now(),
        center.lat,
        center.lng
    );
    // マップボックスに合わせる
    const sunAzimuth = 180 + (sunPos.azimuth * 180) / Math.PI;
    const sunAltitude = 90 - (sunPos.altitude * 180) / Math.PI;

    return [sunAzimuth, sunAltitude];
};

// 空のレイヤに太陽の位置をセット
const setSunPosition = () => {
    const targetTime = new Date(displayTime.value);

    // 時間から太陽の位置を取得
    const sunPosition = getSunPosition(targetTime);

    // 太陽の位置を更新
    map.setPaintProperty("sky", "sky-atmosphere-sun", sunPosition);
};

日時を変更できるように入力欄を追加

テンプレート内に時間設定を追加

<!-- 時間をセット -->
    <input type="datetime-local" v-model="displayTime" @change="setSunPosition" />
Vue3でMapboxを使用する - 空に太陽を反映編 - 2022-03-05 18:25:50

コメントはありません。

4251

お気軽に
お問い合わせください。

お問い合わせ
gomibako@aska-ltd.jp