2

我有以下代码(底部),它是嵌入在 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>';

有谁可以帮我离开这里吗?

4

1 回答 1

2

使用该代码的原理。

  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);
    
于 2013-10-03T15:40:57.677 回答