谷歌地图 - 使用map.fitBounds (bounds);.


google maps - using map.fitBounds (bounds);

我有以下代码(底部),它是嵌入在php中的javascript,用于创建带有一堆标记的谷歌地图。所以我想将缩放设置为显示我所有标记的水平。我知道我需要这段代码:

var latlngbounds = new google.maps.LatLngBounds();
for (var i = 0; i < latlng.length; i++) {
      latlngbounds.extend(latlng[i]);
}
map.fitBounds(latlngbounds);

设置边界,但我无法弄清楚我应该把它放在哪里,或者我需要对我正在使用的代码进行哪些更改,如下所示:

$zoom = 10;
$markers = '';
$mrtallyman = 1;
foreach($locations as $location) {
    $markers .= 'var myLatlng = new google.maps.LatLng'.$location[1].';
                    var marker'.$mrtallyman.' = new google.maps.Marker({
                      position: myLatlng,
                      map: map,
                      title:"'.$location[0].'",
                      icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld='.$mrtallyman.'|FF776B|000000",
                    });'; 
    $mrtallyman++;
}
echo '
<script type="text/javascript">
  function initialize() {
    var userLocation = "'.$area.'";
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( {"address": userLocation}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var latLng = results[0].geometry.location;
            var mapOptions = {
              center: latLng,
              zoom: '.$zoom.',
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("searchPageMap"), mapOptions);
            '.$markers.'
        } else {
           alert("Geocode failed. Reason: " + status);
        }
     });
 }
  google.maps.event.addDomListener(window, "load", initialize);
</script>';

谁能在这里帮我?

使用该代码的原则。

  1. 创建一个空的 google.maps.LatLngBounds 对象

    var latlngbounds = new google.maps.LatLngBounds();
    
  2. 添加要显示的所有位置。 它们必须是google.maps.LatLng对象

    $markers .= 
    'var myLatlng = new google.maps.LatLng'.$location[1].';
    latlngbounds.extend(myLatlng);
    var marker'.$mrtallyman.' = new google.maps.Marker({
                  position: myLatlng,
                  map: map,
                  title:"'.$location[0].'",
                  icon: "https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld='.$mrtallyman.'|FF776B|000000",
                });'; 
    
  3. 将所有位置添加到边界后(在foreach循环右括号之后),调用map.fitBounds

    map.fitBounds(latlngbounds);