LoginSignup
5
6

More than 5 years have passed since last update.

郵便番号から住所と緯度経度取得

Last updated at Posted at 2017-05-28

郵便番号のフォーム

sample.html
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> 
<script src="https://maps.googleapis.com/maps/api/js?key={googleから取得したkey}"></script>
<script src="path/to/map.js"></script>
</head>
<body>
<label>郵便番号</label>
<input class="form-control" id="zip1" placeholder="000" name="zip1" type="text" value="">
<input class="form-control" id="zip2" placeholder="0000" name="zip2" type="text" value="">
</body>

Javascript

map.js
$(function(){
    $('#zip2').keyup(function() {

        if ($('#zip1').val().length != 3) {
            return false;
        }
        if ($('#zip2').val().length != 4) {
            return false;
        }

        var zip = $('#zip1').val() + $('#zip2').val();
        console.log(zip); // 1020071
        $.ajax({
          type : 'get',
          url : '//maps.googleapis.com/maps/api/geocode/json',
          crossDomain : true,
          dataType : 'json',
          data : {
            address : zip,
            language : 'ja',
            sensor : false
        },
        success : function(resp){
          if(resp.status == "OK"){
            var obj = resp.results[0].address_components;
            if (obj.length < 5) {
              return false;
            }

            var address = obj[3]['long_name'] + obj[2]['long_name'] + obj[1]['long_name'];
                  // console.log(address); // 東京都千代田区富士見
                  attrLatLngFromAddress(address);
            } else {
                  return false;
            }
          }
        });
    });

    function attrLatLngFromAddress(address){
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({'address': address}, function(results, status){
            if(status == google.maps.GeocoderStatus.OK) {
                var lat = results[0].geometry.location.lat();
                var lng = results[0].geometry.location.lng();
                // 小数点第六位以下を四捨五入した値を緯度経度にセット、小数点以下の値が第六位に満たない場合は0埋め

                console.log((Math.round(lat * 1000000) / 1000000).toFixed(6)); // 緯度
                console.log((Math.round(lng * 1000000) / 1000000).toFixed(6)); // 経度
            }
        });
    }
});
5
6
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
6