mapbox-gl的学习过程之自定义移动的图片点(模拟物体移动)
项目上 有使用到mapbox地图 学习记录一下,以下是代码: mapbox官方文档
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Guides</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<!-- npm i mapbox-gl -->
<link rel="stylesheet" href="./node_modules/mapbox-gl/dist/mapbox-gl.css" />
<script src="./node_modules/mapbox-gl/dist/mapbox-gl.js"></script>
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
// TO MAKE THE MAP APPEAR YOU MUST
// ADD YOUR ACCESS TOKEN FROM
// https://account.mapbox.com
// 引入Mapbox GL JS库
// 初始化地图
// 首先,确保Mapbox.js已经在你的页面中被引入
// mapboxgl.accessToken = 'YOUR_MAPBOX_ACCESS_TOKEN'; // 替换为你的Mapbox访问令牌
var map = new mapboxgl.Map({
container: "map", // 地图容器的id
style: "mapbox://styles/mapbox/streets-v11", // 地图样式
center: [116, 39], // 初始中心点坐标
zoom: 1, // 初始缩放级别
});
map.on("load", function () {
// 添加一个初始位置的点
var customImageId = "custom-marker";
// 加载自定义图片
map.loadImage(
"https://p9-passport.byteacctimg.com/img/mosaic-legacy/3797/2889309425~90x90.png",
function (error, image) {
if (error) throw error;
// 添加自定义图片到Mapbox
map.addImage(customImageId, image);
map.addSource("point", {
type: "geojson",
data: {
type: "FeatureCollection",
features: [
{
type: "Feature",
geometry: {
type: "Point",
coordinates: [116, 39],
},
},
],
},
});
map.addLayer({
id: "point-layer",
type: "symbol",
source: "point",
layout: {
"icon-image": customImageId,
"icon-size": 0.1,
},
});
}
);
// 移动点的函数
function movePoint() {
// 获取当前点的位置
var point = map.getSource('point')._data.features[0].geometry.coordinates;
// 更新点的位置
point[0] += 0.001; // 更新经度
point[1] += 0.001; // 更新纬度
// 更新源数据
map.getSource('point').setData({
type: "FeatureCollection",
features: [
{
type: "Feature",
geometry: {
type: "Point",
coordinates: point,
},
},
],
});
}
// 每隔一定时间移动点
setInterval(movePoint, 500); // 每100毫秒移动一次点
});
</script>
</body>
</html>