Appearance
快速开始
适用于原生 TypeScript / Vite 浏览器应用。构建环境与仓库保持一致,使用 Node.js >=22.12.0。 SDK 是 ESM 包,不在服务端渲染阶段创建地图;组件卸载或页面切换时应调用 destroy()。
安装
直接通过官网 HTTPS 地址安装 SDK,无需手动下载 TGZ 或配置私有 npm。下载页提供文件与 SHA-256,供需要离线保存或核对的用户使用。
sh
npm create vite@latest my-map -- --template vanilla-ts
cd my-map
npm install
npm install https://map.shardx.cn/shardx-map-sdk-0.1.0.tgz cesium@1.146.0Cesium 是 peer dependency,兼容范围为 >=1.146.0 <1.147.0,不会打入 SDK。 不要用强制忽略 peer 检查的方式安装其他 Cesium 次版本。
准备静态资源
在消费项目根目录执行 SDK 提供的资源复制命令:
sh
npx shardx-copy-cesium-assets --out public/cesium将此步骤加入消费项目自己的开发和构建流程。输出中必须有 Workers、Assets、Widgets、ThirdParty, 并与安装的 Cesium 版本一致,详见静态资源。
创建地图
Vite 的环境变量会进入浏览器产物;VITE_TIANDITU_KEY 是浏览器地图服务 key,不是服务器密钥。 应在天地图控制台限制可用域名,并按供应商规则管理额度与授权。不要在前端放 npm token。
html
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>我的地图</title>
</head>
<body>
<div id="map"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>css
html,
body {
margin: 0;
height: 100%;
}
#map {
width: 100%;
height: 100vh;
}ts
import { createMap } from '@shardx-map/sdk';
import '@shardx-map/sdk/style.css';
import 'cesium/Build/Cesium/Widgets/widgets.css';
import './style.css';
async function start() {
const map = await createMap({
container: 'map',
assetBaseUrl: new URL(`${import.meta.env.BASE_URL}cesium/`, location.origin).href,
source: { type: 'naturalEarth' },
view: { longitude: 113.88, latitude: 22.56, height: 20000, pitch: -60 },
});
const offError = map.on('error', (event) => {
// 不上传原始网络请求 URL、key 或业务隐私数据。
console.warn(event.code, event.message);
});
map.addLayer({
id: 'places',
features: [
{
id: 'office',
type: 'point',
position: [113.88, 22.56, 0],
color: '#22c55e',
size: 12,
popup: '办公地点',
},
],
});
const offClick = map.on('click', (event) => {
if (event.featureId) console.log(event.layerId, event.featureId);
});
// 页面卸载时执行:
function dispose() {
offClick();
offError();
map.destroy();
}
window.addEventListener('pagehide', dispose, { once: true });
if (import.meta.hot)
import.meta.hot.dispose(() => {
window.removeEventListener('pagehide', dispose);
dispose();
});
}
void start().catch(() => {
document.querySelector('#map')!.textContent = '初始化失败,请检查 WebGL2 与 Cesium 资源路径';
});createMap 返回 Promise<MapInstance>,必须 await,初始化异常使用 try/catch 捕获。瓦片请求在此后异步发生,实例创建成功不等于底图已加载。 监听 error 并在真实浏览器中观察请求结果。不要用固定延时当作地图加载成功信号。
接下来
HTML 放入 index.html,CSS 放入 src/style.css,TypeScript 放入 src/main.ts;运行 npm run dev。Natural Earth 无需 Key,但只有低分辨率全球底图。天地图用自己的授权 Key:await map.setSource({ type: 'tianditu', key, style: 'vector' })。
想直接运行已有工程,可下载独立 Demo ZIP,解压后执行 npm ci、npm run dev;依赖安装需要网络。八类完整示例包含可运行源码与在线入口。