再補充(2019年4月8日)
國家天地圖地圖服務需要攜帶key才能通路。别忘了去官網申請key。
補充(2018年8月2日)
現在leaflet.js已經支援EPSG4326。如果你使用的是新版本的leaflet,那麼通過簡單的配置就能實作:
var map = L.map('mapid', {
crs: L.CRS.EPSG4326
}).setView([30, 120], 15);
L.tileLayer('http://t1.tianditu.com/vec_c/wmts?layer=vec&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}', {
maxZoom: 20,
tileSize: 256,
zoomOffset: 1
}).addTo(map );
如果你使用的是早版本的leaflet,那麼下面的介紹會幫助你。
問題描述
使用Leaflet,主要是看中了它輕便、跨平台的特性。
1.Leaflet無法直接加載WMTS服務。
2.使用Leaflet擴充插件leaflet-tilelayer-wmts.js加載wmts,預設是隻支援EPSG3857.無法支援EPSG4326.
Leaflet預設坐标系是EPSG3857,而天地圖使用的投影方式是EPSG4326或者900913。
這樣完全加不上嘛!
解決之道
檢視leaflet-tilelayer-wmts.js源代碼,試試能否找到解決方法。試了試,完全看不懂哎。我覺得我有必要再學習下EPSG和WMTS的相關知識了。
通過查找相關資料和代碼分析,大體了解了切片的方式和加載的大緻原理。
再回到leaflet-tilelayer-wmts.js,修改了内部的getDefaultMatrix方法:
原來的代碼是:
getDefaultMatrix : function () {
/**
* the matrix3857 represents the projection
* for in the IGN WMTS for the google coordinates.
*/
var matrixIds3857 = new Array(22);
for (var i= 0; i<22; i++) {
matrixIds3857[i]= {
identifier : "" + i,
topLeftCorner : new L.LatLng(20037508.3428,-20037508.3428)
};
}
return matrixIds3857;
}
隻改一個地方:
getDefaultMatrix : function () {
/**
* the matrix3857 represents the projection
* for in the IGN WMTS for the google coordinates.
*/
var matrixIds3857 = new Array(22);
for (var i= 0; i<22; i++) {
matrixIds3857[i]= {
identifier : "" + i,
topLeftCorner : new L.LatLng(90,-180)
};
}
return matrixIds3857;
}
被自己的無恥打動了,就那麼一個地方。
然後改改變量名稱就可以了
總結
需要注意的地方,投影方式要一緻。
比如加載時:
var url='http://t0.tianditu.com/vec_c/wmts';
var emap = new L.TileLayer.WMTS( url ,
{
tileSize:256,
layer: 'vec',
style: "default",
tilematrixSet: "c",
format: "tile",
attribution: "<a href='https://github.com/mylen/leaflet.TileLayer.WMTS'>GitHub</a>© <a href='http://www.ign.fr'>IGN</a>"
}
);
var map = L.map('map',{crs:L.CRS.EPSG4326,center: {lon:112 , lat:40},zoom: 13})
map.addLayer(emap)
最後看結果(隻加載了一個矢量圖層):

Demo下載下傳