Javascript 如何使用谷歌地图 v3 检查标记是否在边界内

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3648545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:35:11  来源:igfitidea点击:

How can I check the marker is or isn't in the bounds using google maps v3

javascriptgoogle-mapsgoogle-maps-api-3

提问by zjm1126

This is my code, I think it may has some mistakes:

这是我的代码,我认为它可能有一些错误:

        var bounds_array;
        google.maps.event.addListener(map,'bounds_changed', function (){
            var bounds_=map.getBounds();
            if(bounds_){
                var leftBottom=[bounds_.getSouthWest().lat(),bounds_.getSouthWest().lng()]
                var rightTop=[bounds_.getNorthEast().lat(),bounds_.getNorthEast().lng()]
                bounds_array=[leftBottom,rightTop];
            }
        });

    function check_is_in_or_out(marker){
        var leftBottom=bounds_array[0],rightTop=bounds_array[1];
        var marker_p=[marker.getPosition().lat(),marker.getPosition().lng()];
        if(marker_p[0]<leftBottom[0]||marker_p[0]>rightTop[0]||
            marker_p[1]<leftBottom[1]||marker_p[1]>rightTop[1])return 0;//0 is out
        else return 1;//1 is in
    }

Is this code enough to check the bounds is in or out?

这段代码是否足以检查边界是进还是出?

回答by Daniel Vassallo

The LatLngBoundsobject comes with a contains()method which takes a LatLngpoint and returns true if the point happens to be within the bounds, or false if outside.

LatLngBounds对象带有一个contains()方法,该方法接受一个LatLng点,如果该点恰好在边界内,则返回 true,如果在边界外,则返回 false。

Therefore, what about something like the following?

因此,像下面这样的事情呢?

function check_is_in_or_out(marker){
  return map.getBounds().contains(marker.getPosition());
}