LoginSignup
5
7

More than 3 years have passed since last update.

位置情報を取得するAPIを解説してみた

Posted at

完成形はこちらになります↓


See the Pen
NVXQYE
by Yuji Yakena (@yuji-yakena)
on CodePen.


1.まずは簡単なhtmlを作成

index.html
<!DOCTYP html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Geolocation</title>
</head>
<body>
  <h1>位置情報サンプル</h1>
  <button onclick="getPosition();">位置情報を取得する</button>
  <script src="app.js"></script>
</body>
</html>

ポイントは2箇所あります

<button onclick="getPosition();">
ボタンをクリックすることで、jsファイルで定義したgetPosition()メソッドを呼び出して実行します。

<script src="app.js"></script>
jsファイルを読み込みます。

2.jsファイルにてメソッドの定義

app.js
function getPosition(){
  navigator.geolocation.getCurrentPosition(
    function(position){
      let nowLatitude = position.coords.latitude;
      let nowLongitude = position.coords.longitude;

      alert("緯度:"+nowLatitude+"、経度"+nowLongitude);
    },
  );
}

function 関数名()
任意の関数名を定義し、{ }内に実際の動作を記述します。
html側では、この関数名で呼び出します。

navigator.geolocation.getCurrentPosition()
デバイスの現在位置を取得するメソッドです。
引数として、success・error が使用されます。

メソッドの構文・定義など詳細はこちら↓
https://developer.mozilla.org/ja/docs/Web/API/Geolocation/getCurrentPosition

function(position)
先程引用した位置取得メソッドの引数として認識されます。

let 変数名
任意の変数を定義して、緯度・経度プロパティを格納します。

position.coords.latitude
position.coords.longitude
それぞれ緯度・軽度プロパティとして取得できます。

alert(引数)
先程定義した変数をアラート表示します。

まとめ

APIを理解する最初のステップとして、参考になれれば幸いです。。

参考元

MDN JavaScript リファレンス
https://developer.mozilla.org/ja/docs/Web/JavaScript

5
7
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
5
7