LoginSignup
55
60

【Google MAP】名称から場所を検索・特定する

Last updated at Posted at 2019-06-07

Google Map API v3 名称から場所を検索・特定する

はじめに

  • Googleに限らずMapを扱うときには、まずは、その場所の緯度経度の情報が必要というのが基本ですが、やりたいことによっては緯度経度の情報がわからない場合もあります。
  • そんなときはGeocodingを使用します。(Geocoding:名称・地名・住所などの情報を、緯度経度の座標値に変換してくれる)

やりたいこと

  • 名称を検索ボックスに入れ、検索ボタンを押下すると、該当の場所にピンを立てる。
  • ピンに吹き出しをつけ、名称(google検索の結果へのリンクつき)、緯度経度、住所、画像検索へのリンクをいれる。

前提

  • Google Map API keyの取得

イメージ

 デモサイト

googleMap1.png

コード

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>Placeサーチ</title>
    <style>
      #header {
    	  background-color: darkblue;
    	  padding: 3px;
    	  width: 1195px;
          font-family: Meriyo UI;
          font-size: 14px;
    	  color: white;
      }
      #target {
        width: 1200px;
        height: 700px;
      }
    </style>
  </head>

  <body>
    <div id="header"><b>Google Maps - 場所検索</b></div>
    <div>施設名称検索 (例:マチュピチュ、万里の長城)</div>
    <input type="text" id="keyword"><button id="search">検索実行</button>
    <button id="clear">結果クリア</button>
    <div id="target"></div>

    <script src="https://maps.googleapis.com/maps/api/js?language=ja&region=JP&key=キーをセット&callback=initMap" async defer></script>

    <script>

      var map;
      var marker;
      var infoWindow;

      function initMap() {

        //マップ初期表示の位置設定
        var target = document.getElementById('target');
        var centerp = {lat: 37.67229496806523, lng: 137.88838989062504};

        //マップ表示
        map = new google.maps.Map(target, {
          center: centerp,
          zoom: 2,
        });

        // 検索実行ボタンが押下されたとき
        document.getElementById('search').addEventListener('click', function() {

          var place = document.getElementById('keyword').value;
          var geocoder = new google.maps.Geocoder();      // geocoderのコンストラクタ

          geocoder.geocode({
            address: place
          }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {

              var bounds = new google.maps.LatLngBounds();

              for (var i in results) {
                if (results[0].geometry) {
                  // 緯度経度を取得
                  var latlng = results[0].geometry.location;
                  // 住所を取得
                  var address = results[0].formatted_address;
                  // 検索結果地が含まれるように範囲を拡大
                  bounds.extend(latlng);
                  // マーカーのセット
                  setMarker(latlng);
                  // マーカーへの吹き出しの追加
                  setInfoW(place, latlng, address);
                  // マーカーにクリックイベントを追加
                  markerEvent();
                }
              }
            } else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
              alert("見つかりません");
            } else {
              console.log(status);
              alert("エラー発生");
            }
          });

        });

        // 結果クリアーボタン押下時
        document.getElementById('clear').addEventListener('click', function() {
          deleteMakers();
        });

      }

      // マーカーのセットを実施する
      function setMarker(setplace) {
        // 既にあるマーカーを削除
        deleteMakers();

        var iconUrl = 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png';
          marker = new google.maps.Marker({
            position: setplace,
            map: map,
            icon: iconUrl
          });
        }

        //マーカーを削除する
        function deleteMakers() {
          if(marker != null){
            marker.setMap(null);
          }
          marker = null;
        }

        // マーカーへの吹き出しの追加
        function setInfoW(place, latlng, address) {
          infoWindow = new google.maps.InfoWindow({
          content: "<a href='http://www.google.com/search?q=" + place + "' target='_blank'>" + place + "</a><br><br>" + latlng + "<br><br>" + address + "<br><br><a href='http://www.google.com/search?q=" + place + "&tbm=isch' target='_blank'>画像検索 by google</a>"
        });
      }

      // クリックイベント
      function markerEvent() {
        marker.addListener('click', function() {
          infoWindow.open(map, marker);
        });
      }

    </script>

  </body>
</html>

まとめ

  • Google Mapで「名称」はわかるけど、場所がわからない or なんとなくしかわならない場合に活用できるかと思います。
  • これを使用して、世界絶景ランキングの場所を自動でポイントすることを実施しました。

参考URL

55
60
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
55
60