2017-05-12 8 views
2

これはthis questionとよく似ています。すべてのマーカーが現在のズームレベルで表示されていることを確認したいと思います。しかし、あらかじめ中心点(ユーザの現在位置)を選んでおきたい。円がマーカーであり、正方形が私の意図する中心点である場合、下の画像では、リンクされたソリューションは最初の(左上の)画像を作成します。私は2番目(右、下)の画像が欲しいです。Google Maps API 3 - すべてのマーカーを画面に表示しますが、センターポイントを保持する

What I don't wantWhat I do want

答えて

2

あなたはLatLngBoundsオブジェクトを作成し、マーカーの座標のそれぞれでそれを拡張することができます。次に、あなたの境界オブジェクトを北東と南西の座標にし、これらの座標が現在のマップ境界内に含まれているかどうかを確認します。そうでない場合は、ズームアウトしてもう一度お試しください。

以下のコードのほとんどは、特定の範囲内でランダムなマーカーを生成することです。本当に興味深い部分は、bounds.extend(position)fitAllBoundsの機能です。

var map, bounds; 
 

 
function initialize() { 
 

 
    var southWest = new google.maps.LatLng(40, -70); 
 
    var northEast = new google.maps.LatLng(35, -80); 
 
    var lngSpan = northEast.lng() - southWest.lng(); 
 
    var latSpan = northEast.lat() - southWest.lat(); 
 

 
    var center = new google.maps.LatLng(40, -70); 
 

 
    map = new google.maps.Map(document.getElementById("map-canvas"), { 
 
    zoom: 12, 
 
    center: center, 
 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
 
    }); 
 

 
    // Add center marker 
 
    new google.maps.Marker({ 
 
    position: center, 
 
    label: 'C', 
 
    map: map 
 
    }); 
 

 
    // Create the bounds object 
 
    bounds = new google.maps.LatLngBounds(); 
 

 
    // Create random markers 
 
    for (var i = 0; i < 20; i++) { 
 

 
    // Calculate a random position 
 
    var position = new google.maps.LatLng(southWest.lat() + latSpan * Math.random(), southWest.lng() + lngSpan * Math.random()); 
 

 
    var marker = new google.maps.Marker({ 
 
     position: position, 
 
     map: map 
 
    }); 
 

 
    google.maps.event.addListener(marker, 'click', (function(marker, i) { 
 
     return function() { 
 
     map.setZoom(5); 
 
     map.setCenter(marker.position); 
 
     } 
 
    })(marker, i)); 
 

 
    // Extend the bounds with the last marker position 
 
    bounds.extend(position); 
 
    } 
 

 
    // Fit all bounds once, when the map is ready 
 
    google.maps.event.addListenerOnce(map, 'idle', function() { 
 

 
    fitAllBounds(bounds); 
 
    }); 
 
} 
 

 
function fitAllBounds(b) { 
 

 
    // Get north east and south west markers bounds coordinates 
 
    var ne = b.getNorthEast(); 
 
    var sw = b.getSouthWest(); 
 

 
\t // Get the current map bounds 
 
    var mapBounds = map.getBounds(); 
 

 
    // Check if map bounds contains both north east and south west points 
 
    if (mapBounds.contains(ne) && mapBounds.contains(sw)) { 
 

 
    // Everything fits 
 
    return; 
 

 
    } else { 
 

 
    var mapZoom = map.getZoom(); 
 

 
    if (mapZoom > 0) { 
 

 
     // Zoom out 
 
     map.setZoom(mapZoom - 1); 
 

 
     // Try again 
 
     fitAllBounds(b); 
 
    } 
 
    } 
 
} 
 

 
initialize();
#map-canvas { 
 
    height: 200px; 
 
    width: 200px; 
 
}
<div id="map-canvas"></div> 
 

 
<script src="https://maps.googleapis.com/maps/api/js"></script>

ここでは、JSFiddleにもあります:

JSFiddle demo

関連する問題