由于polyline-encoded的工作原理,这很棘手:该插件扩展了Leaflet
。因此,如果我们希望它完全像JavaScript一样工作,我们需要扩展小册子类型和它的1550行!更有问题的是,每当我们想要更新Leaflet
时,我们都需要检查它的类型是否已经更新,并将它们与polyline-encoded
类型合并!
另一个潜在的问题:在你的代码,Leaflet
是一个ES6模块中使用,但polyline-encoded
是基于改变当前Leaflet
对象L
,混合新旧JavaScript的方式的IIFE。我很想知道它是否有效。
无论如何,一个更安全的选择,我看到(但还没有测试):
- 定义新类型→见下文
Leaflet.encoded.d.ts
,添加到您的项目。
- 强制转换
L
作为在Leaflet.encoded.d.ts
:Lx.L;
中定义的扩展类型。
- 使用
Lx
而不是L
扩展名为polyline-encoded
的每次使用。适应
您的代码:
import * as L from 'leaflet';
import 'https://rawgit.com/jieter/Leaflet.encoded/master/Polyline.encoded.js';
const Lx = L as any as Lx.L;
const map = L.map('map').setView([-43.4175044, 172.185657], 8);
const coordinates = Lx.Polyline.fromEncoded('...').getLatLngs();
Leaflet.encoded.d.ts
:
// Type definitions for Leaflet polyline-encoded 0.0.8
// Project: https://github.com/jieter/Leaflet.encoded
// Definitions by: Romain Deneau <https://github.com/rdeneau>
// TypeScript Version: 2.5
import * as Leaflet from 'leaflet';
export as namespace Lx;
export interface L {
PolylineUtil: PolylineUtil;
Polyline: Polyline;
Polygon: Polygon;
}
// -- PolylineUtil plugin ---------------------------------
export interface PolylineUtilOptions {
precision: number;
factor: number;
dimension: number;
}
export type LatLngTuple = [number, number];
export interface PolylineUtil {
/**
* Decode the string `encoded` to an array of `[lat, lng]`-arrays.
*/
decode(encoded: string, options?: number|PolylineUtilOptions): LatLngTuple[];
/**
* Encode an array of `L.LatLng` objects, or an array of arrays.
*/
encode(points: Leaflet.LatLng[]|LatLngTuple[], options?: number|PolylineUtilOptions): string;
}
// -- Polyline/Polygon extensions -------------------------
export class Polyline extends Leaflet.Polyline {
/**
* Return an encoded string for the current Polyline.
*/
encodePath(): string;
/**
* Construct a new `L.Polyline` from a string, with optional `options` object.
* Backslashes in strings should be properly escaped.
*/
fromEncoded(encoded: string, options?: Leaflet.PolylineOptions): Leaflet.Polyline;
}
export class Polygon extends Leaflet.Polygon {
/**
* Return an encoded string for the current Polygon.
*/
encodePath(): string;
/**
* Construct a new `L.Polygon` from a string, with optional `options` object.
* Backslashes in strings should be properly escaped.
*/
fromEncoded(encoded: string, options?: Leaflet.PolylineOptions): Leaflet.Polygon;
}
如果它的工作,这类型甚至可以被共享,他们提交给DefinitelyTyped repository。
好吧,找到折线的@types包并导入它,这应该做的伎俩。 – toskv
@toskv如果没有可用的类型包,那么自己创建一个包最简单的方法是什么? 'fromEncoded'方法实际上是我需要的唯一方法。 – routeburn
只需将它写入项目的.d.ts文件即可。 – toskv