You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Maps中getBounds().contains返回false问题求助

解决Google Maps Rectangle的contains方法返回false的问题

嘿,我一眼就揪出问题所在啦!你定义矩形bounds的时候把north和south的数值搞反了!

问题根源

纬度的规则是:数值越大越靠北,数值越小越靠南。你设置的north: -37.822802其实比south: -37.822260更靠南(因为-37.822802 < -37.822260),这直接导致你定义的矩形边界是无效的——Google Maps的LatLngBounds要求north必须大于south,east必须大于west。当传入不符合规则的边界时,contains方法自然无法正确判断点的归属。

修复方案

把north和south的数值调换过来,让north的数值更大(更靠北):

var rectangle1 = new google.maps.Rectangle({
  strokeColor: '#FF0000',
  strokeOpacity: 0.8,
  strokeWeight: 2,
  fillColor: '#FF0000',
  fillOpacity: 0.35,
  map: map,
  bounds: {
    north: -37.822260,  // 改为更大的数值(更靠北)
    south: -37.822802,  // 改为更小的数值(更靠南)
    east: 145.036010,
    west: 145.035324
  }
});

更稳妥的边界创建方式

你也可以用LatLngBounds构造函数来创建边界,它会自动帮你校正north/south、east/west的顺序,避免手动设置出错:

var bounds = new google.maps.LatLngBounds(
  new google.maps.LatLng(-37.822802, 145.035324),  // 西南点(south, west)
  new google.maps.LatLng(-37.822260, 145.036010)   // 东北点(north, east)
);

var rectangle1 = new google.maps.Rectangle({
  // 其他属性不变
  bounds: bounds
});

修改后再调用rectangle1.getBounds().contains(new google.maps.LatLng(-37.822545, 145.035526)),就会正确返回true啦!

内容的提问来源于stack exchange,提问作者SYang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:34:33