Skip to content

Commit 4d8e4e2

Browse files
committed
docs(kml): clarify loading, CORS, and NetworkLink behavior
1 parent 2402750 commit 4d8e4e2

2 files changed

Lines changed: 46 additions & 1 deletion

File tree

examples/basic/src/samples/documentation/pages/kml-layer.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,30 @@ const doc: SamplePageDoc = {
1111
</MapViewContainer>`,
1212
state: `const [features, setFeatures] = useState<KMLFeatureData[]>([]);
1313
const [selected, setSelected] = useState<SelectedFeature | null>(null);
14-
const layerState = useMemo(() => new KMLLayerState({ /* fallback style */ }), []);`,
14+
const layerState = useMemo(() => new KMLLayerState({ /* fallback style */ }), []);
15+
16+
// Fetch the document (here: public/sample.kml) and parse it into features.
17+
useEffect(() => {
18+
fetch('/sample.kml')
19+
.then(response => response.text())
20+
.then(text => setFeatures(KMLParser.parse(text)));
21+
}, []);`,
1522
explanation: {
1623
en: [
1724
'Parse a KML document with KMLParser and render its placemarks — styled polygons, lines, and points — as a tiled overlay.',
25+
'KMLParser.parse takes the KML text, so fetch the document yourself first; KMLLoader.load takes a URL instead (anything fetch accepts — a same-origin path such as /sample.kml or an absolute https URL), follows <NetworkLink> references and unpacks KMZ archives. On the web that fetch is subject to CORS, so a cross-origin document loads only when its server sends Access-Control-Allow-Origin — otherwise serve it from your own origin or inject a proxying fetch through the KMLLoader constructor.',
1826
'Both the features and the selected feature live in React state, and layerState is a KMLLayerState whose style is the fallback used when a placemark carries no KML <Style>.',
1927
"handleMapClick resolves which feature was hit and stores it, then InfoBubble anchors a PropertyTable of the placemark's name, description, and ExtendedData at the clicked coordinate.",
2028
],
2129
ja: [
2230
'KML ドキュメントを KMLParser で解析し、スタイル付きのポリゴン・ライン・ポイントをタイルオーバーレイとして描画します。',
31+
'KMLParser.parse は KML テキストを受け取るので取得は自前で行います。KMLLoader.load なら URL を渡せます(fetch が引けるもの、例えば同一オリジンの /sample.kml や絶対 https URL)。こちらは <NetworkLink> の参照先も追跡し、KMZ も展開します。ただし web の取得は CORS の制約を受けるため、別オリジンの文書は配信側が Access-Control-Allow-Origin を返す場合にのみ読めます。返らない場合は自分のオリジンに置くか、KMLLoader の constructor で fetch を差し替えてプロキシ経由にしてください。',
2332
'features と選択中の Feature はどちらも React の state に保持し、layerState は KML の <Style> を持たないプレースマークに使う既定スタイルを持つ KMLLayerState です。',
2433
'handleMapClick がどの Feature に当たったかを判定して保存し、InfoBubble がプレースマークの name / description / ExtendedData の PropertyTable をクリック座標に固定します。',
2534
],
2635
'es-419': [
2736
'Analiza un documento KML con KMLParser y renderiza sus placemarks — polígonos, líneas y puntos con estilo — como una superposición de mosaicos.',
37+
'KMLParser.parse recibe el texto KML, así que tú haces la descarga; KMLLoader.load recibe una URL (cualquiera que acepte fetch: una ruta del mismo origen como /sample.kml o una URL https absoluta), sigue las referencias <NetworkLink> y descomprime archivos KMZ. En la web esa descarga está sujeta a CORS: un documento de otro origen solo carga si su servidor envía Access-Control-Allow-Origin; si no, publícalo en tu propio origen o inyecta un fetch con proxy en el constructor de KMLLoader.',
2838
'Tanto los features como el elemento seleccionado viven en el estado de React, y layerState es un KMLLayerState cuyo estilo es el respaldo cuando un placemark no trae <Style> KML.',
2939
'handleMapClick determina qué elemento se tocó y lo almacena, luego InfoBubble ancla un PropertyTable con name, description y ExtendedData del placemark en la coordenada tocada.',
3040
],

react-kml/README.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,41 @@ const loader = new KMLLoader();
6969
const features = await loader.load('https://example.com/doc.kml');
7070
```
7171

72+
`load` accepts a URL, KML text, or KML/KMZ bytes — a string is treated as KML
73+
text when it starts with `<` (after leading whitespace) and as a URL otherwise.
74+
75+
### Cross-origin documents
76+
77+
The default fetch is the global `fetch`, so it is subject to CORS. A document on
78+
another origin loads only when its server sends `Access-Control-Allow-Origin`;
79+
many published KML/KMZ files do not. Serve the document from your own origin, or
80+
pass a `fetch` that routes through a proxy you control:
81+
82+
```ts
83+
const loader = new KMLLoader({
84+
fetch: async url => {
85+
const response = await fetch(`/kml-proxy?src=${encodeURIComponent(url)}`);
86+
return new Uint8Array(await response.arrayBuffer());
87+
},
88+
});
89+
```
90+
91+
This applies to `<NetworkLink>` targets too, and they fail quietly: only the
92+
root document's failure is thrown from `load` — a link that cannot be fetched or
93+
parsed is skipped and reported to `onDocumentError`. Without that callback, a
94+
blocked link looks like a document that simply has fewer features:
95+
96+
```ts
97+
const loader = new KMLLoader({
98+
onDocumentError: (url, error) => console.warn('skipped', url, error),
99+
});
100+
```
101+
102+
Relative `<NetworkLink>` hrefs resolve against the URL the document came from,
103+
so pass an absolute URL (`new URL('/sample.kml', location.href).href`) when the
104+
document has relative links — a root URL that is itself relative leaves them
105+
unresolvable, and they are dropped.
106+
72107
## License
73108

74109
Apache License 2.0

0 commit comments

Comments
 (0)