index.html中添加天地图所使用的js文件
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React</title>
<script type="text/javascript" src="http://api.tianditu.gov.cn/api?v=4.0&tk=密钥"></script>
<script src="http://cdn.bootcss.com/d3/3.5.17/d3.js " charset="utf-8"></script>
<script src="http://lbs.tianditu.gov.cn/api/js4.0/opensource/openlibrary/D3SvgOverlay.js"></script>
<script src="http://lbs.tianditu.gov.cn/api/js4.0/opensource/openlibrary/CarTrack.js"></script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
相关js代码
import {useEffect, useState} from "react";
const coordinates = [
[116.26802, 39.90623],
[116.28896, 39.90622],
[116.30421, 39.90625],
[116.3155, 39.90618],
[116.3313, 39.90611],
[116.34643, 39.90538],
[116.35033, 39.90582],
]
function App() {
const [map, setMap] = useState(null);
const [zoom, setZoom] = useState(13);
const [CarTrack, setCarTrack] = useState(null);
useEffect(() => {
const tile = new window.T.TileLayer("http://t4.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=密钥");
const mapInst = new window.T.Map("mapDiv", {layers: [tile]});
setMap(mapInst);
}, []);
useEffect(() => {
if (map) {
onLoad()
}
}, [map])
useEffect(() => {
if (map) {
getCarTrack(coordinates);
}
}, [map])
function onLoad() {
map.centerAndZoom(new window.T.LngLat(116.318090, 39.920270), zoom);
}
function getCarTrack(datas) {
const CarTrackInst = new window.T.CarTrack(map, {
interval: 5,
speed: 10,
dynamicLine: true,
polylinestyle: {color: "#2C64A7", weight: 5, opacity: 0.9},
Datas: datas.map(function (coordinates) {
console.log("datadata", coordinates)
var lnlat = new window.T.LngLat(coordinates[0], coordinates[1]);
return lnlat;
}
)
})
setCarTrack(CarTrackInst)
}
function handleStart() {
CarTrack.start();
}
function handlePause() {
CarTrack.pause()
}
function handleEnd() {
CarTrack.stop()
}
return (
<>
<div>首页</div>
<div id="mapDiv" style={{width: 1000, height: 1000}}></div>
<input type="button" value="开始" onClick={handleStart}/>
<input type="button" value="暂停" onClick={handlePause}/>
<input type="button" value="结束" onClick={handleEnd}/>
</>
)
}
export default App
效果
