LoginSignup
3
2

More than 1 year has passed since last update.

ブラウザでGeoLocation APIを使ってみる

Last updated at Posted at 2021-09-23

今回は、ブラウザ(Chrome)からシステム側のGPS情報を取得して、それを表示するサンプルプログラムを載せました。
まず、下記の2つのメソッドの違いですが、単発で位置情報を取得する場合は1番でよいのですが、電車、自動車などで連続的に位置情報を取得したい場合は、圧倒的に2番のほうが優れています。

  1. Geolocation.getCurrentPosition()
  2. Geolocation.watchPosition()

したがって、今回のサンプルプログラムは、単発的に位置情報をブラウザから取得するものとなっています。

(補足)このプログラムを普通に動作させようとすると、多くの方はPC上のVisual Studio Codeで新規htmlファイルを作って、そこにコピペして、左側に表示されているファイルツリー上でそのファイルを選択した状態で、マウスの右ボタンでOpen with Live Serverを選択して表示すると思いますが、ご存じの通り、PC(Mac)にはGPSが入っていませんので、全然面白くありません。

そこで、実際にスマホで試してみる際は、もし、普段使っているGoogle Cloud PlatformやAWSなどがあれば、一旦そこでNode.JS + Expressのサーバーを立てて、下記のコードをhtmlファイルとしてコピペしましょう。

ちなみに、このようなミニアプリをちゃちゃっと作って動作させてみたい場合ですが、AWSのAPI Gateway, Lambda, DynamoDB, S3, Cognitoの組み合わせは大変おすすめです。
API GatewayとLambdaで、Node.JS + Expressのミニサーバーを立てることができますので、そこで生成されたURLリンク(https://xxxxx)を使って、今回のミニアプリをスマホのブラウザで動作させることが可能です。

もし、AWSのSDKのインストールや、クレデンシャルの設定などがすでになされている場合(環境設定が終わっている場合)ですが、まったく新規のミニサーバーを作成(新規のURLを生成して、Expressサーバーとして稼働)する時間は、10分 ~ 20分程度です。

latitude(lat) ... 緯度
longitutde(lng) ... 経度
accuracy(acc) ... 緯度経度の精度
altitude(alt) ... 高度
altitude Accuracy(altAcc) ... 高度の精度
heading(heading) ... 向き(東西南北)
speed(speed) ... 速度
timestamp(timestamp) ... UNIX時間

Geolocation.getCurrentPosition()、Geolocation.watchPosition()については、こちらに載っていますので、ご参照願います。


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <title>Get Location Data</title>

    <style>
    .output{
        margin-left: 10px;
        font-size: 16px;
    }
    .flex-container {
        display: flex;
        justify-content: center;
    }
    .flex-container > button {
        width:160px;
        height:40px;
        margin: 0px 15px 0px 15px;
        font-size: 17px;
    }
    </style>

</head>

<body>
    <p class='output'>Click the button to get your coordinates.</p>
    <div class="flex-container">
        <button class="center waves-effect waves-light btn blue" onclick="spot()">Get Location</button>
    </div>

    <p id="demo"></p>

    <div class="output">
        <div id="lat"></div>
        <div id="lng"></div>
        <div id="acc"></div>
        <div id="alt"></div>
        <div id="altAcc"></div>
        <div id="heading"></div>
        <div id="speed"></div>
        <div id="timestamp"></div>
    </div>

<script>

var options = {
  enableHighAccuracy: true,
  timeout: 1000,
  maximumAge: 0
};

function getLocationPromise () {
    return new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject, options);
    });
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

async function spot (){
    console.time('time to get location');

    const position = await getLocationPromise();
    console.log('position:',position);

    document.getElementById("lat").innerHTML = 'Lat: ' + position.coords.latitude;
    document.getElementById("lng").innerHTML = 'Lng: ' + position.coords.longitude;
    document.getElementById("acc").innerHTML = 'Accuracy of position: ' + position.coords.accuracy;
    document.getElementById("alt").innerHTML = 'Altitude: ' + position.coords.altitude;
    document.getElementById("altAcc").innerHTML = 'Altitude Accuracy: ' + position.coords.altitudeAccuracy;
    document.getElementById("heading").innerHTML = 'Heading: ' + position.coords.heading;
    document.getElementById("speed").innerHTML = 'Speed: ' + position.coords.speed;
    document.getElementById("timestamp").innerHTML = 'Timestamp: ' + position.timestamp;

    console.timeEnd('time to get location');
}

</script>
</body>
</html>

3
2
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
3
2