前言
我们这一节使用轻量化的javascript库leaflet来实现在html中加载天地图,实现类似高德地图、百度地图的效果。
效果图如下:
话不多说,进入主题!!
一、注册开发者权限
我们需要在天地图平台注册一个账号,然后申请成为开发者,我这里申请的是个人开发者,申请流程我就不做演示了。
天地图平台:https://www.tianditu.gov.cn/
进入开发者界面: 进入控制台,点击创建新应用:
填写对应的信息,点击提交,创建完成:
创建完成之后,我们会有一个Key名称,这个就相当于我们的秘钥,要保管好。
二、加载天地图
1、下载leaflet
leaflet下载地址:https://leafletjs.com/download.html
进入leaflet官网,下载最新的稳定版代码,如图:
下载完成之后,我们只需要保留主要的三个文件即可,images、leaflet.css、leaflet.js,将这三个文件导入我们的项目中,如图:
2、加载天地图
1、首先将css和js文件引入html中:
2、leaflet加载地图和echarts一样,也需要一个带框高的盒子才行,所以我们需要定义一个带宽高的div标签来装载地图,我们需要给div起一个id来唯一标识这个盒子(注意:不能使用class,否则leaflet识别不了):
#map {
position: absolute;
width: 100%;
height: 100vh;
left: 0;
top: 0;
}
3、编写js代码加载天地图:
//设置底图
const map = L.map("map",{
center: [23.82319, 109.02358], //中心点[纬度,经度]
zoom: 6, //默认缩放等级
crs: L.CRS.EPSG4326 //采用wgs84坐标系
});
//开发key
const key = "xxxxxx";
//xyz方式加载底图
const tdt_url_bottom = "https://t0.tianditu.gov.cn/DataServer?T=img_c&x={x}&y={y}&l={z}&tk=";
//xyz方式加载底图的标注
const tdt_url_label = "https://t0.tianditu.gov.cn/DataServer?T=cia_c&x={x}&y={y}&l={z}&tk=";
//设置底图图层(url请求地址,偏移量,贴片尺寸大小,最小缩放等级,最大缩放层级)
const layer_bottom = L.tileLayer(tdt_url_bottom + key, {
zoomOffset: 1,
tileSize: 256,
minZoom: 7,
maxZoom: 17
});
//设置底图标注
const layer_label = L.tileLayer(tdt_url_label + key, {
zoomOffset: 1,
tileSize: 256,
minZoom: 7,
maxZoom: 17
});
//将图层丢到地图上
layer_bottom.addTo(map);
layer_label.addTo(map)
4、效果如图:
三、去掉左上角的缩放图标以及右下角的logo
在创建地图时,在option中设置两个属性即可:
const map = L.map("map",{
center: [23.82319, 109.02358], //[纬度,经度]
zoom: 6, //默认缩放层级和layer的最小缩放层级一致
crs: L.CRS.EPSG4326, //坐标系的代码
zoomControl: false, //去掉左上角缩放图标
attributionControl: false //去掉右下角的logo
});
总结
完成代码如下:
#map {
position: absolute;
width: 100%;
height: 100vh;
left: 0;
top: 0;
}
//设置底图
const map = L.map("map",{
center: [23.82319, 109.02358], //[纬度,经度]
zoom: 6, //默认缩放等级
crs: L.CRS.EPSG4326 //wgs84坐标系的代码
});
//开发key
const key = "xxxx";
//xyz方式加载底图
const tdt_url_bottom = "https://t0.tianditu.gov.cn/DataServer?T=img_c&x={x}&y={y}&l={z}&tk=";
//xyz方式加载底图标注
const tdt_url_label = "https://t0.tianditu.gov.cn/DataServer?T=cia_c&x={x}&y={y}&l={z}&tk=";
//设置底图图层(url请求地址,偏移量,贴片尺寸大小,最大缩放层级)
const layer_bottom = L.tileLayer(tdt_url_bottom + key, {
zoomOffset: 1,
tileSize: 256,
minZoom: 7,
maxZoom: 17
});
//设置底图标注
const layer_label = L.tileLayer(tdt_url_label + key, {
zoomOffset: 1,
tileSize: 256,
minZoom: 7,
maxZoom: 17
});
//将图层丢到地图上
layer_bottom.addTo(map);
layer_label.addTo(map)
精彩链接
发表评论