由於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