如何在按住Shift键的同时在google地图上绘制google.maps.Rectangle,然后一旦绘制了它的边界(比如返回其中的所有标记)?
答案 0 :(得分:0)
所以我需要在谷歌地图上绘制一个简单的矩形,并返回一个落在矩形内的标记数组。令人惊讶的是,我在网上找不到这个简单的例子。所以我发布这个是为了帮助其他人解决同样的问题。
如果你能看到任何明显的问题,请告诉我,虽然它似乎可以满足我的需求。
该代码假设您拥有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()
);*/
}
}
});