Leaflet
[email protected]
2016年10月9日
2016年10月11日添加統計圖
2016年10月17日添加Identify
1 目标:實作HTML展示地圖的功能。
在WEB頁面展示線上的地圖服務,并實作常用的地圖操作,完成各種地圖互動,顯示各種地圖資料等功能。
2原理:JS+CSS實作各種地圖服務、資源的展示和控制。
通過JS+CSS按照各種地圖服務标準,擷取地圖資料,通過HTML展示、控制、互動等。
Leaflet核心包實作了标準地圖服務、資源的展示和控制,其它地圖服務需要使用插件實作,如arcgis地圖服務需要使用arcgis的插件才能加載,google地圖服務不對外開放,需要使用google map的api 插件才能加載。
Leaflet主要元件是map,使用一個div作為地圖的容器,在其中展示地圖。Leaflet使用L對象作為所有Leaflet的基本對象。
參考:http://leafletjs.com/reference-1.0.0.html#map-example
http://leafletjs.com/examples.html
3方法:Leaflet基本類型
參考:http://leafletjs.com/examples/quick-start/
http://leafletjs.com/reference-1.0.0.html
3.1 地圖Map:L.map
初始化:L.map(“div id”)。
3.2 圖層:tileLayer,tileLayer.wms等多種類型的圖層。
3.2.1 TMS:tileLayer
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',{
attribution: '© <ahref="http://osm.org/copyright" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >OpenStreetMap</a>contributors'
}).addTo(map);
3.2.2 WMS:tileLayer.wms
varwmsBhxq = L.tileLayer.wms('http://localhost:8087/geoserver/bhxq/wms?', {
layers: 'bhxq:bhxq',
format: 'image/png',
transparent: true,
attribution: "Map© 2016 XXZX"
}).addTo(mymap);
varmymap = L.map('mapid').setView([38.88, 117.58], 10);
varwmsTDHBaseMap =L.tileLayer.wms('http://111.160.249.157:8095/Tile/WMS/BHGGVECTORBLEND.gis', {
layers: 'bhggvectorblend',
crs:L.CRS.EPSG4326,
format: 'image/png',
transparent: true,
attribution: "Map© 2016 XXZX"
}).addTo(mymap);
3.2.2.1 标準的WMS不支援GetFeatureInfo(),可以通過插件實作元素資訊查詢功能。
插件位址:https://github.com/heigeo/leaflet.wms
原理:添加identify啟用功能(預設啟用),通過GetFeatureInfo()送出ajax請求資料,parseFeatureInfo()處理傳回值,ShowFeatureInfo()将結果顯示在Map上。
示例:參見:Identify地圖元素資訊:點選地圖顯示圖層對應元素的資訊
3.2.3 WMTS:不能直接加載,需要使用插件L.tileLayer.WMTS加載。
3.3 地圖元素:Marker,Popup,Tooltip
3.3.1 圖示Marker:L.marker(坐标).addTo(地圖)。
Div作為Marker的圖示:L.divIcon()。
varmyDivIcon=L.divIcon({
className:'leaflet-echart-icon',
iconSize:[160, 160],
html:'<div id="marker1" style="width: 160px; height: 160px;position: relative; background-color: transparent;">asd</div>'
});
varmarker=L.marker([51.5, -0.09],{icon:myDivIcon}).addTo(map);
3.3.2 氣泡Popup:marker.bindPopup('pop <br>OK.').openPopup();
3.4 地圖控件:zoom,layers等固定的不随map移動上的HTML元素。
L.control.layers(null,baseLayers).addTo(mymap);
添加控件:L.control(),指定位置postion,指定内容onAdd。
varchartControl=L.control({position:'bottomright'});
chartControl.onAdd=function(map){
vardiv=L.DomUtil.create('div','info div');
div.id="chartdiv";
div.style="width:500px;height: 300px; background-color: white;";
returndiv;
};
chartControl.addTo(map);
自定義控件:
3.5 事件event:事件的響應函數可以擷取事件參數。
mymap.on('click', onMapClick);
4應用
注意:div style中width,height 100%無效的問題,添加html,body的style解決。
html, body{ margin:0;height:100%; }
參考:http://www.weste.net/2014/4-28/96579.html
http://www.cnblogs.com/shitao/p/5604652.html
4.1 基本展示
參考:http://leafletjs.com/examples/quick-start/
//index.htm
<!DOCTYPE html>
<html>
<head>
<metacharset="utf-8" />
<linkrel="stylesheet" href="js/leaflet/leaflet.css" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" />
<styletype="text/css">
html, body{ margin:0;height:100%; }
#map{ height:100%;width:100%;}
</style>
<scripttype="text/javascript" src="js/leaflet/leaflet-src.js"></script>
<title>LeafletDemo</title>
</head>
<body>
<divid='map'></div>
<scripttype="text/javascript">
varmap=L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',{
attribution: '© <ahref="http://osm.org/copyright" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >OpenStreetMap</a>contributors'
}).addTo(map);
L.marker([51.5,-0.09]).addTo(map).bindPopup('A pretty CSS3 popup.<br> Easilycustomizable.').openPopup();
</script>
</body>
</html>
4.2 圖層控制
//bhxq.htm
<!DOCTYPE html>
<html>
<head>
<metacharset="UTF-8">
<linkrel="stylesheet" href="js/leaflet/leaflet.css" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" />
<style>
html, body{margin:0; height:100%; }
#mapid {height:100%;width: 100%;}
</style>
<scripttype="text/javascript" src="js/leaflet/leaflet-src.js"></script>
<title>濱海新區</title>
</head>
<body>
<divid="mapid"></div>
<scripttype="text/javascript">
var mymap =L.map('mapid').setView([38.88, 117.58], 10);
var wmsBhxq =L.tileLayer.wms('http://localhost:8087/geoserver/bhxq/wms?', {
layers: 'bhxq:bhxq',
format: 'image/png',
transparent: true,
attribution: "Map© 2016 XXZX"
}).addTo(mymap);
var wmsRoad =L.tileLayer.wms('http://localhost:8087/geoserver/bhxq/wms?', {
layers: 'bhxq:主要道路',
format:'image/png',
transparent: true,
attribution: "Map© 2016 XXZX"
}).addTo(mymap);
var wmsPlace =L.tileLayer.wms('http://localhost:8087/geoserver/bhxq/wms?', {
layers: 'bhxq:行政地名',
format:'image/png',
transparent: true,
attribution: "Map© 2016 XXZX"
}).addTo(mymap);
var baseLayers ={
"濱海新區":wmsBhxq,
"主要道路":wmsRoad,
"行政地名":wmsPlace
};
L.control.layers(null,baseLayers).addTo(mymap);
var popup =L.popup();
functiononMapClick(e) {
popup.setLatLng(e.latlng).setContent("You clicked the map at "+ e.latlng.toString()).openOn(mymap);
}
mymap.on('click',onMapClick);
</script>
</body>
</html>
4.3 地圖+統計圖:leaflet顯示echarts圖表
ECharts參見:..\Net\ECharts.docx
參考:http://www.cnblogs.com/shitao/p/5604652.html
4.3.1 地圖點選氣泡顯示ECharts圖表
目标:在leaflet地圖點選氣泡顯示ECharts圖表。
原理:leaflet地圖的marker中顯示ECharts圖表的HTML。
//popup.htm
<!DOCTYPE html>
<html>
<head>
<metacharset="utf-8" />
<styletype="text/css">
html, body{margin:0; height:100%; }
#map {height:100%;width:100%;}
</style>
<linkrel="stylesheet" href="js/leaflet/leaflet.css" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" />
<script type="text/javascript"src="js/leaflet/leaflet-src.js" ></script>
<scripttype="text/javascript" src="js/echarts/echarts.js"></script>
<title>LeafletCharts Demo</title>
</head>
<body>
<divid='map'></div>
<scripttype="text/javascript">
varmap=L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',{
attribution: '© <ahref="http://osm.org/copyright" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >OpenStreetMap</a>contributors'
}).addTo(map);
varmarker=L.marker([51.5, -0.09]).addTo(map);
var content ='<div style="width: 280px; height: 280px;"id="marker2"></div>';
marker.bindPopup(content,{});
marker.on('popupopen',function(e) {
// 基于準備好的dom,初始化echarts執行個體
var myChart =echarts.init(document.getElementById('marker2'));
// 指定圖表的配置項和資料
option = {
tooltip: {
trigger: 'axis'
},
xAxis: [{
type: 'category',
data: ['1月', '2月', '3月', '4月']
}],
yAxis: [{
type: 'value',
name: '水量(ml)',
min: 0,
max: 50,
interval: 50,
axisLabel: {
formatter: '{value} '
}
}, {
type: 'value',
name: '溫度(°C)',
min: 0,
max: 10,
interval: 5,
axisLabel: {
formatter: '{value} '
}
}],
series: [{
name: '蒸發量',
type: 'bar',
data: [2.0, 4.9, 7.0, 23.2]
}, {
name: '降水量',
type: 'bar',
data: [2.6, 5.9, 9.0, 26.4]
}, {
name: '平均溫度',
type: 'line',
yAxisIndex: 1,
data: [2.0, 2.2, 3.3, 4.5]
}]
};
// 使用剛指定的配置項和資料顯示圖表。
myChart.setOption(option);
});
</script>
</body>
</html>
4.3.2 地圖固定位置顯示ECharts圖表
目标:在leaflet地圖固定位置顯示ECharts圖表。
原理:leaflet地圖的控件,在此控件上顯示chart的html。
//mapcharts_control.html
<!DOCTYPE html>
<html>
<head>
<metacharset="utf-8" />
<styletype="text/css">
html, body{margin:0; height:100%; }
#map {height:100%;width:100%;}
</style>
<linkrel="stylesheet" href="js/leaflet/leaflet.css" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" />
<scripttype="text/javascript" src="js/leaflet/leaflet-src.js"></script>
<scripttype="text/javascript" src="js/echarts/echarts.js"></script>
<title>LeafletMap Charts Control Demo</title>
</head>
<body>
<divid='map'></div>
<scripttype="text/javascript">
varmap=L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',{
attribution: '© <ahref="http://osm.org/copyright" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >OpenStreetMap</a>contributors'
}).addTo(map);
varmarker=L.marker([51.5, -0.09]).addTo(map);
var content = '<div style="width: 280px; height:280px;" id="marker2"></div>';
marker.bindPopup(content,{});
marker.on('popupopen',function(e) {
var myChart= createChart('marker2');
});
//create controlchart
var chartControl=L.control({position:'bottomright'});
chartControl.onAdd=function(map){
vardiv=L.DomUtil.create('div','info div');
div.id="chartdiv";
div.style="width:500px;height: 300px; background-color: white;";
returndiv;
};
chartControl.addTo(map);
createChart('chartdiv');
//creat echarts
functioncreateChart(divid){
// 基于準備好的dom,初始化echarts執行個體
var myChart= echarts.init(document.getElementById(divid));
// 指定圖表的配置項和資料
option = {
tooltip: {
trigger: 'axis'
},
xAxis: [{
type: 'category',
data: ['1月', '2月', '3月', '4月']
}],
yAxis: [{
type: 'value',
name: '水量(ml)',
min: 0,
max: 50,
interval: 50,
axisLabel: {
formatter: '{value} '
}
}, {
type: 'value',
name: '溫度(°C)',
min: 0,
max: 10,
interval: 5,
axisLabel: {
formatter: '{value} '
}
}],
series: [{
name: '蒸發量',
type: 'bar',
data: [2.0, 4.9, 7.0, 23.2]
}, {
name: '降水量',
type: 'bar',
data: [2.6, 5.9, 9.0, 26.4]
}, {
name: '平均溫度',
type: 'line',
yAxisIndex: 1,
data: [2.0, 2.2, 3.3, 4.5]
}]
};
// 使用剛指定的配置項和資料顯示圖表。
myChart.setOption(option);
returnmyChart;
}
</script>
</body>
</html>
4.3.3 地圖直接顯示ECharts圖表
目标:在leaflet地圖坐标直接顯示ECharts圖表。
原理:leaflet地圖的marker上,以echarts的html作為marker的divicon。
<!DOCTYPE html>
<html>
<head>
<metacharset="utf-8" />
<style type="text/css">
html, body{margin:0; height:100%; }
#map {height:100%;width:100%;}
</style>
<linkrel="stylesheet" href="js/leaflet/leaflet.css" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" />
<scripttype="text/javascript" src="js/leaflet/leaflet-src.js"></script>
<script type="text/javascript"src="js/echarts/echarts.js" ></script>
<title>LeafletMap Charts Control Demo</title>
</head>
<body>
<divid='map'></div>
<scripttype="text/javascript">
varmap=L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',{
attribution: '© <ahref="http://osm.org/copyright" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >OpenStreetMap</a>contributors'
}).addTo(map);
var myDivIcon=L.divIcon({
className:'leaflet-echart-icon',
iconSize:[160, 160],
html:'<div id="marker1" style="width: 160px; height: 160px;position: relative; background-color: transparent;">asd</div>'
});
varmarker=L.marker([51.5, -0.09],{icon:myDivIcon}).addTo(map);
createChart("marker1");
//creat echarts
functioncreateChart(divid){
// 基于準備好的dom,初始化echarts執行個體
var myChart= echarts.init(document.getElementById(divid));
// 指定圖表的配置項和資料
option = {
tooltip: {
trigger: 'axis'
},
xAxis: [{
type: 'category',
data: ['1月', '2月', '3月', '4月']
}],
yAxis: [{
type: 'value',
name: '水量(ml)',
min: 0,
max: 50,
interval: 50,
axisLabel: {
formatter: '{value} '
}
}, {
type: 'value',
name: '溫度(°C)',
min: 0,
max: 10,
interval: 5,
axisLabel: {
formatter: '{value} '
}
}],
series: [{
name: '蒸發量',
type: 'bar',
data: [2.0, 4.9, 7.0, 23.2]
}, {
name: '降水量',
type: 'bar',
data: [2.6, 5.9, 9.0, 26.4]
}, {
name: '平均溫度',
type: 'line',
yAxisIndex: 1,
data: [2.0, 2.2, 3.3, 4.5]
}]
};
// 使用剛指定的配置項和資料顯示圖表。
myChart.setOption(option);
returnmyChart;
}
</script>
</body>
</html>
4.4 Identify地圖元素資訊:點選地圖顯示圖層對應元素的資訊
4.4.1 目标:通過點選擷取地圖元素資訊,在前台氣泡展示。
4.4.2 原理:前台使用leaflet.wms.js插件通過jQuery Ajax請求WMS資料,WMS傳回資料并在leaflet上展示。使用Mule進行異步跨域操作。
4.4.3 流程
4.4.3.1 添加leaflet.wms插件:使用leaflet.wms.js插件
<script type="text/javascript" src="js/leaflet/leaflet.wms.js"></script>
4.4.3.2 自定義結果顯示:擴充leaflet.wms的source。
var MySource =L.WMS.Source.extend({
'parseFeatureInfo': function(result, url) {
// Hook to handle parsing AJAX response
if (result == "error") {
// AJAX failed, possibly due toCORS issues.
// Try loading content in<iframe>.
result = "<iframesrc='" + url + "' style='border:none'>";
}
return result;
},
'showFeatureInfo': function(latlng, info) {
console.log(info);
// Hook to handle displayingparsed AJAX response to the user
if (!this._map) {
return;
}
this._map.openPopup(info, latlng);
}
});
4.4.3.3 添加查詢圖層:添加需要顯示資訊的圖層
var source = newMySource("http://localhost:8081/geoserver/bhxq/wms?",{
'transparent': true,
format:'image/png',
attribution: "Map© 2016 XXZX"
});
varwmsPlace=source.getLayer("bhxq:行政地名").addTo(mymap);
4.4.3.4 将跨域的WMS服務進行同域轉發:MULE
參見:..\ESB\Mule.docx 《GET請求參數轉發-WMS GetFeatureInfo消息轉發》 部分。
4.4.3.5 完整代碼
//identify.html
<!DOCTYPE html>
<html>
<head>
<metacharset="UTF-8">
<linkrel="stylesheet" href="js/leaflet/leaflet.css" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" />
<style>
html, body{margin:0; height:100%; }
#mapid {height:100%;width: 100%;}
</style>
<scripttype="text/javascript" src="js/leaflet/leaflet-src.js"></script>
<scripttype="application/javascript" src="js/jquery-3.1.1.js"></script>
<scripttype="text/javascript"src="js/leaflet/leaflet.wms.js"></script>
<title>Identify</title>
</head>
<body>
<divid="mapid"></div>
<scripttype="text/javascript">
//map
var mymap =L.map('mapid').setView([38.88, 117.58], 10);
var wmsBhxq =L.tileLayer.wms('http://localhost:8087/geoserver/bhxq/wms?', {
layers: 'bhxq:bhxq',
format: 'image/png',
transparent: true,
attribution: "Map© 2016 XXZX"
}).addTo(mymap);
var wmsRoad =L.tileLayer.wms('http://localhost:8087/geoserver/bhxq/wms?', {
layers: 'bhxq:主要道路',
format:'image/png',
transparent: true,
attribution: "Map© 2016 XXZX"
}).addTo(mymap);
//add identifylayer
var MySource =L.WMS.Source.extend({
'parseFeatureInfo': function(result, url) {
// Hook to handle parsing AJAX response
if (result == "error") {
// AJAX failed, possibly due toCORS issues.
// Try loading content in<iframe>.
result = "<iframesrc='" + url + "' style='border:none'>";
}
return result;
},
'showFeatureInfo': function(latlng, info) {
console.log(info);
// Hook to handle displayingparsed AJAX response to the user
if (!this._map) {
return;
}
this._map.openPopup(info, latlng);
}
});
var source = newMySource("http://localhost:8081/geoserver/bhxq/wms?",{
'transparent':true,
format:'image/png',
attribution: "Map© 2016 XXZX"
});
varwmsPlace=source.getLayer("bhxq:行政地名").addTo(mymap);
var baseLayers ={
"濱海新區":wmsBhxq,
"主要道路":wmsRoad,
"行政地名":wmsPlace
};
L.control.layers(null, baseLayers).addTo(mymap);
</script>
</body>
</html>
4.4.3.6 運作結果
4.5 Identify地圖元素資訊:JSONP跨域操作
4.5.1 目标:通過點選擷取地圖元素資訊,在前台氣泡展示。
4.5.2 原理:前台使用leaflet.wms.js插件通過jQuery Ajax JSONP請求WMS資料,GeoServer傳回JSONP資料調用回調函數(預設parseResponse(json)),leaflet調用identify的處理函數(parseFeatureInfo()處理資料,showFeatureInfo()顯示資料)上展示。
JSONP原理參見:..\Net\jQuery.docx《JSONP》部分。
GeoServer要求使用info_format=text/javascript辨別jsonp請求。
url = this._url + L.Util.getParamString(params, this._url)+'&info_format=text/javascript';//usejsonp
用戶端使用datatype=jsonp辨別。
$.ajax({
type:"get",
url: url,
dataType:'jsonp'
});
GeoServer開啟JSONP支援參見:GeoServer.docx《JSONP》部分。
注意:如果跨域不成功,可以使用iframe進行基本展示。
result = "<iframesrc='" + url + "' style='border:none'>";
注意:由于jsonp調用指定函數,需要暴露parseResponse()函數(為什麼不能調用success()???)。
4.5.3 流程:
4.5.3.1 GeoServer伺服器開啟JSONP支援
參見:GeoServer.docx《JSONP》部分。
4.5.3.2 添加leaflet.wms插件:使用leaflet.wms.js插件
<scripttype="text/javascript"src="js/leaflet/leaflet.wms.js"></script>
4.5.3.3 構造JSONP請求、自定義結果顯示:擴充leaflet.wms的source。
URL添加info_format=text/javascript辨別為jsonp請求。format_options=callback:回調函數名指定回調函數。
ajax添加datatype=jsonp辨別。jsonpCallback:回調函數名在jquery中注冊回調函數,有jquery進行轉碼。
//JSON Identify Object
var DataCenterSource =L.WMS.Source.extend({
'getFeatureInfo': function(point, latlng, layers, callback){//request wms jsonp info
// Request WMSGetFeatureInfo and call callback with results
// (split from identify()to faciliate use outside of map events)
varsuccessFunction='success_parseResponse';
var params =this.getFeatureInfoParams(point, layers),
url = this._url +L.Util.getParamString(params, this._url)+'&info_format=text/javascript'+'&format_options=callback:'+successFunction;//usejsonp,指定jsonp的回調函數
this._wms_url=url;//for iframe get request
this.showWaiting();
this.clickPos=latlng;//popup position
$.ajax({
async:false,
type: "get",
url: url,
dataType:'jsonp',
jsonpCallback:successFunction,
success:function(response){//thisfunction will be called by jsonpCallback function
console.log('success');
//console.log(source);
source.hideWaiting();
var text = source.parseFeatureInfo(response,source._url_wms);
source.showFeatureInfo(source.clickPos,JSON.stringify(text));
}
});
},
'parseFeatureInfo': function(result, url){//process response info here
// Hook to handle parsing AJAX response
if (result == "error") {
// AJAX failed, possibly due toCORS issues.
// Try loading content in<iframe>.
result = "<iframe src='" + url +"' style='border:none'>";
}
return result;
},
'showFeatureInfo': function(latlng, info){//open popup
console.log('showFeatureInfo='+info);
// Hook to handle displayingparsed AJAX response to the user
if(!this._map) {
return;
}
this._map.openPopup(info, latlng);
}
});
4.5.3.4 添加查詢圖層:添加需要顯示資訊的圖層
//add identify layer
varsource = newDataCenterSource("http://localhost:8087/geoserver/bhxq/wms?",{
'transparent':true,
format:'image/png',
attribution: "Map© 2016 XXZX"
});
varwmsPlace=source.getLayer("bhxq:行政地名").addTo(mymap);
4.5.3.5 完整代碼
//identify-jsonp.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="js/leaflet/leaflet.css" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" />
<style>
html, body{ margin:0; height:100%; }
#mapid {height: 100%;width: 100%;}
</style>
<script type="text/javascript"src="js/leaflet/leaflet-src.js" ></script>
<script type="application/javascript"src="js/jquery-3.1.1.js"></script>
<script type="text/javascript"src="js/leaflet/leaflet.wms.js"></script>
<script type="text/javascript"src="js/leaflet.wms.datacenter.js" ></script>
<title>Identify</title>
</head>
<body>
<div id="mapid"></div>
<script type="text/javascript">
//map
var mymap = L.map('mapid').setView([38.88, 117.58],10);
var wmsBhxq =L.tileLayer.wms('http://localhost:8087/geoserver/bhxq/wms?', {
layers:'bhxq:bhxq',
format:'image/png',
transparent: true,
attribution: "Map© 2016 XXZX"
}).addTo(mymap);
var wmsRoad =L.tileLayer.wms('http://localhost:8087/geoserver/bhxq/wms?', {
layers:'bhxq:主要道路',
format:'image/png',
transparent: true,
attribution: "Map©2016 XXZX"
}).addTo(mymap);
//add identify layer
varsource = newDataCenterSource("http://localhost:8087/geoserver/bhxq/wms?",{
'transparent': true,
format:'image/png',
attribution: "Map© 2016 XXZX"
});
varwmsPlace=source.getLayer("bhxq:行政地名").addTo(mymap);
var baseLayers = {
"濱海新區": wmsBhxq,
"主要道路": wmsRoad,
"行政地名": wmsPlace
};
L.control.layers(null, baseLayers).addTo(mymap);
</script>
</body>
</html>
//leaflet.wms.datacenter.js
//JSON Identify Object
var DataCenterSource =L.WMS.Source.extend({
'getFeatureInfo': function(point, latlng, layers, callback){//request wms jsonp info
// Request WMSGetFeatureInfo and call callback with results
// (split fromidentify() to faciliate use outside of map events)
varsuccessFunction='success_parseResponse';
var params =this.getFeatureInfoParams(point, layers),
url = this._url +L.Util.getParamString(params,this._url)+'&info_format=text/javascript'+'&format_options=callback:'+successFunction;//usejsonp,指定jsonp的回調函數
this._wms_url=url;//for iframe get request
this.showWaiting();
this.clickPos=latlng;//popup position
$.ajax({
async:false,
type: "get",
url: url,
dataType:'jsonp',
jsonpCallback:successFunction,
success:function(response){//thisfunction will be called by jsonpCallback function
console.log('success');
//console.log(source);
source.hideWaiting();
var text = source.parseFeatureInfo(response,source._url_wms);
source.showFeatureInfo(source.clickPos,JSON.stringify(text));
}
});
},
'parseFeatureInfo': function(result, url){//process response info here
// Hook to handle parsing AJAX response
if (result == "error") {
// AJAX failed, possibly due toCORS issues.
// Try loading content in<iframe>.
result = "<iframesrc='" + url + "' style='border:none'>";
}
return result;
},
'showFeatureInfo': function(latlng, info){//open popup
console.log('showFeatureInfo='+info);
// Hook to handle displayingparsed AJAX response to the user
if(!this._map) {
return;
}
this._map.openPopup(info, latlng);
}
});
process identify info
//functionparseResponse(response){
// //console.log(source);
// source.hideWaiting();
// var text = source.parseFeatureInfo(response,source._url_wms);
// source.showFeatureInfo(source.clickPos,JSON.stringify(text));
//}
//functionsuccess_parseResponse(response){//外部的回調函數,會優先調用
// console.log('outter success...'+JSON.stringify(response));
//}
4.5.3.6 運作結果
請求
http://localhost:8087/geoserver/bhxq/wms?&service=WMS&request=GetFeatureInfo&version=1.1.1&layers=bhxq%3A%E8%A1%8C%E6%94%BF%E5%9C%B0%E5%90%8D&styles=&format=image%2Fpng&transparent=true&width=1680&height=920&srs=EPSG%3A3857&bbox=12960509.641977917%2C4634224.150873668%2C13217338.057016108%2C4774868.282918389&query_layers=bhxq%3A%E8%A1%8C%E6%94%BF%E5%9C%B0%E5%90%8D&X=654&Y=502&info_format=text/javascript&format_options=callback:success_parseResponse&callback=success_parseResponse&_=1476756695021
響應
success_parseResponse({"type":"FeatureCollection","totalFeatures":"unknown","features":[{"type":"Feature","id":"行政地名.98","geometry":{"type":"Point","coordinates":[117.32804859057012,38.83744788501207]},"geometry_name":"the_geom","properties":{"OBJECTID":2782,"Name":"萬家碼頭村","Name_PY":"WanJiaMaTouCun","Ctype":"自然村名稱","Ntype":"190108","Code":"120116","Address":"","Telephone":"","label":"萬家碼頭村"}}],"crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:EPSG::4490"}}})