/**
* 高德地图实体基类
* 提供高德地图要素的通用功能,如弹窗管理、飞行定位、要素销毁等
*/
export default class GaodeEntity {
/** 信息窗口实例 */
private infoWindow: any = null;
/** 地图实例 */
protected hnMap: any = null;
/** 配置对象 */
protected config: any = null;
/** 图形实例 */
protected graphic: any = null;
/**
* 构造函数
* @param hnMap 地图实例
*/
constructor(hnMap: any) {
this.hnMap = hnMap;
}
/**
* 添加属性弹窗
* 点击要素时显示包含要素属性信息的弹窗
*/
addPopupByAttr(): void {
this.infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)});
const handleClick = (e: any) => {
const data = this.config.extData.data;
let content = '';
for (const key in data) {
content += `
${key}: ${data[key]}
`;
}
this.infoWindow.setContent(content);
this.infoWindow.open(this.hnMap.map.map, e.lnglat);
};
this.graphic.on('click', handleClick);
}
/**
* 添加自定义DOM弹窗
* 点击要素时显示自定义DOM结构的弹窗
* @param getCustomDom 自定义DOM生成函数,接收要素数据,返回DOM字符串
*/
addCustomPopup(getCustomDom: (data: any) => string): void {
this.infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)});
const handleClick = (e: any) => {
const data = this.config.extData.data;
const dom = getCustomDom(data);
this.infoWindow.setContent(dom);
this.infoWindow.open(this.hnMap.map.map, e.lnglat);
};
this.graphic.on('click', handleClick);
}
/**
* 飞行定位到要素
* 根据要素类型自动选择合适的定位方式
*/
flyTo(): void {
if (this.graphic.getCenter) {
this.hnMap.map.map.setCenter(this.graphic.getCenter());
} else if (this.graphic.getPosition) {
this.hnMap.map.map.setCenter(this.graphic.getPosition());
} else if (this.graphic.getBounds) {
const bounds = this.graphic.getBounds();
this.hnMap.map.map.setBounds(bounds);
}
}
/**
* 销毁要素
* 从地图中移除要素
*/
destroy(): void {
this.graphic.remove();
}
}