Point类
# 概述
Point类是 Openlayers 中Geom最简单的几何对象,该类是继承于SimpleGeometry类,关于SimpleGeometry类可以参考这篇文章
本文主要介绍Point类的源码实现原理。
# 源码分析
# Point类的源码实现
Point类的源码实现如下:
class Point extends SimpleGeometry {
constructor(coordinates, layout) {
super();
this.setCoordinates(coordinates, layout);
}
clone() {
const point = new Point(this.flatCoordinates.slice(), this.layout);
point.applyProperties(this);
return point;
}
closestPointXY(x, y, closestPoint, minSquaredDistance) {
const flatCoordinates = this.flatCoordinates;
const squaredDistance = squaredDx(
x,
y,
flatCoordinates[0],
flatCoordinates[1]
);
if (squaredDistance < minSquaredDistance) {
const stride = this.stride;
for (let i = 0; i < stride; ++i) {
closestPoint[i] = flatCoordinates[i];
}
closestPoint.length = stride;
return squaredDistance;
}
return minSquaredDistance;
}
getCoordinates() {
return this.flatCoordinates.slice();
}
computeExtent(extent) {
return createOrUpdateFromCoordinate(this.flatCoordinates, extent);
}
getType() {
return "Point";
}
intersectsExtent(extent) {
return containsXY(extent, this.flatCoordinates[0], this.flatCoordinates[1]);
}
setCoordinates(coordinates, layout) {
this.setLayout(layout, coordinates, 0);
if (!this.flatCoordinates) {
this.flatCoordinates = [];
}
this.flatCoordinates.length = deflateCoordinate(
this.flatCoordinates,
0,
coordinates,
this.stride
);
this.changed();
}
}
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
# Point类的构造函数
Point类的构造函数接受两个参数coordinates和layout,分别表示几何对象的坐标和坐标的形式;在构造函数中除了调用super初始化父类的实例属性,还会调用this.setCoordinates方法。
# Point类的主要方法
Point类的方法也不是很多,主要有如下
setCoordinates方法:该方法会在Point类的构造函数中被调用;在其内部首先会调用父类的setLayout方法,设置父类的属性this.layout和this.stride,然后判断,若this.flatCoordinates为false,则设置this.flatCoordinates为空数组[],然后调用delateCoordinate方法扁平化几何对象的坐标设置this.flatCoordinates的值,最后调用this.changed方法。clone方法:内部就是实例化Point类,然后调用实例对象的applyProperties修改属性,最后返回实例对象closestPointXY方法:接受四个参数,目标点坐标x和y,最近点坐标closestPoint,最短距离平方minSquaredDistance;先计算目标点距离几何对象的最短距离的平方squaredDistance,然后比较它和参数minSquaredDistance的大小;若squaredDistance小于minSquaredDistance,则修改最近点坐标,并返回squaredDistance;否则,直接返回minSquaredDistancegetCoordinates方法:获取几何对象的一维数组computeExtent方法:调用createOrUpdateFromCoordinate创建几何对象的包围盒并返回getType方法:返回点几何对象的类型PointintersectsExtent方法:内部调用containsXY方法并返回结果,用于判断点是不是在extent内或在其边界上
# 总结
本文主要介绍了Point类的实现和主要方法,Point类是最简单的几何对象。