LoginSignup
1
1

More than 3 years have passed since last update.

HTML Geolocation APIとGoogle Map Geocoding APIを実行する

Last updated at Posted at 2019-08-23

位置情報の取り扱いについて調べたのでまとめました。
Google Map Geocoding APIを実行するためには、コンソールからApi keyを発行する必要があります。

<!DOCTYPE html>
<html lang="ja">
  <head>
    <title>Hello!</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style type="text/css">
      body {
        font-family: "Benton Sans", "Helvetica Neue", helvetica, arial, sans-serif;
        margin: 2em;
      }
      h1 {
        font-style: italic;
        color: #373fff;
      }
    </style>
    <script type="text/javascript" defer>
      if (navigator.geolocation) {
        //Geolocation APIを利用できる環境向けの処理

        getPotision().then(
          position => {
            showPotision(position)
            showLocation(position)
          },
          error => {showError(error)}    
        )

      } else {
        //Geolocation APIを利用できない環境向けの処理
        window.alert("Geolocation APIが利用できない環境です")
      }

      function getPotision() {
        // getCurretnPositionを待つのでPromise化してます
        // 元々は getCurrentPosition(successCallback, errorCallback, options)
        return new Promise((resolve, reject) => {
          navigator.geolocation.getCurrentPosition(resolve, reject, {"enableHighAccuracy": true})
        })
      }

      function showLocation(potision){

        // Googoe Geolocation API の呼び出し
        // 緯度・軽度から住所の情報を引いてくれます。住所の候補は複数返ります
        const key = "YourKey"
        let latitude = potision.coords.latitude
        let longitude = potision.coords.longitude
        let url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${key}`
        let request = new Request(url);
        fetch(request)
          .then(response => {
            if (response.status === 200) {
              return response.json();
            } else {
              throw new Error('Something went wrong on api server!');
            }
          })
          .then(response => {
            console.log("Geolocation API response", response);

            response.results.forEach(item => {
              console.log(item.formatted_address);
              var newLi = document.createElement("li"); 
              newLi.appendChild(document.createTextNode(item.formatted_address))
              var targetElement = document.getElementById("location_result")
              targetElement.appendChild(newLi);
            });


        }).catch(error => {
            console.log(error);
          });
      }

      function showPotision(position) {
        console.log("Got potision", position);
        let targetElement = document.getElementById("potision_result")


        let text = "緯度: " + position.coords.latitude
        let newLi = document.createElement("li")
        newLi.appendChild(document.createTextNode(text))
        targetElement.appendChild(newLi)

        text = "経度: " + position.coords.longitude
        newLi = document.createElement("li")
        newLi.appendChild(document.createTextNode(text))
        targetElement.appendChild(newLi)

        text = "高度: " + position.coords.accuracy
        newLi = document.createElement("li")
        newLi.appendChild(document.createTextNode(text))
        targetElement.appendChild(newLi)

        text = "緯度・経度の誤差: " + position.coords.altitudeAccuracy
        newLi = document.createElement("li")
        newLi.appendChild(document.createTextNode(text))
        targetElement.appendChild(newLi)

        text = "方角: " + position.coords.heading
        newLi = document.createElement("li")
        newLi.appendChild(document.createTextNode(text))
        targetElement.appendChild(newLi)

        text = "速度: " + position.coords.speed
        newLi = document.createElement("li")
        newLi.appendChild(document.createTextNode(text))
        targetElement.appendChild(newLi)
      }

      function showError(error) {
        var err_msg = "";
        switch(error.code)
        {
          case 1:
            err_msg = "位置情報の利用が許可されていません";
            break;
          case 2:
            err_msg = "デバイスの位置が判定できません";
            break;
          case 3:
            err_msg = "タイムアウトしました";
            break;
        }
        document.getElementById("potision_result").innerHTML = err_msg;
      }      
    </script>
  </head>  
  <body>

    <h2>ここに現在位置が表示されます</h2>
    <ul id="potision_result"></ul>

    <h2>ここに現在住所が表示されます</h2>
    <ol id="location_result"></ol>

  </body>
</html>
1
1
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
1
1