Google 地图 JavaScript API - 自动缩放级别?

发布于 2024-09-09 09:29:04 字数 2339 浏览 2 评论 0原文

我正在使用多个地图标记。目前,我在 JavaScript 中使用 map.fitBounds(bounds); 来调整地图大小。 bounds 包含多个 LatLng 对象。

我做错了什么?因为它缩小得太远了:-(

在此处输入图像描述

JavaScript 源

var geocoder, map;
$(document).ready(function(){
    var coll_gmap = $(".gmap");
    if ( coll_gmap.length != 0 )
    {
        //initiate map
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(-34.397, 150.644);
        var myOptions = {
            zoom: 13,
            center: latlng,
           mapTypeControl: true,
            navigationControl: true,
            scaleControl: true,
            navigationControlOptions: {style: google.maps.NavigationControlStyle.ZOOM_PAN},
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var bounds = new google.maps.LatLngBounds();
        //loop all addressen + insert into map
          map = new google.maps.Map(coll_gmap[0], myOptions);
        coll_gmap.each(function(index)
        {
             if (geocoder) {
                    geocoder.geocode( { 'address': $(this).attr("address")}, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            map.setCenter(results[0].geometry.location);
                            bounds.extend(results[0].geometry.location);

                            var marker = new google.maps.Marker({
                                map: map, 
                                position: results[0].geometry.location
                            });
                        } else {
                            console.log("Geocode was not successful for the following reason: " + status);
                        }//end if status
                    }); //end if geocoder.geocode
                } //end if geocoder   

        }) //end coll_gmap each
        map.fitBounds(bounds);

        }//end if coll_gmap length
       /* console.log("Script created by NicoJuicy");*/   
}); //end onload

HTML 源

<div class="gmap" address="SomeAddress1" style="width:700px;height:350px"></div>
<div class="gmap" address="someAddress2"></div>

I'm working with multiple map markers. Currently I use map.fitBounds(bounds); in my JavaScript to resize the map. bounds contains multiple LatLng objects.

What am i doing wrong? Because it zooms out too far :-(

enter image description here

JavaScript source

var geocoder, map;
$(document).ready(function(){
    var coll_gmap = $(".gmap");
    if ( coll_gmap.length != 0 )
    {
        //initiate map
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(-34.397, 150.644);
        var myOptions = {
            zoom: 13,
            center: latlng,
           mapTypeControl: true,
            navigationControl: true,
            scaleControl: true,
            navigationControlOptions: {style: google.maps.NavigationControlStyle.ZOOM_PAN},
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var bounds = new google.maps.LatLngBounds();
        //loop all addressen + insert into map
          map = new google.maps.Map(coll_gmap[0], myOptions);
        coll_gmap.each(function(index)
        {
             if (geocoder) {
                    geocoder.geocode( { 'address': $(this).attr("address")}, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            map.setCenter(results[0].geometry.location);
                            bounds.extend(results[0].geometry.location);

                            var marker = new google.maps.Marker({
                                map: map, 
                                position: results[0].geometry.location
                            });
                        } else {
                            console.log("Geocode was not successful for the following reason: " + status);
                        }//end if status
                    }); //end if geocoder.geocode
                } //end if geocoder   

        }) //end coll_gmap each
        map.fitBounds(bounds);

        }//end if coll_gmap length
       /* console.log("Script created by NicoJuicy");*/   
}); //end onload

HTML source

<div class="gmap" address="SomeAddress1" style="width:700px;height:350px"></div>
<div class="gmap" address="someAddress2"></div>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

海拔太高太耀眼 2024-09-16 09:29:04

fitBounds() 方法应该可以工作。但请注意,它总是在地图的大小上保留一些填充。请考虑以下示例:

<!DOCTYPE html>
<html> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
   <title>Google Maps fitBounds Padding</title> 
   <script src="http://maps.google.com/maps/api/js?sensor=false" 
           type="text/javascript"></script> 
</head> 
<body> 
   <div id="map" style="width: 543px; height: 350px;"></div> 

   <script type="text/javascript"> 
      var map = new google.maps.Map(document.getElementById('map'), { 
        mapTypeId: google.maps.MapTypeId.ROADMAP 
      });

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

      var points = [
        new google.maps.LatLng(51.22, 4.40),
        new google.maps.LatLng(50.94, 3.13)
      ];

      // Extend bounds with each point
      for (var i = 0; i < points.length; i++) {
        bounds.extend(points[i]);
        new google.maps.Marker({position: points[i], map: map});
      }

      // Apply fitBounds
      map.fitBounds(bounds);  

      // Draw the bounds rectangle on the map
      var ne = bounds.getNorthEast();
      var sw = bounds.getSouthWest();

      var boundingBox = new google.maps.Polyline({
        path: [
          ne, new google.maps.LatLng(ne.lat(), sw.lng()),
          sw, new google.maps.LatLng(sw.lat(), ne.lng()), ne
        ],
        strokeColor: '#FF0000',
        strokeOpacity: 1.0,
        strokeWeight: 2
      });

      boundingBox.setMap(map);
   </script> 
</body> 
</html>

上述示例的屏幕截图:

Google Maps fitBounds Padding

红色边界框代表 LatLngBounds< /code> 使用两个标记扩展时的对象。请注意,地图画布的宽度为 543px,还要注意边界框左侧和右侧的填充边距。

现在,如果我们使用 542px 将地图画布的宽度减少 1px,则 fitBounds() 方法将弹出到较低的缩放级别:

Google 地图 fitBounds 填充

The fitBounds() method should work. However note that it always keeps some padding on the sizes of the map. Consider the following example:

<!DOCTYPE html>
<html> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
   <title>Google Maps fitBounds Padding</title> 
   <script src="http://maps.google.com/maps/api/js?sensor=false" 
           type="text/javascript"></script> 
</head> 
<body> 
   <div id="map" style="width: 543px; height: 350px;"></div> 

   <script type="text/javascript"> 
      var map = new google.maps.Map(document.getElementById('map'), { 
        mapTypeId: google.maps.MapTypeId.ROADMAP 
      });

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

      var points = [
        new google.maps.LatLng(51.22, 4.40),
        new google.maps.LatLng(50.94, 3.13)
      ];

      // Extend bounds with each point
      for (var i = 0; i < points.length; i++) {
        bounds.extend(points[i]);
        new google.maps.Marker({position: points[i], map: map});
      }

      // Apply fitBounds
      map.fitBounds(bounds);  

      // Draw the bounds rectangle on the map
      var ne = bounds.getNorthEast();
      var sw = bounds.getSouthWest();

      var boundingBox = new google.maps.Polyline({
        path: [
          ne, new google.maps.LatLng(ne.lat(), sw.lng()),
          sw, new google.maps.LatLng(sw.lat(), ne.lng()), ne
        ],
        strokeColor: '#FF0000',
        strokeOpacity: 1.0,
        strokeWeight: 2
      });

      boundingBox.setMap(map);
   </script> 
</body> 
</html>

Screenshot from the above example:

Google Maps fitBounds Padding

The red bounding box represents the LatLngBounds object when extended with both markers. Note that the map canvas is 543px wide, and also note the padding margin to the left and right of the bounding box.

Now if we reduce the width of the map canvas by just 1px, using 542px, the fitBounds() method will pop to a lower zoom level:

Google Maps fitBounds Padding

两仪 2024-09-16 09:29:04

我使用右侧的“相关”链接来到这里,我认为您的问题的答案与上一个问题的答案相同。 :p

看,问题是,每次您使用平移/缩放地图的功能时,脚本都会忽略新的类似输入,直到再次准备好为止。因此,您必须检测到这一点,并且仅在接受时调用 fitBounds() 。尝试将您的替换

map.fitBounds(bounds);

var listener = google.maps.event.addListener(map, "idle", function() { 
               map.fitBounds(bounds);
               google.maps.event.removeListener(listener); });

“祝你好运”。

I got here using a "Related" link to the right, and I think that the answer to your problem is the same as to the previous question. :p

See, the thing is that every time you use a function that pans/zooms the map, the script ignores new, similar, input until it's ready for it again. Therefore, you have to detect this and only call fitBounds() when it's accepted. Try replacing your

map.fitBounds(bounds);

with

var listener = google.maps.event.addListener(map, "idle", function() { 
               map.fitBounds(bounds);
               google.maps.event.removeListener(listener); });

Good luck.

ペ泪落弦音 2024-09-16 09:29:04

只需使用 setZoom 函数即可。

var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': zipcode }, function(results, status)
{
    if (status == google.maps.GeocoderStatus.OK)
    {
        map.setCenter(results[0].geometry.location);
        map.setZoom(12);
    }
    else
    {
        alert(zipcode + " not found" + "\nstatus : " + status);
    }
});

Just use the setZoom function.

var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': zipcode }, function(results, status)
{
    if (status == google.maps.GeocoderStatus.OK)
    {
        map.setCenter(results[0].geometry.location);
        map.setZoom(12);
    }
    else
    {
        alert(zipcode + " not found" + "\nstatus : " + status);
    }
});
下壹個目標 2024-09-16 09:29:04

我已经找到了解决方案。

不要执行一次操作

bounds.extend(myLatLng)

每次将 myLatLng 添加到边界时,

bounds = map.getBounds();
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);

,而是执行以下操作希望这对任何人都有帮助!

I have found the solution.

Instead of doing a single

bounds.extend(myLatLng)

Everytime you add a myLatLng to your bounds, do these actions

bounds = map.getBounds();
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);

Hope this helps anyone!

听,心雨的声音 2024-09-16 09:29:04
//Custom zoom if you have just type of geocode response    
function get_node(node_name){
return document.getElementById(node_name);
}

var map_options = {};
var options = {
    'zoom'      : LB_listing.zoomopt,
    'minZoom'   : 3,
    'center'    : latlng,
    'mapTypeId' : google.maps.MapTypeId.ROADMAP
};
map_options.map = new google.maps.Map(get_node('googleMap'), options);


geocoder = new google.maps.Geocoder();
var address = $("#search_location").val();
geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        switch(results[0].types[0]){
            case 'street_address':
                map_options.zoomopt = 6;
                break;
            case 'route':
                map_options.zoomopt = 14;
                break;
            case 'bus_station':
                map_options.zoomopt = 14;
                break;
            case 'intersection':
                map_options.zoomopt = 6;
                break;
            case 'political':
                map_options.zoomopt = 14;
                break;
            case 'country':
                map_options.zoomopt = 5;
                break;
            case 'administrative_area_level_1':
                map_options.zoomopt = 6;
                break;
            case 'administrative_area_level_2':
                map_options.zoomopt = 6;
                break;
            case 'administrative_area_level_3':
                map_options.zoomopt = 6;
                break;
            case 'administrative_area_level_4':
                map_options.zoomopt = 6;
                break;
            case 'administrative_area_level_5':
                map_options.zoomopt = 6;
                break;
            case 'colloquial_area':
                map_options.zoomopt = 6;
                break;
            case 'locality':
                map_options.zoomopt = 11;
                break;
            case 'ward':
                map_options.zoomopt = 6;
                break;
            case 'sublocality':
                map_options.zoomopt = 6;
                break;
            case 'neighborhood':
                map_options.zoomopt = 14;
                break;
            case 'premise':
                map_options.zoomopt = 6;
                break;
            case 'subpremise':
                map_options.zoomopt = 6;
                break;
            case 'postal_code':
                map_options.zoomopt = 6;
                break;
            case 'natural_feature':
                map_options.zoomopt = 6;
                break;
            case 'airport':
                map_options.zoomopt = 6;
                break;
            case 'park':
                map_options.zoomopt = 6;
                break;
            case 'point_of_interest':
                map_options.zoomopt = 6;
                break;
            default:
                map_options.zoomopt = 6;
                break;
        }
        map_options.newLocation(results[0].geometry.location.lat(),results[0].geometry.location.lng());
    }else {
        $('#message_error').show().delay(3000).fadeOut(1000);
        $('#message_error_msg').html("Geocode was not successful for the following reason: " + status);
    }
});

map_options.newLocation = function(newLat,newLng) {
map_options.map.setCenter({
    lat : newLat,
    lng : newLng
});
map_options.map.setZoom(map_options.zoomopt);

}

//Custom zoom if you have just type of geocode response    
function get_node(node_name){
return document.getElementById(node_name);
}

var map_options = {};
var options = {
    'zoom'      : LB_listing.zoomopt,
    'minZoom'   : 3,
    'center'    : latlng,
    'mapTypeId' : google.maps.MapTypeId.ROADMAP
};
map_options.map = new google.maps.Map(get_node('googleMap'), options);


geocoder = new google.maps.Geocoder();
var address = $("#search_location").val();
geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        switch(results[0].types[0]){
            case 'street_address':
                map_options.zoomopt = 6;
                break;
            case 'route':
                map_options.zoomopt = 14;
                break;
            case 'bus_station':
                map_options.zoomopt = 14;
                break;
            case 'intersection':
                map_options.zoomopt = 6;
                break;
            case 'political':
                map_options.zoomopt = 14;
                break;
            case 'country':
                map_options.zoomopt = 5;
                break;
            case 'administrative_area_level_1':
                map_options.zoomopt = 6;
                break;
            case 'administrative_area_level_2':
                map_options.zoomopt = 6;
                break;
            case 'administrative_area_level_3':
                map_options.zoomopt = 6;
                break;
            case 'administrative_area_level_4':
                map_options.zoomopt = 6;
                break;
            case 'administrative_area_level_5':
                map_options.zoomopt = 6;
                break;
            case 'colloquial_area':
                map_options.zoomopt = 6;
                break;
            case 'locality':
                map_options.zoomopt = 11;
                break;
            case 'ward':
                map_options.zoomopt = 6;
                break;
            case 'sublocality':
                map_options.zoomopt = 6;
                break;
            case 'neighborhood':
                map_options.zoomopt = 14;
                break;
            case 'premise':
                map_options.zoomopt = 6;
                break;
            case 'subpremise':
                map_options.zoomopt = 6;
                break;
            case 'postal_code':
                map_options.zoomopt = 6;
                break;
            case 'natural_feature':
                map_options.zoomopt = 6;
                break;
            case 'airport':
                map_options.zoomopt = 6;
                break;
            case 'park':
                map_options.zoomopt = 6;
                break;
            case 'point_of_interest':
                map_options.zoomopt = 6;
                break;
            default:
                map_options.zoomopt = 6;
                break;
        }
        map_options.newLocation(results[0].geometry.location.lat(),results[0].geometry.location.lng());
    }else {
        $('#message_error').show().delay(3000).fadeOut(1000);
        $('#message_error_msg').html("Geocode was not successful for the following reason: " + status);
    }
});

map_options.newLocation = function(newLat,newLng) {
map_options.map.setCenter({
    lat : newLat,
    lng : newLng
});
map_options.map.setZoom(map_options.zoomopt);

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文