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

相对

如何在按住Shift键的同时在google地图上绘制google.maps.Rectangle,然后在绘制后对其边界做一些处理(例如返回所有位于其中的标记)?

相对

因此,我需要在Google地图上绘制一个简单的矩形,并返回一个位于该矩形内的标记数组。令人惊讶的是,我在网上找不到一个简单的例子。因此,我发布此内容是为了帮助其他人解决相同的问题。

如果您看到任何明显的问题,请告诉我,尽管目前看来它可以满足我的需求。

该代码假定您使用jQuery,并且已经将Google Map对象存储在名为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/

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档