DEMO :https://mercurywang.github.io/demos/mapbox.html
1. 注册
这个是登录界面,需要点击下面的 Sign up 注册。
登录之后会生成一个 access token
写这篇文章的时候才发现原来一个自然月 30 天,超过 50000 次调用要收费的 。谁让你有世界地图呢,省着点用吧。
2.新建 HTML 文件
添加如下引用:
一个地图的容器:
样式:
#map {
width: 100%;
height: 100%;
position: relative;
}
添加 js 代码:
mapboxgl.accessToken = "your token";
//这里是个坐标[经度, 纬度]
const start = [12.4, 55.7];
let map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mapbox/streets-v11",
center: start,
zoom: 1
});
这样打开就能看见满屏的世界地图了
然后把上面参数中的 zoom 改为 9,添加了城市按钮样式后:
效果图
添加一个 fly function:
function fly(end, zoom) {
map.flyTo({
// These options control the ending camera position: centered at
// the target, at zoom level 9, and north up.
center: end,
zoom: zoom,
bearing: 0,
// These options control the flight curve, making it move
// slowly and zoom out almost completely before starting
// to pan.
speed: 0.8, // make the flying slow
curve: 1, // change the speed at which it zooms out
// This can be any easing function: it takes a number between
// 0 and 1 and returns another number between 0 and 1.
easing: function(t) {
return t;
}
});
}
点击按钮时调用 fly(), 这里目前写死的,以后补充一个根据地址查询经纬度的方法。
function copenhagen() {
fly(start, 9);
}
function malmo() {
fly([13.2, 55.6], 10.5);
}
function berlin() {
fly([13.35, 52.53], 11.5);
}
function shenyang() {
fly([123.5, 41.5], 9);
}
function beijing() {
fly([116.5, 40], 9);
}
function hongkong() {
fly([114.2, 22.3], 10);
}
function future() {
fly([133.2, -23.3], 4);
}