如何使用google.maps.Rectangle对象在谷歌地图上绘制选择/边界框/矩形,并检查标记是否落在其中

How to draw selection / bounding box / rectangle on google map using google.maps.Rectangle object and check if markers fall within it

本文关键字:矩形 检查 在其中 是否 边界 对象 Rectangle maps google 谷歌地图 选择      更新时间:2023-09-26

如何在谷歌地图上绘制一个google.maps.Rectangle,同时按住shift键,然后在绘制后对其边界执行一些操作(例如返回落在其中的所有标记)?

所以我

需要在谷歌地图上画一个简单的矩形,并返回一个落在矩形内的标记数组。令人惊讶的是,我在网上找不到一个简单的例子。所以我发布这个是为了帮助其他人解决同样的问题。

如果您发现任何明显的问题,请告诉我,尽管它目前似乎可以满足我的需求。

该代码假设您有jQuery,并且已经将google地图对象存储在名为themap的变量中。

var shiftdown = false;
var gribBoundingBox = null;
var boxcomplete = false;
var original_click_pos = null;
$(window).keydown(function (evt) {
    if (evt.which === 16) { // shift
        shiftdown = true;
    }
}).keyup(function (evt) {
    if (evt.which === 16) { // shift
        shiftdown = false;
    }
});
function cleargribBoundingBox(){
    if(gribBoundingBox !== null){
        gribBoundingBox.setMap(null); // remove the rectangle
    }
    boxcomplete = false;
original_click_pos = null;
}
google.maps.event.addListener(themap, 'mousedown', function (e) {
    if (shiftdown) {
        themap.setOptions({
            draggable: false
        });
        cleargribBoundingBox();
  original_click_pos = e.latLng;
        gribBoundingBox = new google.maps.Rectangle({
            map: themap,
            bounds: new google.maps.LatLngBounds(original_click_pos,original_click_pos),
            fillOpacity: 0.15,
            strokeWeight: 0.9,
            clickable: false
        });
    }
});
google.maps.event.addListener(themap, 'mousemove', function (e) {
    if(gribBoundingBox !== null){
        if(!boxcomplete){
            //moving mouse accross map, box is in process of being drawn
            //lets update its bounds
    var newbounds = new google.maps.LatLngBounds(original_click_pos,original_click_pos);
            newbounds.extend(e.latLng);
            gribBoundingBox.setBounds(newbounds);
        } else{
            //moving mouse accross map, box is present
        }
    } else {
        //moving mouse over map, no bounding box present
        //either no bounding box has been made yet or we are not holding shift and we are just dragging the map around
    }
});
google.maps.event.addListener(themap, 'mouseup', function (e) {
    if(gribBoundingBox !== null){ //we just completed a box
    if(!boxcomplete){ //we just completed a box
              boxcomplete = true;
              themap.setOptions({
                    draggable: true
              });
              //check if markers are in the box
              /*var boundsSelectionArea = new google.maps.LatLngBounds(
                    gribBoundingBox.getBounds().getSouthWest(),
                    gribBoundingBox.getBounds().getNorthEast()
              );*/
    }
}
});

https://jsfiddle.net/x1xpmhvk/