feat(页面): 添加区域探索与国家边界功能
This commit is contained in:
53
components/globe/use-country-data.ts
Normal file
53
components/globe/use-country-data.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { feature } from "topojson-client";
|
||||
import type { Topology, GeometryCollection } from "topojson-specification";
|
||||
import type { FeatureCollection, Feature, Geometry } from "geojson";
|
||||
import { COUNTRY_LABELS } from "@/lib/geo/country-labels";
|
||||
|
||||
const TOPOJSON_URL =
|
||||
"https://cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json";
|
||||
|
||||
export interface LabelData {
|
||||
lat: number;
|
||||
lng: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export function useCountryData(locale: string) {
|
||||
const [countries, setCountries] = useState<Feature<Geometry>[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
fetch(TOPOJSON_URL)
|
||||
.then((res) => res.json())
|
||||
.then((topo: Topology) => {
|
||||
if (cancelled) return;
|
||||
const geo = feature(
|
||||
topo,
|
||||
topo.objects.countries as GeometryCollection
|
||||
) as FeatureCollection;
|
||||
setCountries(geo.features);
|
||||
setIsLoading(false);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setIsLoading(false);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const labels: LabelData[] = useMemo(() => {
|
||||
const lang = locale === "zh" ? "zh" : "en";
|
||||
return COUNTRY_LABELS.map((c) => ({
|
||||
lat: c.lat,
|
||||
lng: c.lng,
|
||||
name: c[lang],
|
||||
}));
|
||||
}, [locale]);
|
||||
|
||||
return { countries, labels, isLoading };
|
||||
}
|
||||
Reference in New Issue
Block a user