≪ Today I learned.
RSS購読
    公開日
    タグ
    HTML
    著者
    ダーシノ

    geolocation要素による位置情報の取得方法

    Chrome 144以降で<geolocation>要素がサポートされた。

    JavaScriptのGeolocation APIよりも権限要求や位置情報取得の実装が簡略化された。Geolocation APIでは予期せぬタイミングで権限要求のダイアログが表示されたり、ブラウザがブロックしたり、ユーザー体験が阻害されるケースがあったが、<geolocation>要素ではユーザーの明示的な操作により開始されるので意図とタイミングが明確になった。

    <!-- 手動実行 -->
    <geolocation id="geo-manual">
      Fallback: Geolocation element is not supported
    </geolocation>
    
    <!-- 自動実行 -->
    <geolocation id="geo-auto" autolocate>
      Fallback: Geolocation element is not supported
    </geolocation>
    const geoManual = document.getElementById('geo-manual')
    const geoAuto = document.getElementById('geo-auto')
    
    function output(event) {
      console.log('タイムスタンプ', event.timeStamp)
      console.log('緯度', event.target.position.coords.latitude)
      console.log('経度', event.target.position.coords.longitude)
    }
    
    geoManual.onlocation = output
    geoAuto.onlocation = output

    autolocate属性を指定すると、権限がある場合は自動的に位置情報の取得ができる。

    デモ

    手動で位置情報を取得

    Geolocation element is not supported

    自動で位置情報を取得

    Geolocation element is not supported

    Output:

    位置情報取得の権限を許可してください