OpenLayers 3實踐與原理探究3-ol3一個完整的例子
阿新 • • 發佈:2019-01-08
【注】所有程式碼掛在我的github上,本例對應demo2
接著我們看一個比較長的例子,例子實現的是可以繪製圖形,可以根據自己的設定列印地圖
我們先看顯示效果是:
由於ol3的api現在更新變化挺大的,所以自己執行的例子的時候注意版本是3.17.1
例子中的解釋比較詳細,不具體進行展開介紹。本例子主要分為三部分,在js檔案中已經隔開
- 第一部分是地圖的初始化,包括新增圖層,新增控制元件
- 第二部分加個標註點,點選顯示位置的彈出框
- 第三部分自定義工具,包括點、線、面、圓形、菱形、矩形、多邊形的繪製工具和列印地圖工具
為了節省篇幅,index.css
在這裡就不在列出,程式碼掛在我的 github上,本例對應demo2
,詳情可以檢視百度雲共享的資源
indxe.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>完整的例子</title>
<link rel="stylesheet" href="css/index.css">
<link rel="stylesheet" href="pubjs/v3.17.1-dist/ol.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
</head>
<body>
<div class="toolsets">
<button id="search-position" class="search-position btn btn-success btn-sm">查詢座標</button>
<button id="draw-point" class="draw-point btn btn-success btn-sm" >點</button>
<button id="draw-line" class="draw-line btn btn-success btn-sm">線</button>
<button id="draw-ploygon" class="draw-ploygon btn btn-success btn-sm">多邊形</button>
<button id="draw-circle" class="draw-circle btn btn-success btn-sm">圓形</button>
<button id="draw-square" class="draw-square btn btn-success btn-sm">菱形</button>
<button id="draw-box" class="draw-box btn btn-success btn-sm">矩形</button>
<button id="reshape" class="reshape btn btn-info btn-sm">修改形狀</button>
<button id="print" class="print btn btn-info btn-sm">列印地圖</button>
</div>
<!-- 列印地圖的設定 -->
<form class="form print-form">
<label>Page size </label>
<select id="format">
<option value="a0">A0 (slow)</option>
<option value="a1">A1</option>
<option value="a2">A2</option>
<option value="a3">A3</option>
<option value="a4" selected>A4</option>
<option value="a5">A5 (fast)</option>
</select>
<label>Resolution </label>
<select id="resolution">
<option value="72">72 dpi (fast)</option>
<option value="150">150 dpi</option>
<option value="300">300 dpi (slow)</option>
</select>
</form>
<div id="map" class="map">
<div style="display: none;">
<!-- Clickable label for Vienna -->
<a class="overlay" id="Shanghai" target="_blank" href="http://en.wikipedia.org/wiki/Shanghai">Shanghai</a>
<div id="marker" title="Marker"></div>
<!-- Popup -->
<div id="popup" title="點選查詢:"></div>
</div>
</div>
<script type="text/javascript" src="pubjs/jquery.js"></script>
<script type="text/javascript" src="pubjs/v3.17.1-dist/ol-debug.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
index.js
/********************************************************************************************/
var view = new ol.View({
center: [9101767, 2822912],
zoom: 6
}); //map.view的變數
/*圖層*/
var bglayer = new ol.layer.Tile({
source: new ol.source.BingMaps({
// key: 'Your Bing Maps Key from http://www.bingmapsportal.com/here',
key: 'AgiU9gCjKNfaR2yFSDfLw8e9zUlAYisRvRC2_L-LsGYN2bII5ZUvorfP3QJvxmjn', //自己申請的key
imagerySet: 'Aerial'
})
});
var source = new ol.source.Vector({ wrapX: false });
//繪圖繪在此向量圖層
var vector = new ol.layer.Vector({
source: source,
style: new ol.style.Style({ //修改繪製的樣式
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#ffcc33'
})
})
})
});
var map = new ol.Map({
controls: ol.control.defaults().extend([
new ol.control.FullScreen(), //全屏控制元件
new ol.control.ScaleLine(), //比例尺
new ol.control.OverviewMap(), //鷹眼控制元件
// new ol.control.Zoom(),
]),
layers: [bglayer, vector], //新增兩個圖層
target: 'map', //div#id='map'
view: view,
// interaction:
});
/**上面的部分就可以初始化地圖**/
/********************************************************************************************/
/**
* Marker標註
*/
var pos = ol.proj.fromLonLat([121.3725, 31.008889]); //經緯度座標轉換
// Vienna marker
var marker = new ol.Overlay({
position: pos,
positioning: 'center-center',
element: document.getElementById('marker'),
stopEvent: false
});
map.addOverlay(marker);
// Shanghai label
var Shanghai = new ol.Overlay({
position: pos,
element: document.getElementById('Shanghai')
});
map.addOverlay(Shanghai); //標籤 a
/**
* Popup查詢座標彈出框
*/
// Popup showing the position the user clicked
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');
var popup = new ol.Overlay({
element: container,
autoPan: true,
autoPanAnimation: {
duration: 250
}
});
map.addOverlay(popup);
//關閉popup
closer.onclick = function() {
popup.setPosition(undefined);
closer.blur();
return false;
};
$('.search-position').click(function(event) {
map.removeInteraction(draw); //點選選擇時候 取消上次結果
//在地圖上點選
map.on('click', function(evt) {
var coordinate = evt.coordinate;
var hdms = ol.coordinate.toStringHDMS(ol.proj.transform(
coordinate, 'EPSG:3857', 'EPSG:4326'));
content.innerHTML = '<p>點選的座標是:</p><code>' + hdms +
'</code>';
popup.setPosition(coordinate);
});
});
/********************************************************************************************/
/* 自定義工具 */
var draw, select, modify;
$('.toolsets button').click(function(event) {
console.log($(this).text());
var geometryFunction, shapeName, maxPoints;
map.removeInteraction(draw); //點選選擇時候 取消繪圖互動
map.removeInteraction(select); //點選選擇時候 取消選擇
map.removeInteraction(modify); //點選選擇時候 取消修改
switch ($(this).text()) {
case "點":
shapeName = 'Point';
break;
case "線":
shapeName = 'LineString';
break;
case "多邊形":
shapeName = 'Polygon';
break;
case "圓形":
shapeName = 'Circle';
break;
case "菱形":
shapeName = 'Circle';
geometryFunction = ol.interaction.Draw.createRegularPolygon(4);
break;
case "矩形":
shapeName = 'LineString';
maxPoints = 2;
geometryFunction = function(coordinates, geometry) {
if (!geometry) {
geometry = new ol.geom.Polygon(null);
}
var start = coordinates[0];
var end = coordinates[1];
geometry.setCoordinates([
[start, [start[0], end[1]], end, [end[0], start[1]], start]
]);
return geometry;
};
break;
case "修改形狀":
reshape.init();
break;
case "列印地圖":
printMap.init();
break;
}
draw = new ol.interaction.Draw({
source: source,
type: /** @type {ol.geom.GeometryType} */ (shapeName),
geometryFunction: geometryFunction,
maxPoints: maxPoints
});
map.addInteraction(draw); //增加的互動
});
/*修改地圖*/
var reshape = {
init: function() {
// select選擇形狀
// modify修改形狀
var select = new ol.interaction.Select({
wrapX: false
});
var modify = new ol.interaction.Modify({
features: select.getFeatures()
});
// var selectModify = new ol.interaction.defaults().extend([select, modify]);
map.addInteraction(select);
map.addInteraction(modify);
//interactions: ol.interaction.defaults().extend([select, modify]),
}
};
/*列印地圖*/
var printMap = {
init: function() {
map.removeInteraction(draw); //點選選擇時候 取消繪製
var dims = {
a0: [1189, 841],
a1: [841, 594],
a2: [594, 420],
a3: [420, 297],
a4: [297, 210],
a5: [210, 148]
};
var loading = 0;
var loaded = 0;
// var exportButton = document.getElementById('export-pdf');
// exportButton.disabled = true;
document.body.style.cursor = 'progress';
var format = document.getElementById('format').value;
var resolution = document.getElementById('resolution').value;
var dim = dims[format];
var width = Math.round(dim[0] * resolution / 25.4);
var height = Math.round(dim[1] * resolution / 25.4);
var size = /** @type {ol.Size} */ (map.getSize());
var extent = map.getView().calculateExtent(size);
var source = bglayer.getSource();
var tileLoadStart = function() {
++loading;
};
var tileLoadEnd = function() {
++loaded;
if (loading === loaded) {
var canvas = this;
window.setTimeout(function() {
loading = 0;
loaded = 0;
var data = canvas.toDataURL('image/png'); //canvas
var pdf = new jsPDF('landscape', undefined, format);
pdf.addImage(data, 'JPEG', 0, 0, dim[0], dim[1]);
pdf.save('map.pdf');
source.un('tileloadstart', tileLoadStart);
source.un('tileloadend', tileLoadEnd, canvas);
source.un('tileloaderror', tileLoadEnd, canvas);
map.setSize(size);
map.getView().fit(extent, size);
map.renderSync();
// exportButton.disabled = false;
document.body.style.cursor = 'auto';
}, 100);
}
};
map.once('postcompose', function(event) {
source.on('tileloadstart', tileLoadStart);
source.on('tileloadend', tileLoadEnd, event.context.canvas);
source.on('tileloaderror', tileLoadEnd, event.context.canvas);
});
map.setSize([width, height]);
map.getView().fit(extent, /** @type {ol.Size} */ (map.getSize()));
map.renderSync();
}
};