/
leaflet.layerindex.js
93 lines (78 loc) · 3.12 KB
/
leaflet.layerindex.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
* Spatial index of layer objects using RTree.js
* https://github.com/imbcmdth/RTree
*/
// Backport of Leaflet 0.5
if (typeof L.LatLngBounds.prototype.isValid != 'function') {
L.LatLngBounds.prototype.isValid = function () {
return !!(this._southWest && this._northEast);
};
}
L.LayerIndexMixin = {
search: function (bounds) {
var rtbounds = this._rtbounds(bounds);
return this._rtree ? this._rtree.search(rtbounds) : [];
},
searchBuffer: function (latlng, radius) {
/* Caution: radius is in degrees */
var around = L.latLngBounds([latlng.lat - radius,
latlng.lng - radius],
[latlng.lat + radius,
latlng.lng + radius]);
return this.search(around);
},
indexLayer: function (layer) {
if (this.options.indexing !== undefined && !this.options.indexing)
return;
var bounds = this._layerBounds(layer);
if (!this._rtree) this._rtree = new RTree();
this._rtree.insert(this._rtbounds(bounds), layer);
},
unindexLayer: function (layer, options) {
var bounds;
if (options && options.bounds) {
bounds = options.bounds;
} else if (options && options.latlng) {
bounds = new L.LatLngBounds(options.latlng, options.latlng);
} else if (options && options.latlngs) {
bounds = new L.LatLngBounds(options.latlngs);
} else {
bounds = this._layerBounds(layer);
}
this._rtree.remove(this._rtbounds(bounds), layer);
},
_layerBounds: function (layer) {
// Introspects layer and returns its bounds.
var bounds = null;
if (layer instanceof L.LayerGroup) {
// Leaflet uses project() in Circle's getBounds() method.
// It will fail it if the layer is not yet on the map.
// Thus, rewrite that part and add switch for Circles,
// ignoring their radius in pixels.
bounds = new L.LatLngBounds();
layer.eachLayer(function (sublayer) {
if (sublayer instanceof L.Circle || sublayer instanceof L.Marker)
bounds.extend(sublayer.getLatLng());
else if (sublayer instanceof L.LayerGroup)
bounds.extend(this._layerBounds(sublayer));
else
bounds.extend(sublayer.getBounds());
}, this);
}
else if (typeof layer.getLatLng == 'function') {
bounds = new L.LatLngBounds(layer.getLatLng(), layer.getLatLng());
}
else if (typeof layer.getBounds == 'function') {
bounds = layer.getBounds();
}
if (!(bounds && bounds.isValid()))
throw "Unable to get layer bounds";
return bounds;
},
_rtbounds: function (bounds) {
return {x: bounds.getSouthWest().lng,
y: bounds.getSouthWest().lat,
w: bounds.getSouthEast().lng - bounds.getSouthWest().lng,
h: bounds.getNorthWest().lat - bounds.getSouthWest().lat};
}
};