Google Maps API v3-fitBounds仅使一个标记居中 [英] Google Maps API v3 - fitBounds centers only one marker

查看:64
本文介绍了Google Maps API v3-fitBounds仅使一个标记居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些要检索的标记,并且想将地图居中. 是的,我已经阅读了所有其他答案,但是它似乎对我不起作用: Google Map API v3-设置范围和中心

I have a few markers that I retrieve and want to center the map to. Yes, I have read all the other answers, but it doesn't seem to work for me: Google Map API v3 — set bounds and center

JS:

geocoder.geocode( {'address': loc}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var markerBounds = new google.maps.LatLngBounds();
            var coordinate = results[0].geometry.location;
            var icon = new google.maps.MarkerImage("images/icon-"+type+".png", new google.maps.Size(37, 44));   

            //create the marker
            var marker = new google.maps.Marker({
                map: map, 
                position: coordinate,
                visible: true,
                id: type,
                shadow: shadow,
                icon: icon
            });
            markerBounds.extend(coordinate);
            map.fitBounds(markerBounds);
        }
}

推荐答案

您的代码始终使用只有一个点(最后一个标记)的LatLngBounds来调用fitBounds. 如果您多次调用该函数,则每次调用该函数都会适合最后一个标记的边界. 您可以在geocoder.geocode函数外部定义markerBounds变量,这样它将保留其值.

Your code is always calling fitBounds with a LatLngBounds of only one point, the last marker... If you are calling that function several times, each time you call it, will fitBounds of the last marker. You could define the markerBounds variable outside the geocoder.geocode function, so it will retain it's value.

var markerBounds = new google.maps.LatLngBounds();
geocoder.geocode( {'address': loc}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var coordinate = results[0].geometry.location;
            var icon = new google.maps.MarkerImage("images/icon-"+type+".png", new google.maps.Size(37, 44));   

            //create the marker
            var marker = new google.maps.Marker({
                map: map, 
                position: coordinate,
                visible: true,
                id: type,
                shadow: shadow,
                icon: icon
            });
            markerBounds.extend(coordinate);
            map.fitBounds(markerBounds);
        }
}

现在,markerBounds初始化一次,并使用每个新标记进行扩展.

Now, markerBounds is initialized once, and extended with each new marker.

这篇关于Google Maps API v3-fitBounds仅使一个标记居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆