需求是:一个图层有十几个点,用户在地图上随机点击一个点,查询出在这个图层中距离用户点击处最近的点,查询出后将查询出的点添加到地图上展现。
直接上代码
methods:{
startClosePoint() {
loadModules([
"esri/rest/support/Query",
"esri/Graphic",
"esri/layers/FeatureLayer",
"esri/geometry/geometryEngine",
"esri/geometry/Point",
"esri/layers/GraphicsLayer",
]).then(
([
Query,
Graphic,
FeatureLayer,
geometryEngine,
Point,
GraphicsLayer,
]) => {
// 要素图层
this.$allPointLayer = new FeatureLayer({
url: "xxx",
});
let pointSymbol = {
type: "point-3d",
symbolLayers: [
{
type: "object",
width: 5000,
resource: { primitive: "diamond" }, // https://developers.arcgis.com/javascript/latest/api-reference/esri-symbols-ObjectSymbol3DLayer.html#material 可以查看resource
material: { color: "#FFD700" },
},
],
};
this.$pointGraphicsLayer = new GraphicsLayer(); // 创建 GraphicsLayer
this.$map.add(this.$pointGraphicsLayer);
// 绑定好监听事件,到时候解绑要用到
this.$clickSceneView = this.$view.on("click", (event) => {
// 开始进行最近点的查询
let nearestDistance = Infinity;
let nearestFeature = null;
// 根据点击处创建点
const clickedPoint = new Point({
x: event.mapPoint.longitude,
y: event.mapPoint.latitude,
spatialReference: this.$view.spatialReference,
});
this.$allPointLayer.queryFeatures().then((result) => {
result.features.forEach((feature) => {
// geometryEngine可以用来计算距离
const distance = geometryEngine.distance(
clickedPoint,
feature.geometry
);
if (distance < nearestDistance) {
nearestDistance = distance;
nearestFeature = feature;
}
});
// 显示或处理最近的要素和距离
if (nearestFeature) {
// 创建用于显示的点要素
const pointGraphic = new Graphic({
geometry: {
type: "point",
longitude: nearestFeature.attributes.longitude,
latitude: nearestFeature.attributes.latitude,
spatialReference: this.$view.spatialReference,
},
symbol: pointSymbol
});
// 先清除所有
this.$pointGraphicsLayer.removeAll();
this.$pointGraphicsLayer.add(captialGraphic);
this.$advanceLoading.close();
// 移动视角
this.$view.goTo({
zoom: 12,
center: [
nearestFeature.attributes.longitude,
nearestFeature.attributes.latitude,
],
tilt: 45,
});
}
});
});
}
);
},
}
关键就是geometryEngine,我之前一直以为是要用Query才能实现查询。
geometryEngine的官网参考也放在这里了:geometryEngine | API Reference | ArcGIS Maps SDK for JavaScript 4.27 | ArcGIS Developers
然后是事件的解绑,这个没有什么好说的。
this.$clickSceneView.remove(); // this.$clickSceneView就是上面代码的this.$clickSceneView