谷歌地图API V3的fitBounds()方法不起作用。

6

我想在Google地图上调用fitBounds()函数,以便用户可以相对于所选标记/位置查看自己的位置。

下面是处理此操作的函数:

var fitMapToShowResult = function(index){
    var hereLatLng = new google.maps.LatLng (lat,lng); //location of the user defined outside this func
    var firstResultLatLng = new google.maps.LatLng(
                                $scope.searchResults[index].geometry.location.k,
                                $scope.searchResults[0].geometry.location.B
    );
    var latlngList = new Array( hereLatLng, firstResultLatLng ); // latlng: an array of instances of GLatLng
    var latlngbounds = new google.maps.LatLngBounds();
    for (var i=0;i<latlngList.length;i++){
       latlngbounds.extend(latlngList[i]);
       console.log('latlngbounds',latlngbounds);
    }
    //$scope.map.setCenter(latlngbounds.getCenter());
    $scope.map.fitBounds(latlngbounds); 

};

这个功能大概有80%的时间运行得很完美。但是大约每5次中就会有1次标记完全不可见,缩放比例也过高,以至于两个点永远无法同时可见。我做错了什么?

可能与我的地图使用自定义标记有关。

为了帮助调试,我添加了以下代码来在地图上绘制边界...

    rect = new google.maps.Rectangle( {bounds: latlngbounds, map: $scope.map} );

前几个结果总是看起来很完美:enter image description here

但经常是不正确的:enter image description hereenter image description here注意,在每一个不正确的情况下,矩形的一个维度(高度/宽度)是正确的,而另一个维度是不正确的。我的直觉告诉我这是相关的。

类似问题的汇总

我知道这是一个普遍的问题,但我已经审查了所有其他的问题,我的问题似乎不是任何一个问题的复制。希望这个库存对未来的故障排除有用,但这些都没有解决我的问题。

google maps V3 fitBounds not accurate 无用的问题,没有代码和答案。

Google Maps API v3 - fitBounds centers only one marker 用户在循环内重新定义了内部,没有意识到这一点。

Using setZoom() after using fitBounds() with Google Maps API V3 & Google Maps API V3 fitbounds() zooms out but never in & Google Maps with fitBounds don't zoom fitBounds() 是异步的,所以需要在事件监听器中包装后续操作。

google maps → fitBounds manually 用户将错误类型的参数传递给LatLngBounds(应该是两个google.maps.LatLng)。

google maps fitBounds() is broken or..? & Google maps API V3 method fitBounds() 构造 google.maps.LatLngBounds时使用了有缺陷的坐标(而不是留空并使用.extend()

Trying to get Google Maps fitbounds to work 超级初学者没有意识到JavaScript方法是区分大小写的。

谷歌地图V3自定义标记图像和fitBounds() fitBounds()按预期工作,但用户需要为大型自定义标记腾出更多的空间。

Google Maps V3适应可见标记 有关如何使用fitBounds()的简单问题... RTFM。

谷歌地图API V3 - fitBounds随机工作,但偶尔会忽略边界并在海洋中加载 写作时没有答案。听起来像是无效的纬度/经度对。


你为什么要同时调用 $scope.map.setCenter(latlngbounds.getCenter());$scope.map.fitBounds(latlngbounds);?它们可能会相互干扰。 - geocodezip
@geocodezip 很抱歉,那是个错误。我尝试了两种方式,发现是否包含 setCenter() 似乎并不重要,因此我已将其移除。 - emersonthis
1
你能提供一个最小、完整、可测试和易读的示例,以展示问题吗? - geocodezip
你应该避免使用 geometry.location.k。如上所述,请提供一个 MCVE,以便我们知道 $scope.searchResults 和其他变量是什么。 - MrUpsidown
很好的相似问题总结!寻找常见错误的好地方。 - ProblemsOfSumit
显示剩余2条评论
2个回答

1
不要使用值作为geometry.location.**k**,它依赖于最小化文件(例如MinifyJS),当谷歌发布新版本时,它将会更改。

0

MrUpsidown是对的。我的边界框不正确,因为我直接引用了....geometry.location.k而不是LatLng对象。相应地重构代码解决了这个问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接