react接入腾讯地图自动定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
src="https://unpkg.com/react@18/umd/react.development.js"
crossorigin
></script>
<script
src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"
crossorigin
></script>
<!-- geolocation.min.js 参考腾迅地图https://lbs.qq.com/webApi/component/componentGuide/componentGeolocation -->
<script src="https://mapapi.qq.com/web/mapComponents/geoLocation/v/geolocation.min.js"></script>
<!-- /api/gljs?v=1.exp 参考https://lbs.qq.com/service/webService/webServiceGuide/webServiceOverview -->
<script src="https://map.qq.com/api/gljs?v=1.exp&key=申请key"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<title>自动定位</title>
<style>
* {
margin: 0;
padding: 0;
}
#app {
width: 100vw;
height: 100vh;
}
.mapWrapper {
/*地图(容器)显示大小*/
width: 100%;
height: 50%;
background-color: #009ddc;
position: relative;
}
.mapWrapper > .point {
position: absolute;
left: 48%;
top: 48%;
width: 20px;
height: 20px;
background-color: red;
border-radius: 50%;
}
.mapWrapper > .citys {
position: fixed;
bottom: 0;
left: 0;
height: 50vh;
}
</style>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
const key = "申请key";
function MapCom() {
let [citys, setCitys] = React.useState([]);
async function showPosition(position) {
// 2. 创建地图实例,并定义地图中心点坐标
const center = new TMap.LatLng(position.lat, position.lng);
const map = new TMap.Map(document.querySelector(".mapWrapper"), {
center, //设置地图中心点坐标
zoom: 15, //设置地图缩放级别
});
// 监听地图拖拽事件
map.on("dragend", () => {
getCitys(map);
});
getCitys(map); // 初始化加载地图时,根据中心点坐标获取周边地点列表
}
async function getCitys(map) {
// map.getCenter(): 获取地图中心点坐标;
const centerPos = map.getCenter();
// 根据中心点坐标请求周边地点信息。
const {
result: { pois },
} = await fetch(
`https://apis.map.qq.com/ws/geocoder/v1/?key=${key}&location=${centerPos.lat},${centerPos.lng}&get_poi=1`
).then((res) => res.json());
setCitys(pois);
}
function showErr() {
console.log("定位失败");
}
React.useEffect(() => {
// 1. 自动定位,获取当前位置信息
const geolocation = new qq.maps.Geolocation(key, "地图");
// geolocation.getLocation: 获取当前所在地理位置,调用一次即重新定位一次,定位数据比较精确。网页h5定位使用的电脑的定位机制,位置信息会存在较大的偏差。
geolocation.getLocation(showPosition, showErr);
}, []);
return (
<div className="mapWrapper">
<div className="point"></div>
<div className="citys">
{citys.map((c) => (
<p key={c.id}>{c.title}</p>
))}
</div>
</div>
);
}
const root = ReactDOM.createRoot(document.querySelector("#app"));
root.render(<MapCom />);
</script>
</body>
</html>