Robinit

IT関連メモ

郵便番号検索 Webアプリを作る(2)

郵便番号検索 Webアプリを作る(1)の続き
ソースコードの各処理の内容をみていく

HTML Head

<meta charset=" ">

について、「charset属性」は、HTML5から単独で使えるようになった属性
文字コードは、「Shift_JIS」「UTF-8」などがありますが、HTML5から、UTF-8 を使用することが推奨されている
理由はWin、MacLinuxUnix、どんな OSでもOKなのと、
2バイト文字(漢字や仮名などの日本語・中国語・ハングル・アラビア語など)も含めた、世界中の言語の文字を表示できるから

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

でbootstrapのCSSを指定し読み込む

<style type="text/css">

以降で、HTML文書にCSSを適用する

<head>
    <meta charset="UTF-8">
    <title>郵便番号検索</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <style type="text/css">
        .container {
            text-align: center;
            margin-top: 100px;
            width: 450px;
        }
        .result {
            margin-top: 20px;
        }
    </style>
</head>

HTML Body

Bootstrapで基本的なformを作るために

<div class="form-group">

<input type~  class="form-control" 

を指定し、レイアウトを利用する

    <div class="container">
        <h1>郵便番号検索</h1>
        <div class="form-group">
            <label for="exampleInputText">住所を入力してください</label>
            <input type="text" id="city" class="form-control" placeholder="ex. 大阪府大阪市北区小松原町">
        </div>
        <button class="btn btn-primary" id="btn">検索</button>
        <div class="result" id="str"></div>
    </div>

Google Maps Geocoding API

検索ボタンが押下されたら、
入力された住所の郵便番号を取得する処理を行う
郵便番号の取得には、Google Maps Geocoding API を利用する。

事前準備として以下サイトでAPI Keyを取得する。
developers.google.com

キーの取得のページに遷移する
f:id:wonder_three:20180208002243p:plain

API Keyを取得したらメモする

次に住所から郵便番号を取得するために以下のAPIを使う
https://maps.googleapis.com/maps/api/geocode/json?address=[住所]&key=[取得したAPI Key]

例えば、住所に「千代田区千代田」を入れてAPIを実行
[https://maps.googleapis.com/maps/api/geocode/json?address=千代田区千代田&key=[取得したAPI Key]

結果として以下のJSONが取得できる

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "千代田",
               "short_name" : "千代田",
               "types" : [ "political", "sublocality", "sublocality_level_2" ]
            },
            {
               "long_name" : "",
               "short_name" : "",
               "types" : [ "political", "sublocality", "sublocality_level_4" ]
            },
            {
               "long_name" : "千代田区",
               "short_name" : "千代田区",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "東京都",
               "short_name" : "東京都",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "日本",
               "short_name" : "JP",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "100-0001",
               "short_name" : "100-0001",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "日本、〒100-0001 東京都千代田区千代田1",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 35.6905143,
                  "lng" : 139.7614146
               },
               "southwest" : {
                  "lat" : 35.6773769,
                  "lng" : 139.7443137
               }
            },
            "location" : {
               "lat" : 35.6838012,
               "lng" : 139.7539454
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 35.6905143,
                  "lng" : 139.7614146
               },
               "southwest" : {
                  "lat" : 35.6773769,
                  "lng" : 139.7443137
               }
            }
         },
         "place_id" : "ChIJ4bzvNguMGGARUXRpAo8Oi6s",
         "types" : [ "political", "sublocality", "sublocality_level_2" ]
      }
   ],
   "status" : "OK"
}

取得した値のそれぞれの値はデベロッパー ガイドを参考にすればよいが、
今回は郵便番号なので、"postal_code"を利用する

入力された住所から郵便番号を取得し結果を表示する

jQueryAJAXメソッドを使って「Google Maps Geocoding API」をよびだすので、
jQueryのライブラリを読み込む

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

以下で検索ボタンがクリックされたときのイベント処理を実装する

    <script type="application/javascript">
        var postalCode = "";
        var btn = document.getElementById('btn');
        btn.addEventListener('click', function() {

住所が入力されていなければalert()で警告表示し結果表示部分にも、
「郵便番号が見つかりません。」という文言を表示する。
その際、Bootstrapのalertsのレイアウトを使って表示する
Alerts · Bootstrap

            var city = document.getElementById('city');
            if (city.value == "") {
                alert("住所を入力してください");
                document.getElementById("str").innerHTML = "<div class=\"alert alert-primary\" role=\"alert\">郵便番号が見つかりません。</div>";

Google Maps Geocoding APIの第1引数 addressに入力された住所、第2引数に取得したAPI Keyを指定し、
ajaxメソッドを利用してAPIをよび出す

APIの呼び出しが成功すれば、
$.each()をつかい、取得したデータにpostal_codeがないか?検索する
postal_codeがあれば、郵便番号を表示する

            } else {
                const API_KEY = xxxxxxxxxxx; //個人のAPI key
                var url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + city.value + "&key=" + API_KEY;
                $.ajax({
                    url: url,
                    type: "GET",
                    success: function(data) {
                        postalCode = "";
                        $.each(data['results'][0]['address_components'], function(key, value) {
                            if (value["types"][0] == "postal_code") {
                                postalCode = value["long_name"];
                            }
                        })
                        if (postalCode) {
                            document.getElementById("str").innerHTML = "<div class=\"alert alert-primary\" role=\"alert\">郵便番号は、" + postalCode + "です。</div>";
                        } else {
                            document.getElementById("str").innerHTML = "<div class=\"alert alert-primary\" role=\"alert\">郵便番号が見つかりません。</div>";
                        }
                    }
                })
            }
        })
    </script>

※$.each() は配列やハッシュに対して繰り返し処理を行うことができる
$.each() は以下のように記述する。

$.each(対象のオブジェクト, function(index, val) {
  繰り返し実行する処理
});)

配列 array に対して繰り返し処理を行う場合は、以下のように記載する。

array = ["Apple", "Orange", "Grape"];
$.each(array, function(index, val) {
  $('ul').append("<li>" + index + ":" + val + "</li>");
});