javascript - 谷歌地图 - 使用map.fitBounds(边界);

标签 javascript php google-maps google-maps-api-3

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

关于javascript - 谷歌地图 - 使用map.fitBounds(边界);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19162118/

相关文章:

php - MySQL 查询 : How many times has a candidate won an election?

php - cakephp 2.3 ajax表单提交

android - Google Maps android通过在 map 中移动标记来获取经纬度

android - 导航完成后,如何从 Android 应用程序中的谷歌地图获取回调

javascript - 计算/异步数据获取

javascript - 如何为 php 文件制作通用的 ajax 函数

javascript - 用javascript去掉括号

javascript - Jquery - 迭代页面中的所有组合框并根据类名删除?

php - 使用 TCPDF 获取 'Headers already sent'

google-maps - 使用 place_id 链接到 Google map 路线