Angular14项目中OpenLayers6的ControlMousePosition自定义coordinateFormat问题
Angular 14 + OpenLayers 6 自定义 coordinateFormat 类型错误修复
在Angular 14项目中使用OpenLayers 6时,编写自定义coordinateFormat出现类型错误,原代码如下:
import { createStringXY, format } from 'ol/coordinate'; import { Component, OnInit, ChangeDetectionStrategy, Input, ElementRef, } from '@angular/core'; import Map from 'ol/Map'; import ControlMousePosition from 'ol/control/MousePosition'; @Component({ selector: 'app-mouse-position', template: ``, styles: [], changeDetection: ChangeDetectionStrategy.OnPush, }) export class MousePositionComponent implements OnInit { @Input() map!: Map; @Input() positionTemplate!: string; control!: ControlMousePosition; constructor(private element: ElementRef) { } ngOnInit() { this.control = new ControlMousePosition({ className: 'mouseposition-control', coordinateFormat: (coordinate: number[]) => { return format(coordinate, this.positionTemplate);}, target: this.element.nativeElement, undefinedHTML: undefined, }); this.map.addControl(this.control); } }
报错信息:
Type '(coordinate: number[]) => string' is not assignable to type
'CoordinateFormat'. The types of arguments 'coordinate' and 'arg0'
are incompatible.
Type 'number[] | undefined' is not assignable to type 'number[]'.
Type 'undefined' is not assignable to type 'number[]'. ts(2322)
错误原因与修复方案
OpenLayers定义的CoordinateFormat类型允许传入的coordinate参数为number[] | undefined,但自定义函数仅接受number[]类型,导致类型不匹配。
修正方法:
- 将自定义函数的参数类型改为
number[] | undefined - 处理
coordinate为undefined的情况,返回空字符串或其他默认值
修正后的代码:
import { createStringXY, format } from 'ol/coordinate'; import { Component, OnInit, ChangeDetectionStrategy, Input, ElementRef, } from '@angular/core'; import Map from 'ol/Map'; import ControlMousePosition from 'ol/control/MousePosition'; @Component({ selector: 'app-mouse-position', template: ``, styles: [], changeDetection: ChangeDetectionStrategy.OnPush, }) export class MousePositionComponent implements OnInit { @Input() map!: Map; @Input() positionTemplate!: string; control!: ControlMousePosition; constructor(private element: ElementRef) { } ngOnInit() { this.control = new ControlMousePosition({ className: 'mouseposition-control', coordinateFormat: (coordinate: number[] | undefined) => { if (!coordinate) return ''; return format(coordinate, this.positionTemplate); }, target: this.element.nativeElement, undefinedHTML: undefined, }); this.map.addControl(this.control); } }
也可以利用TypeScript类型推断,省略参数类型让TS自动匹配:
coordinateFormat: (coordinate) => { if (!coordinate) return ''; return format(coordinate, this.positionTemplate); },
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

