寫(xiě)在前面
WebGIS 開(kāi)發(fā)基礎(chǔ)之 Leaflet
1. GIS Web開(kāi)發(fā)基本概念:
GIS利职、Map滔灶、Layer、Feature员魏、Geometry丑蛤、Symbol、Data(Point撕阎、Polyline受裹、Polygon)、Renderer虏束、Scale棉饶、Project、Coordinates镇匀;
2. GIS Web 開(kāi)發(fā)概述:
架構(gòu)模式照藻、常用平臺(tái)和 SDK、二維汗侵、三維
3. 使用 Leaflet 開(kāi)發(fā)常用功能:
- 地圖加載(底圖類(lèi)型幸缕、切換)
- 地圖操作(縮放、平移晰韵、定位/書(shū)簽发乔、動(dòng)畫(huà))
- 圖層管理(加載、移除雪猪、調(diào)整順序)
- 要素標(biāo)繪(點(diǎn)/聚簇栏尚、線、面浪蹂,符號(hào)化/靜態(tài)動(dòng)態(tài))
- 屬性標(biāo)注(字段可選抵栈、樣式定制)
- 專(zhuān)題地圖(點(diǎn)告材、線、面古劲,渲染)
- 查詢(xún)定位(屬性查詢(xún)斥赋、空間查詢(xún)/周邊搜索/緩沖區(qū)/面查點(diǎn)線面/點(diǎn)線查面、圖屬互查产艾、綜合查詢(xún))
- 信息窗口(入口疤剑、Popup、定制)
- 坐標(biāo)轉(zhuǎn)換(地理與投影闷堡、不同地理坐標(biāo)系)
- 空間運(yùn)算(長(zhǎng)度面積測(cè)量隘膘、點(diǎn)取坐標(biāo)、緩沖區(qū)杠览、相交包含關(guān)系)
- 動(dòng)態(tài)監(jiān)控(固定點(diǎn)狀態(tài)切換弯菊、車(chē)輛監(jiān)控)
4. Leaflet 常用 API
<a >]</a>
Demo 用到的庫(kù)
- Flat-UI - 基于 Bootstrap 的一個(gè)扁平化風(fēng)格 web 開(kāi)發(fā)框架。
- Leaflet - 一個(gè)為建設(shè)交互性好適用于移動(dòng)設(shè)備地圖踱阿,而開(kāi)發(fā)的現(xiàn)代的管钳、開(kāi)源的 JavaScript 庫(kù)。
- Esri Leaflet - 一個(gè)輕量級(jí)的工具包软舌,基于 leaflet 利用 ArcGIS 服務(wù)才漆。
PART 1: 地圖加載(底圖類(lèi)型、切換) Demo 1
- 庫(kù)引用
<link rel="stylesheet" type="text/css" href="./lib/Flat-UI-master/dist/css/vendor/bootstrap/css/bootstrap.min.css"/>
<link rel="stylesheet" href="./lib/Flat-UI-master/dist/css/flat-ui.min.css">
<link rel="stylesheet" href="./lib/leaflet/leaflet.css">
<script src="./lib/Flat-UI-master/dist/js/vendor/jquery.min.js"></script>
<script src="./lib/Flat-UI-master/dist/js/flat-ui.js"></script>
<script src="./lib/leaflet/leaflet.js"></script>
<script src="./js/urlTemplate.js"></script>
- 地圖加載與切換
const map = L.map('mapDiv', {
crs: L.CRS.EPSG3857, //要使用的坐標(biāo)參考系統(tǒng)佛点,默認(rèn)的坐標(biāo)參考系醇滥,互聯(lián)網(wǎng)地圖主流坐標(biāo)系
// crs: L.CRS.EPSG4326, //WGS 84坐標(biāo)系,GPS默認(rèn)坐標(biāo)系
zoomControl: true,
// minZoom: 1,
attributionControl: false,
}).setView([31.626866, 104.152894], 18); //定位在成都北緯N30°37′45.58″ 東經(jīng)E104°09′1.44″
let Baselayer = L.tileLayer(urlTemplate.mapbox_Image, {
maxZoom: 17, //最大視圖
minZoom: 2, //最小視圖
attribution:
'liuvigongzuoshi@foxmail.com © <a ,
}).addTo(map);
console.log(Baselayer);
const setLayer = (ele) => {
map.removeLayer(Baselayer);
if (ele == 'mapbox_Image') {
Baselayer = L.tileLayer(urlTemplate.mapbox_Image, {
maxZoom: 17,
minZoom: 2,
}).addTo(map);
} else if (ele == 'mapbox_Vector') {
Baselayer = L.tileLayer(urlTemplate.mapbox_Vector, {
maxZoom: 17,
minZoom: 1,
}).addTo(map);
console.log(Baselayer);
}
};
PART 1.1:基于 Demo 1 利用 H5 Geolocation API 定位到當(dāng)前位置 Demo 1.1
- 庫(kù)引用 如上 Demo 1
<!-- marker高亮顯示庫(kù)引用 -->
<link rel="stylesheet" href="./lib/leaflet.marker.highlight/leaflet.marker.highlight.css">
<script src="./lib/leaflet.marker.highlight/leaflet.marker.highlight.js"></script>
- 判斷瀏覽器是否支持
let map;
let Baselayer;
// 使用H5 API定位 定位在當(dāng)前位置
if (navigator.geolocation) {
console.log('/* 地理位置服務(wù)可用 */');
navigator.geolocation.getCurrentPosition(h5ApiSuccess, h5ApiError);
} else {
console.log('/* 地理位置服務(wù)不可用 */');
mapInit([30.626866, 104.152894]); //指定一個(gè)數(shù)據(jù) 定位在成都北緯N30°37′45.58″ 東經(jīng)E104°09′1.44″
}
- 定位成功或失敗處理方法
const h5ApiSuccess = (position) => {
const latitude = position.coords.latitude; //緯度
const longitude = position.coords.longitude; //經(jīng)度
console.log('你的經(jīng)度緯度分別為' + longitude + ',' + latitude + '超营。');
return mapInit([latitude, longitude]);
};
const h5ApiError = () => {
console.log('/* 地理位置請(qǐng)求失敗 */');
mapInit([31.626866, 104.152894]); //指定一個(gè)數(shù)據(jù) 定位在成都北緯N30°37′45.58″ 東經(jīng)E104°09′1.44″
};
- 成功后初始化底圖
const mapInit = (LatLng) => {
map = L.map('mapDiv', {
crs: L.CRS.EPSG3857, //要使用的坐標(biāo)參考系統(tǒng)鸳玩,默認(rèn)的坐標(biāo)參考系,互聯(lián)網(wǎng)地圖主流坐標(biāo)系
// crs: L.CRS.EPSG4326, //WGS 84坐標(biāo)系糟描,GPS默認(rèn)坐標(biāo)系
zoomControl: true,
// minZoom: 1,
attributionControl: true,
}).setView(LatLng, 18); //定位在當(dāng)前位置
Baselayer = L.tileLayer(urlTemplate.mapbox_Image, {
maxZoom: 17, //最大視圖
minZoom: 2, //最小視圖
attribution:
'liuvigongzuoshi@foxmail.com © <a ,
}).addTo(map);
L.marker(LatLng, {
highlight: 'permanent', //永久高亮顯示
}).addTo(map);
console.log(Baselayer);
};
- 更多內(nèi)容
- 更多了解 geolocation 對(duì)象怀喉,可參考 MDN Web 文檔
- 更多了解使用 marker 高亮顯示,可參考 leaflet.marker.highlight 插件
- 基于 Demo 1 利用 leaflet 封裝好的 H5 定位 API,定位到當(dāng)前位置 Demo
PART 2: 地圖操作(縮放船响、平移、定位/書(shū)簽躲履、動(dòng)畫(huà)) Demo 2
庫(kù)引用 如上 Demo 1
設(shè)置地圖縮放到指定圖層
const setZoom = () => {
map.setZoom(10, {
// animate: false
}); //設(shè)置地圖縮放到
};
- 圖層往里進(jìn)一個(gè)圖層见间,放大
const setZoomIn = () => {
map.zoomIn(); //圖層往里進(jìn)一個(gè)圖層,放大
};
const setZoomOut = () => {
map.zoomOut(); //圖層往里出一個(gè)圖層工猜,縮小
};
- 地圖平移至中心點(diǎn)
const panTo = () => {
map.panTo([37.91082, 128.73583], {
animate: true,
}); //地圖平移米诉,默認(rèn)就是true,將地圖平移到給定的中心篷帅。如果新的中心點(diǎn)在屏幕內(nèi)與現(xiàn)有的中心點(diǎn)不同則產(chǎn)生平移動(dòng)作史侣。
};
- 地圖飛到中心點(diǎn)
const flyTo = () => {
map.flyTo([36.52, 120.31]); // 點(diǎn)到點(diǎn)的拋物線動(dòng)畫(huà)拴泌,平移加縮放動(dòng)畫(huà)
};
注意:盡量避免 setZoom()等地圖縮放方法與 flyTo、flyToBounds 一起合用惊橱,因?yàn)檫@兩類(lèi)地圖操作方法都有各自的縮放值蚪腐,造成動(dòng)畫(huà)不流暢、不能定位到目的點(diǎn)税朴。
- 地圖飛到邊界的合適的位置
const flyToBounds = () => {
map.flyToBounds(polygon.getBounds()); //getBounds(獲取邊界):返回地圖視圖的經(jīng)緯度邊界回季。
//飛到這個(gè)多變形區(qū)域上面,自動(dòng)判斷區(qū)域塊的大小正林,合適縮放圖層泡一,將地圖視圖盡可能大地設(shè)定在給定的地理邊界內(nèi)。
};
let polygon = L.polygon(
[
[37, -109.05],
[41, -109.03],
[41, -102.05],
[37, -102.04],
],
[40.774, -74.125],
{
color: 'green',
fillColor: '#f03',
fillOpacity: 0.5,
}
).addTo(map); //地圖上繪制一個(gè)多邊形
- 地圖定位到邊界的合適的位置
const fitBounds = () => {
console.log(polygon.getBounds());
map.fitBounds(polygon.getBounds()); //getBounds(獲取邊界):返回地圖視圖的經(jīng)緯度邊界觅廓。
//平移到一個(gè)區(qū)域上面鼻忠,自動(dòng)判斷區(qū)域塊的大小,合適縮放圖層
};
let polygon = L.polygon(
[
[37, -109.05],
[41, -109.03],
[41, -102.05],
[37, -102.04],
],
[40.774, -74.125],
{
color: 'green',
fillColor: '#f03',
fillOpacity: 0.5,
}
).addTo(map); //地圖上繪制一個(gè)多邊形
PART 3: 圖層管理(加載杈绸、移除帖蔓、調(diào)整順序): Demo 3
- 庫(kù)引用
<link rel="stylesheet" type="text/css" href="./lib/Flat-UI-master/dist/css/vendor/bootstrap/css/bootstrap.min.css"
/>
<link rel="stylesheet" href="./lib/Flat-UI-master/dist/css/flat-ui.min.css">
<link rel="stylesheet" href="./lib/leaflet/leaflet.css">
<script src="./lib/Flat-UI-master/dist/js/vendor/jquery.min.js"></script>
<script src="./lib/Flat-UI-master/dist/js/flat-ui.js"></script>
<script src="./lib/leaflet/leaflet.js"></script>
<!-- esri-leafleat插件 -->
<script src="./lib/esri-leaflet-v2.1.2/dist/esri-leaflet.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/proj4js/2.6.2/proj4.js"></script>
<script src="./js/urlTemplate.js"></script>
- 使用 esri-leaflet 插件加載 ArcGIS 底圖服務(wù)
let oMap = null;
let oLayer = [];
oMap = L.map('mapDiv', {
crs: L.CRS.EPSG4326,
zoomControl: false,
minZoom: 7,
attributionControl: false
}).setView([29.59, 106.59], 12); //定位在重慶
oLayer.push(L.esri.tiledMapLayer({
url: urlTemplate.SYS_IMG_MAPSERVER_PATH,
maxZoom: 17,
minZoom: 0,
useCors: false, //是否瀏覽器在跨域的情況下使用GET請(qǐng)求。
}).addTo(oMap)); //加載第一個(gè)底圖
oLayer.push(L.esri.tiledMapLayer({
url: urlTemplate.SYS_IMG_LABEL_MAPSERVER_PATH,
maxZoom: 17,
minZoom: 0,
useCors: false,
}).addTo(oMap)); //加載第二個(gè)底圖
- 切換底圖(移除及加載)
const setLayer = (layerUrls, maxZoom) => {
for (let i = 0; i < oLayer.length; i++) {
oMap.removeLayer(oLayer[i]); //將圖層在地圖上移除
}
oLayer = []; //制空數(shù)組
layerUrls.map((item) => {
oLayer.push(
L.esri
.tiledMapLayer({
url: item,
useCors: false, //是否瀏覽器在跨域的情況下使用GET請(qǐng)求蝇棉。
maxZoom: maxZoom,
})
.addTo(oMap)
);
});
};
不同的底圖可能圖層數(shù)不一樣讨阻,就可能造成瀏覽器去請(qǐng)求不存在的圖層,以及給用戶(hù)展示出空白區(qū)域的不好體驗(yàn)篡殷,所以切換圖層時(shí)候應(yīng)注意設(shè)置最大及最小縮放值钝吮。
PART 4: 要素標(biāo)繪(點(diǎn)、線板辽、面奇瘦,符號(hào)化/靜態(tài)動(dòng)態(tài)) Demo 4
庫(kù)引用 如上 Demo 1
畫(huà)一個(gè)圓
// 畫(huà)一個(gè)circle
const circle = L.circle([36.52, 120.31], {
color: 'green', //描邊色
fillColor: '#f03', //填充色
fillOpacity: 0.5, //透明度
radius: 10000 //半徑,單位米
}).addTo(map);
// 綁定一個(gè)提示標(biāo)簽
circle.bindTooltip('我是個(gè)圓');
- Maker 及自定義 Maker
// 做一個(gè)maker
const marker = L.marker([36.52, 120.31]).addTo(map);
// 綁定一個(gè)提示標(biāo)簽
marker.bindTooltip('這是個(gè)Marker', { direction: 'left' }).openTooltip();
//自定義一個(gè)maker
const greenIcon = L.icon({
iconUrl: './icon/logo.png',
iconSize: [300, 79], // size of the icon
popupAnchor: [0, -10] // point from which the popup should open relative to the iconAnchor
});
const oMarker = L.marker([36.52, 124.31], { icon: greenIcon }).addTo(map);
// 綁定一個(gè)提示標(biāo)簽
oMarker.bindTooltip('這是個(gè)自定義Marker', { direction: 'left', offset: [-150, 0] });
- 畫(huà)一根線
//畫(huà)一根線
const polyline = L.polyline([[45.51, -122.68], [37.77, -122.43], [34.04, -118.2]], { color: 'red' }).addTo(map);
// 飛到這個(gè)線的位置
map.fitBounds(polyline.getBounds());
- 畫(huà)一個(gè)多邊形
// 畫(huà)一個(gè)polygon
const polygon = L.polygon([
[[37, -109.05], [41, -109.03], [41, -102.05], [37, -102.04]], // outer ring
[[37.29, -108.58], [40.71, -108.58], [40.71, -102.50], [37.29, -102.50]] // hole
], {
color: 'green',
fillColor: '#f03',
fillOpacity: 0.5
}).addTo(map);
// 綁定一個(gè)提示標(biāo)簽
polygon.bindTooltip('this is 個(gè)多邊形');
// 飛到這個(gè)多邊形的位置
map.fitBounds(polygon.getBounds());
PART 5: 信息窗口(入口劲弦、Popup耳标、定制) Demo 5
庫(kù)引用 如上 Demo 1
畫(huà)一個(gè) circle 并綁定一個(gè) Popup
// 畫(huà)一個(gè)circle
const circle = L.circle([36.92, 121.31], {
color: 'green', //描邊色
fillColor: '#f03', //填充色
fillOpacity: 0.5, //透明度
radius: 10000 //半徑,單位米
}).addTo(map);
// 綁定一個(gè)彈窗
circle.bindPopup('我是個(gè)圓');
- 定位一個(gè) marker邑跪,綁定一個(gè)自定義 Popup
// 定位一個(gè)maker
const marker = L.marker([36.52, 120.31]).addTo(map);
//maker上自定義一個(gè)popup
const html = '<p>Hello world!<br />This is a nice popup.</p>';
const popup = marker.bindPopup(html, { maxHeight: 250, maxWidth: 490, className: 'content', offset: [0, 0] }).on('popupopen', function (params) {
console.log(params)
});
- 實(shí)現(xiàn)動(dòng)態(tài)改變 Popup 的內(nèi)容
const mypop = L.popup();
map.on('click', function (e) {
mypop.setLatLng(e.latlng)
.setContent('你臨幸了這個(gè)點(diǎn):<br>' + e.latlng.toString())
.openOn(map);
});
PART 6: geojson 數(shù)據(jù)繪制邊界(坐標(biāo)轉(zhuǎn)換次坡、渲染) Demo 6
庫(kù)引用 如上 Demo 3
獲得 geojson 并處理數(shù)據(jù)
// 請(qǐng)求geojson并處理數(shù)據(jù)
const population = () => {
$.get('./js/geojson.json', function (response) {
const poplData = response.data;
const PolygonsCenter = response.geopoint;
drawPolygons(poplData, PolygonsCenter);
});
};
Mock 返回的數(shù)據(jù) GeoJSON
- 繪制邊界并添加圖例
let oPolygon_VilPop = [];
const legend = L.control({
position: 'bottomright'
});
// 繪制邊界
const drawPolygons = (poplData, PolygonsCenter) => {
for (const i in poplData) {
poplData[i].geoJson = JSON.parse(poplData[i].geoJson);
oPolygon_VilPop[i] = L.geoJSON(poplData[i].geoJson, {
style: function () {
return {
color: 'white',
fillColor: getBgColor(poplData[i].population), //獲取邊界的填充色
fillOpacity: 0.6,
weight: 3,
dashArray: '10',
};
},
})
.bindTooltip(poplData[i].villageName + '<br><br>人口' + poplData[i].population + '人', {
direction: 'top',
})
.on({
mouseover: highlight, //鼠標(biāo)移動(dòng)上去高亮
mouseout: resetHighlight, //鼠標(biāo)移出恢復(fù)原樣式
click: zoomTo, //點(diǎn)擊最大化
})
.addTo(oMap);
}
// 添加圖例
legend.onAdd = legendHtml;
legend.addTo(oMap);
// 定位到該界限的中心位置
oMap.flyToBounds(PolygonsCenter);
};
- 返回邊界的填充色及圖列的樣式
const getBgColor = (d) => {
return d > 400
? '#800026'
: d > 300
? '#BD0026'
: d > 200
? '#FC4E2A'
: d > 100
? '#FD8D3C'
: d > 50
? '#FED976'
: '#FFEDA0';
};
const legendHtml = (map) => {
let div = L.DomUtil.create('div', 'legend locateVP_legend'),
grades = [0, 50, 100, 200, 400],
labels = [],
from,
to;
for (const i = 0; i < grades.length; i++) {
from = grades[i];
to = grades[i + 1];
labels.push(
'<i style="background:' + getBgColor(from + 1) + '"></i> ' + from + (to ? ' ∼ ' + to + '人' : '以上')
);
}
div.innerHTML = labels.join('<br>');
return div;
};
- 鼠標(biāo)移動(dòng)上去的事件、鼠標(biāo)移出的事件画畅、發(fā)生點(diǎn)擊的事件
const highlight = (e) => {
const layer = e.target;
layer.setStyle({
weight: 6,
color: '#fff',
fillOpacity: 0.9,
dashArray: '0',
});
};
const resetHighlight = (e) => {
const layer = e.target;
layer.setStyle({
color: 'white',
weight: 3,
fillOpacity: 0.6,
dashArray: '10',
});
};
const zoomTo = (e) => {
oMap.fitBounds(e.target.getBounds());
};
寫(xiě)在后面
國(guó)內(nèi)常用地圖服務(wù)資源加載插件
Leaflet.ChineseTmsProviders Provider for Chinese Tms Service
Leaflet 調(diào)用國(guó)內(nèi)各種地圖的功能十分復(fù)雜砸琅,幸好有 leaflet.ChineseTmsProviders 這個(gè)插件,這四種地圖直接就可以加載進(jìn)來(lái)轴踱,十分方便症脂。
使用方法很簡(jiǎn)單可點(diǎn)擊上面鏈接去 GitHub 看使用說(shuō)明,或拉這個(gè) demo下來(lái)來(lái)瞧一瞧代碼。
優(yōu)化 marker 相關(guān)的插件
提供了豐富多彩的圖標(biāo) Leaflet.awesome-markers, See the demo map
強(qiáng)大的集聚插件 Leaflet.markercluster, See the demo map
優(yōu)化的 label Leaflet.label, See the demo map
優(yōu)化重疊在一起的 markers OverlappingMarkerSpiderfier-Leaflet, See the demo map
優(yōu)化在邊框上顯示不在當(dāng)前視野中的 marker Leaflet.EdgeMarker, See the demo map
Leaflet 學(xué)習(xí)資料整理
- Leaflet-Develop-Guide ?? -開(kāi)發(fā)文檔及常用插件小結(jié)
模塊化開(kāi)發(fā)的加載包注意的問(wèn)題
- 引 leaflet 包的時(shí)候不要忘記引用包里的 css
import 'leaflet/dist/leaflet.css';
關(guān)于 Leaflet 和 esri-leaflet 一起使用 L.esri.TiledMapLayer 加載 ArcGIS 服務(wù)切片底圖時(shí)诱篷,控制臺(tái)打印報(bào)錯(cuò) Uncaught ReferenceError: proj4 is not defined
- 查看了下源碼
if (!proj4) { warn('L.esri.TiledMapLayer is using a non-mercator spatial reference. Support may be available through Proj4Leaflet http://esri.github.io/esri-leaflet/examples/non-mercator-projection.html');}
問(wèn)題就出在這里壶唤,esri-leaflet 里的一個(gè)插件 proj4leaflet 依賴(lài) proj4,所以需要手動(dòng)引入 proj4 這個(gè)包棕所。 - 這個(gè) GitHub 上面的提問(wèn)及回答 Github esri-leaflet Issues闸盔,原因是 leaflet 不支持該服務(wù)坐標(biāo)系,需要依賴(lài) proj4 進(jìn)行坐標(biāo)投影橙凳。
- 如果你是模塊化開(kāi)發(fā)蕾殴,需要再
npm i proj4
然后再引入進(jìn)來(lái)好了import * as proj4 from 'proj4'; window['proj4'] = proj4;
。 - 如果你是常規(guī)開(kāi)發(fā)岛啸,直接添加一個(gè) script 標(biāo)簽引用 CDN 資源上托管的 Proj4js 就是了
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.4/proj4-src.js"></script>
钓觉。
參考
- GIS 制圖樂(lè)園 esri-leaflet 入門(mén)教程(1)-leaflet 介紹
- Awesome GIS(GIS Tech Stack 技術(shù)棧)
- 麻辣 GIS Leaflet 學(xué)習(xí)筆記
本文 DEMO 地址: https://github.com/liuvigongzuoshi/leaflet-demo
原文首發(fā)地址 https://github.com/liuvigongzuoshi/blog