LoginSignup
1
1

More than 5 years have passed since last update.

(Google Maps JavaScript API )ボタンのオンオフでイベントの切り替え

Posted at

この記事にボタンでオンオフできるようにしただけですが,ボタンで切り替える例が他に見られなかったので書きました.もっとスマートな書き方がありそうな気がします.

<!DOCTYPE html>
<html lang="ja">
<head>
  <title>Test Map</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta charset="utf-8">
  <style>
    html, body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    #map {
      height: 80%;
      width: 80%;
    }
  </style>
</head>
<body>
  <div id="map"></div>
  <button type="button" onClick="addEvent();">ここを押してね!</button>
  <ul id="latlng" style="display:none;">
    <li>lat: <span id="lat"></span></li>
    <li>lng: <span id="lng"></span></li>
  </ul>
  <script>
    var map;

    // マップの初期化
    function initMap() {  
      map = new google.maps.Map(document.getElementById('map'), {
        zoom: 13,
        center: {lat: 36.38992, lng: 139.06065}
      });
    }

    // イベントの追加と表示の切り替え
    function addEvent() {
      if (document.getElementById("latlng").style.display == "none") {
        // 緯度経度を表示
        document.getElementById("latlng").style.display = "block";
        // クリックイベントを追加
        map.addListener('click', function(e) {
          getClickLatLng(e.latLng, map);
        });  
      } else {
        // 緯度経度を非表示
        document.getElementById("latlng").style.display = "none";
        // クリックイベントを削除
        google.maps.event.clearListeners(map, 'click');
      }
    }

    // 座標の取得とマーカーの表示
    function getClickLatLng(lat_lng, map) {
      // 座標を表示
      document.getElementById('lat').textContent = lat_lng.lat();
      document.getElementById('lng').textContent = lat_lng.lng();

      // マーカーを設置
      var marker = new google.maps.Marker({
        position: lat_lng,
        map: map
      });

      // 座標の中心をずらす
      // http://syncer.jp/google-maps-javascript-api-matome/map/method/panTo/
      map.panTo(lat_lng);
    }  
  </script>
  <script src="https://maps.googleapis.com/maps/api/js?signed_in=true&callback=initMap" async defer></script>
</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