LoginSignup
2
5

More than 5 years have passed since last update.

Googlemap API で全てのピンを地図内に収めたい時

Posted at

Webアプリケーションを作っていてGooglemap API関連の機能を作っていると
登録した地点全てを地図内に収めたい時がある。

写真で言うとこんな感じ。
無題.png

それを行うにはJavascriptで実現していく。ネットにはいろいろ上記を実現させる方法が
書いてあったがあまり上手くいかなかった。。

今回、採用したのは以下のアルゴリズム

・初めに出来る限り、ズームアップしておく。

・次に一つ一つ対象のデータを見てそのピンが地図内に収まるようにズームアウトしていく

である。

以下にソースを載せておく。

map.js
function initMap() {
          map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: ave_latitude, lng: ave_longitude} ,
          zoom: 16,
          });

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

          for (var i = 0; i < data.length; i++) {
              markerLatLng = {lat: data[i]['lat'], lng: data[i]['lng']};
              marker[i] = new google.maps.Marker({
              position: markerLatLng,
              map: map
            });
            bounds.extend(new google.maps.LatLng(data[i]['lat'], data[i]['lng'])); 
          }
          map.fitBounds (bounds);
        }
2
5
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
2
5