0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

位置情報の取得を試みます。
色々方法はあるかと思いますが、jsで位置情報を取得できます。
単純にパソコン上で取得します。

位置情報取得方法

ブラウザのGeolocation APIを使うことで、ユーザーの許可を得て現在の位置情報(緯度、経度)を取得することができます。

<!DOCTYPE html>
<html>
<head>
    <title>Get Location</title>
</head>
<body>
    <button onclick="getLocation()">Get Location</button>
    <p id="location"></p>

    <script>
        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition, showError);
            } else {
                document.getElementById("location").innerHTML = "Geolocation is not supported by this browser.";
            }
        }

        function showPosition(position) {
            var lat = position.coords.latitude;
            var lon = position.coords.longitude;
            document.getElementById("location").innerHTML = "Latitude: " + lat + "<br>Longitude: " + lon;
        }

        function showError(error) {
            switch(error.code) {
                case error.PERMISSION_DENIED:
                    document.getElementById("location").innerHTML = "User denied the request for Geolocation."
                    break;
                case error.POSITION_UNAVAILABLE:
                    document.getElementById("location").innerHTML = "Location information is unavailable."
                    break;
                case error.TIMEOUT:
                    document.getElementById("location").innerHTML = "The request to get user location timed out."
                    break;
                case error.UNKNOWN_ERROR:
                    document.getElementById("location").innerHTML = "An unknown error occurred."
                    break;
            }
        }
    </script>
</body>
</html>

説明

  1. getLocation関数:

    • navigator.geolocationが利用可能かどうかをチェックします。
    • 利用可能な場合、getCurrentPositionメソッドを呼び出して現在の位置情報を取得します。
    • 位置情報の取得が成功すると、showPosition関数が呼び出され、緯度と経度が表示されます。
    • エラーが発生した場合は、showError関数が呼び出され、エラーメッセージが表示されます。
  2. showPosition関数:

    • 位置情報が成功すると呼び出され、position.coords.latitudeposition.coords.longitudeを使って緯度と経度を取得し、ページに表示します。
  3. showError関数:

    • 位置情報取得が失敗した場合のエラーメッセージを表示します。エラーコードに応じて適切なメッセージを表示します。

この方法を使うことで、JavaScriptだけでユーザーの位置情報を取得し、表示することができます。

おわりに

簡単にjavaScriptでライブラリーも必要なく取得できるということに最初気づけなかったのでメモりました。これを使えば、googleマップもどきの記録が出来そうです。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?