leaflet加載國家天地圖服務

再補充(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>&copy; <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下載

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章