4X去掉了之前的ArcGISDynamicMapServiceLayer,替换的MapImageLayer更能更强大一些,但是MapImageLayer没有图形的鼠标交互,对需要添加图形交互的MapServer图层需要用FeatureLayer加到map对象上。
// 包含图层url等信息的对象数组
layerList.reverse().forEach((ele: any) => {
let layer;
if (ele.type === 'feature') {
// arcgisFuns是自己封装的arcGIS组件对象 等同于new FeatureLayer
layer = arcgisFuns.FeatureLayer({
// 自己封装的一个拼接图层url的方法
// 示例:http://ip:6080/arcgis/rest/services/XXX/${ele.name}/MapServer
url: layerConfig.getServerPath(ele.name, 'MapServer') + '/0',
id: ele.name,
visible: false,
outFields: ['*'], // 这里需要自行设置输出字段,默认不全
});
} else {
layer = arcgisFuns.MapImageLayer({
url: layerConfig.getServerPath(ele.name, 'MapServer'),
id: ele.name,
visible: false,
});
}
_t.view.map.add(layer);
});
然后是封装的一个获取鼠标点击图层内graphic的方法。GraphicsLayer和FeatureLayer可以直接获取,MapImageLayer因为上边说的原因需要用FeatureLayer替换。
/**
* 获取图层点击的图形对象的简要方法 一次调用终生有效,下次调用会先移除上次的
* @param view arcgis的mapview
* @param layer 目标图层
* @param onClickCallBack 回调
*/
arcgisFuns.getClickGraphic = (view: any, layer: any, onClickCallBack: (graphic: any) => void) => {
if (view.customEventHandle) {
view.customEventHandle.remove();
view.customEventHandle = null;
}
view.customEventHandle = view.on('click', (event: any) => {
view.hitTest(event).then((response: any) => {
if (response.results.length) {
const graphics = response.results.filter((result: any) => {
return result.graphic.layer === layer;
});
if (graphics.length > 0) {
// 这里graphics[0]包含了graphic和mapPoint两个对象
// 这里只输出graphic,都需要的话可以自行修改
onClickCallBack(graphics[0].graphic);
}
}
});
});
};
调用示例
private startClickListen(id: string) {
// 通过id筛出待监听点击的图层
const aimLayer = this.view.map.findLayerById(id);
// this.view是arcgis的mapview对象
arcgisFuns.getClickGraphic(this.view, aimLayer, (graphic: any) => {
// todo ...
});
}
附赠一个光标经过图层graphic的函数
/**
* 获取光标经过的graphic
* @param view arcgis的mapview
* @param layer 目标图层
* @param onHitGraphic 经过时的回调
* @param onMoveOut 移出时的回调
*/
arcgisFuns.getHoverGraphic = (view: any, layer: any, onHitGraphic: any, onMoveOut?: any) => {
if (view.hoverHandle) {
view.hoverHandle.remove();
view.hoverHandle = null; // handler
}
view.hoverHandle = view.on('pointer-move', (event: any) => {
view.hitTest(event, { exclude: view.graphics }).then((response: any) => {
if (response.results.length) {
const graphics = response.results.filter((result: any) => {
return result.graphic.layer === layer;
});
if (graphics.length > 0) {
onHitGraphic(graphics[0]);
}
} else {
onMoveOut();
}
});
});
};