我正在开发Google地图,并希望实现一项功能,用户可以使用鼠标在地图上绘制框/矩形以选择地图上的区域(例如在窗口中选择多个文件)。选择后,我想获得该区域内的所有标记。我一直在寻找Google Maps api和搜索,但我无法找到解决方案。我尝试使用jQuery Selectable进行选择,但它返回的是一堆div,我无法确定是否选择了任何标记。
答案 0 :(得分:9)
我找到了一个库keydragzoom(http://google-maps-utility-library-v3.googlecode.com/svn/tags/keydragzoom/1.0/docs/reference.html)并用它在页面上绘制一个矩形。
稍后,我编辑了库并停止了缩放所选区域,而是让它在'dragend'事件中返回正确的坐标。然后我手动循环遍历地图上的所有标记,以找到该特定区域内的标记。图书馆没有给我正确的坐标,我做了以下更改。
将DragZoom功能更改为
var prj = null;
function DragZoom(map, opt_zoomOpts) {
var ov = new google.maps.OverlayView();
var me = this;
ov.onAdd = function () {
me.init_(map, opt_zoomOpts);
};
ov.draw = function () {
};
ov.onRemove = function () {
};
ov.setMap(map);
this.prjov_ = ov;
google.maps.event.addListener(map, 'idle', function () {
prj = ov.getProjection();
});
}
和DragZoom.prototype.onMouseUp_函数到
DragZoom.prototype.onMouseUp_ = function (e) {
this.mouseDown_ = false;
if (this.dragging_) {
var left = Math.min(this.startPt_.x, this.endPt_.x);
var top = Math.min(this.startPt_.y, this.endPt_.y);
var width = Math.abs(this.startPt_.x - this.endPt_.x);
var height = Math.abs(this.startPt_.y - this.endPt_.y);
var points={
top: top,
left: left,
bottom: top + height,
right: left + width
};
var prj = this.prjov_.getProjection();
// 2009-05-29: since V3 does not have fromContainerPixel,
//needs find offset here
var containerPos = getElementPosition(this.map_.getDiv());
var mapPanePos = getElementPosition(this.prjov_.getPanes().mapPane);
left = left + (containerPos.left - mapPanePos.left);
top = top + (containerPos.top - mapPanePos.top);
var sw = prj.fromDivPixelToLatLng(new google.maps.Point(left, top + height));
var ne = prj.fromDivPixelToLatLng(new google.maps.Point(left + width, top));
var bnds = new google.maps.LatLngBounds(sw, ne);
//this.map_.fitBounds(bnds);
this.dragging_ = false;
this.boxDiv_.style.display = 'none';
/**
* This event is fired when the drag operation ends.
* Note that the event is not fired if the hot key is released before the drag operation ends.
* @name DragZoom#dragend
* @param {GLatLngBounds} newBounds
* @event
*/
google.maps.event.trigger(this, 'dragend', points);
}
};