レスポンシブ対応、Googleマップの中心にピンを表示するテクニック -the new code
Post on:2016年3月3日
sponsorsr
Googleマップをレスポンシブ対応にするのは、簡単です。embedのコードから高さと幅を削除して、ラッパーを用意するだけです。しかし、クリティカルな問題が一つあります。サイズを水平方向に変更した際に、地図の端が切断されてしまいます。
Googleマップの中心にピンを表示し、且つレスポンシブ対応にするテクニックを紹介します。

Create An Auto-Centered Responsive Google Map
以下、各ポイントを意訳したものです。
※当ブログでの翻訳記事は、元サイト様に許可を得て翻訳しています。
デモ
デモでは、デスクトップでも、タブレットでも、スマホでも、そしてコンテンツのサイズを変更しても、Googleマップの中心にピンが表示されています。

実装
Step 1: 空の容器を用意する
Googleマップを埋め込むには、Googleマップのオプションで表示されるiframeを使うのではなく、空のdiv要素を用意します。
| 1 2 3 | <div id="map_container">   <div id="map"></div> </div> | 
容器はレスポンシブ対応にするため、サイズはpxではなく、%で指定します。
| 1 2 3 4 5 6 7 8 9 10 | #map_container {   position: relative;   padding-top: 50%; } #map {   position: absolute;   width: 100%;   height: 100%;   top: 0; } | 
地図をより高くするためには、「padding-top」の値を増やします。
Step 2: Googleマップを埋め込む
用意したdiv要素の容器に、GoogleマップAPIを使って埋め込みます。
まずは、外部スクリプトをbodyの一番下に記述します。
| 1 2 3 4 5 6 7 | <body>   ...   コンテンツ   ...   <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"> </script> </body> | 
外部スクリプトの下に、スクリプトを記述します。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | function initialize() {   var myLatlng = new google.maps.LatLng(53.3333,-3.08333),   mapOptions = {     zoom: 11,     center: myLatlng,     mapTypeId: google.maps.MapTypeId.ROADMAP     }   var map = new google.maps.Map(document.getElementById('map'), mapOptions),   contentString = 'Some address here..',   infowindow = new google.maps.InfoWindow({     content: contentString,     maxWidth: 500   });   var marker = new google.maps.Marker({     position: myLatlng,     map: map   });   google.maps.event.addListener(marker, 'click', function() {     infowindow.open(map,marker);   });   google.maps.event.addDomListener(window, "resize", function() {     var center = map.getCenter();     google.maps.event.trigger(map, "resize");     map.setCenter(center);   }); } google.maps.event.addDomListener(window, 'load', initialize); | 
実装のポイント
1. 「google.maps.LatLng」の値は、表示する地図の緯度と経度です。
デモで表示しているタイムズ・スクエアだと、以下のURLになります。最初の数値が緯度で、2番目の数値が経度です。
| 1 | https://www.google.com/maps/place/Times+Square/@40.758895,-73.9873197,17z | 
Googleマップのオプションで埋め込もうとすると、次のようにコードが表示されます。
| 1 2 3 | <iframe src="https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1 d3022.1422937950165!2d-73.98731968484512!3d40.75889497932676 width="600"  height="450" frameborder="0" style="border:0" allowfullscreen></iframe> | 
この埋め込み用のコードで、経度はURLのすぐ後に、緯度は2番目に記述されています。
2. ズームは、地図のデフォルトの外観のためにズームレベルです。「z」によって明示され、両方のURLで見ることができます。
3. 「contentString」はそれがクリックされる時に現れるターゲットのためのラベルです。
sponsors















