轉自:http://starting.iteye.com/blog/1039809
主要實現的功能有放大,縮小,獲取地圖大小,平移,線路測量,面積測量,拉寬功能,顯示標注,移除標注,畫多邊形獲取經緯度坐標。根據經緯度坐標顯示多邊形。地圖切換,圖層控制等功能。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>OpenLayers map preview</title>
<!-- Import OL CSS, auto import does not work with our minified OL.js build -->
<link rel="stylesheet" type="text/css" href="../theme/default/style.css"/>
<link rel="stylesheet" href="../theme/default/google.css" type="text/css">
<!-- Basic CSS definitions -->
<style type="text/css">
/* General settings */
body {
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-size: small;
}
/* Toolbar styles */
#toolbar {
position: relative;
padding-bottom: 0.5em;
}
/* The map and the location bar */
#map {
clear: both;
position: relative;
width: 698px;
height: 330px;
border: 1px solid black;
}
#wrapper {
width: 698px;
}
#location {
float: right;
}
/* Styles used by the default GetFeatureInfo output, added to make IE happy */
table.featureInfo, table.featureInfo td, table.featureInfo th {
border: 1px solid #ddd;
border-collapse: collapse;
margin: 0;
padding: 0;
font-size: 90%;
padding: .2em .1em;
}
table.featureInfo th {
padding: .2em .2em;
text-transform: uppercase;
font-weight: bold;
background: #eee;
}
table.featureInfo td {
background: #fff;
}
table.featureInfo tr.odd td {
background: #eee;
}
table.featureInfo caption {
text-align: left;
font-size: 100%;
font-weight: bold;
text-transform: uppercase;
padding: .2em .2em;
}
</style>
<!-- Import OpenLayers, reduced, wms read only version -->
<script src="../lib/OpenLayers.js" ></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script defer="defer" type="text/javascript">
var map, measureControls;
var untiled;
var tiled;
function init(){
format = 'image/png';
var bounds = new OpenLayers.Bounds( //地圖區域范圍
74.137, 6.319,
135.086, 53.558
);
var options = {
controls: [],
maxExtent: bounds,
maxResolution: 0.23808203125,
projection: "EPSG:4610",
numZoomLevels: 7,
units: 'degrees'
};
map = new OpenLayers.Map('map', options);
/**********************加載圖層 開始*******************************/
/* tiled = new OpenLayers.Layer.WMS( //圖層組
"基礎圖層", "http://localhost:8080/geoserver/wms",
{
height: '330',
width: '698',
layers: 'sf',
styles: '',
srs: 'EPSG:4326',
format: format,
tiled: 'true',
tilesOrigin : map.maxExtent.left + ',' + map.maxExtent.bottom
},
{
buffer: 0,
displayOutsideMaxExtent: true
}
);*/
var streams = new OpenLayers.Layer.WMS( //圖層組
"中國", "http://localhost:8080/geoserver/wms",
{
height: '330',
width: '698',
layers: 'china',
styles: '',
srs: 'EPSG:4610',
format: format,
tiled: 'true',
tilesOrigin : map.maxExtent.left + ',' + map.maxExtent.bottom
},
{
buffer: 0,
displayOutsideMaxExtent: true
}
);
untiled = new OpenLayers.Layer.WMS( //單獨圖層
"省會", "http://127.0.0.1:8080/geoserver/wms",
{
height: '330',
width: '698',
layers: 'china:provice',
styles: '',
srs: 'EPSG:4610',
transparent: "true",
format: format
},
{singleTile: true, ratio: 1}
);
untiled.setVisibility(false); //設置為不顯示
//var gmap = new OpenLayers.Layer.Google("Google Streets", {visibility: false});
/* var dm_wms = new OpenLayers.Layer.WMS( "點圖層",
"http://127.0.0.1:8080/geoserver/wms",
{layers: "sf:bugsites,sf:archsites",
transparent: "true", format: "image/png"});*/
map.addLayers([streams,untiled]);
/********************END 加載圖層*********************************/
/************************加載一般的基礎控件********************************/
map.addControl(new OpenLayers.Control.PanZoomBar({ //添加平移縮放工具條
position: new OpenLayers.Pixel(2, 15)
}));
map.addControl(new OpenLayers.Control.Navigation()); //雙擊放大,平移
map.addControl(new OpenLayers.Control.Scale($('scale'))); //獲取地圖比例尺
map.addControl(new OpenLayers.Control.MousePosition({element: $('location')})); //獲取鼠標的經緯度
map.setCenter(new OpenLayers.LonLat(100.254, 35.25), 1); //添加平移縮放工具條
map.addControl(new OpenLayers.Control.OverviewMap()); //添加鷹眼圖
map.addControl(new OpenLayers.Control.LayerSwitcher({'ascending':false})); //圖層切換工具
map.addControl(new OpenLayers.Control.Permalink('xxxx')); //添加永久鏈接
//map.addControl(new OpenLayers.Control.MouseToolbar());
//map.zoomToMaxExtent();
var zb=new OpenLayers.Control.ZoomBox({out:true});
var panel = new OpenLayers.Control.Panel({defaultControl: zb});
map.addControl(panel);
/************END************加載一般的基礎控件********************************/
/***********************鼠標點擊,獲取圖層數據*******************************/
map.events.register('click', map, function (e) {
document.getElementById('nodelist').innerHTML = "Loading... please wait...";
var params = {
REQUEST: "GetFeatureInfo",
EXCEPTIONS: "application/vnd.ogc.se_xml",
BBOX: map.getExtent().toBBOX(),
X: e.xy.x,
Y: e.xy.y,
INFO_FORMAT: 'text/html',
QUERY_LAYERS: map.layers[0].params.LAYERS,
FEATURE_COUNT: 50,
Layers: 'ok',
Styles: '',
Srs: 'EPSG:4610',
WIDTH: map.size.w,
HEIGHT: map.size.h,
format: format};
OpenLayers.loadURL("http://localhost:8080/geoserver/wms", params, this, setHTML, setHTML);
OpenLayers.Event.stop(e);
});
/**************END*********鼠標點擊,獲取圖層數據*******************************/
/**********************************點、線、面測量開始**********************************************/
var sketchSymbolizers = {
"Point": {
pointRadius: 4,
graphicName: "square",
fillColor: "white",
fillOpacity: 1,
strokeWidth: 1,
strokeOpacity: 1,
strokeColor: "#333333"
},
"Line": {
strokeWidth: 3,
strokeOpacity: 1,
strokeColor: "#666666",
strokeDashstyle: "dash"
},
"Polygon": {
strokeWidth: 2,
strokeOpacity: 1,
strokeColor: "#666666",
fillColor: "white",
fillOpacity: 0.3
}
};
var style = new OpenLayers.Style();
style.addRules([
new OpenLayers.Rule({symbolizer: sketchSymbolizers})
]);
var styleMap = new OpenLayers.StyleMap({"default": style});
measureControls = {
line: new OpenLayers.Control.Measure(
OpenLayers.Handler.Path, {
persist: true,
handlerOptions: {
layerOptions: {styleMap: styleMap}
}
}
),
polygon: new OpenLayers.Control.Measure(
OpenLayers.Handler.Polygon, {
persist: true,
handlerOptions: {
layerOptions: {styleMap: styleMap}
}
}
)
};
var control;
for(var key in measureControls) {
control = measureControls[key];
control.events.on({
"measure": handleMeasurements,
"measurepartial": handleMeasurements
});
map.addControl(control);
}
/***************************END************點,線、面積測量*****************************************/
//添加點標注的圖層
markers = new OpenLayers.Layer.Markers("markers");
map.addLayer(markers);
markers.setZIndex(200);
}
//獲取面積的結果賦值
function handleMeasurements(event) {
var geometry = event.geometry;
var units = event.units;
var order = event.order;
var measure = event.measure;
var element = document.getElementById('output');
var out = "";
if(order == 1) {
out += "面積為: " + measure.toFixed(3) + " " + units;
} else {
out += "面積為: " + measure.toFixed(3) + " " + units + "<sup>2</" + "sup>";
}
element.innerHTML = out;
}
function setHTML(response){
document.getElementById('nodelist').innerHTML = response.responseText;
};
//縮小
function zoomOut(){
map.zoomOut();
}
//放大
function zoomIn(){
map.zoomIn();
}
//獲取地圖數據
function getSize(){
alert(map.getSize()+",高度為="+map.getSize().h);
}
//切換鼠標事件功能
function toggleControl(_value) {
for(key in measureControls) {
var control = measureControls[key];
if(_value == key ) {
control.activate();
} else {
control.deactivate();
}
}
}
/*********************拉寬并獲取經緯度坐標系*********************************/
function boxExtend(){
var controlBox = new OpenLayers.Control();
OpenLayers.Util.extend(controlBox, {
draw: function () {
this.box = new OpenLayers.Handler.Box( controlBox,
{"done": this.notice},{ "persist": true},
{keyMask:OpenLayers.Handler.MOD_SHIFT });
this.box.activate();
},
notice: function (bounds) {
var ll = map.getLonLatFromPixel(new OpenLayers.Pixel(bounds.left, bounds.bottom));
var ur = map.getLonLatFromPixel(new OpenLayers.Pixel(bounds.right, bounds.top));
alert(ll.lon.toFixed(4) + ", " +
ll.lat.toFixed(4) + ", " +
ur.lon.toFixed(4) + ", " +
ur.lat.toFixed(4));
}
});
map.addControl(controlBox);
}
var markers,marker;
var markArr=new Array();
function addMarker(){
var url = 'http://www.openlayers.org/dev/img/marker.png';
var sz = new OpenLayers.Size(20, 20); //尺寸大小
var calculateOffset = function(size) {
return new OpenLayers.Pixel(-(size.w/2), -size.h);
};
var icon = new OpenLayers.Icon(url, sz, null, calculateOffset);
marker = new OpenLayers.Marker(new OpenLayers.LonLat(113.34851,33.22630), icon);
markers.addMarker(marker);
// marker = new OpenLayers.Marker(madrid, icon.clone());
// markers.addMarker(marker);
}
function removeMarker() {
markers.removeMarker(marker);
}
/*******************多邊形獲取經緯度坐標系*************************/
function test(){
var getpolygonxy = new OpenLayers.Control();
OpenLayers.Util.extend(getpolygonxy, {
draw: function() {
this.polygon= new OpenLayers.Handler.Polygon(getpolygonxy ,
{ "done": this.notice },{ "persist": true},
{ keyMask: OpenLayers.Handler.MOD_SHIFT });
this.polygon.activate();
},
notice: function(bounds) {
alert(bounds);//坐標信息
}
});
map.addControl(getpolygonxy);
}
</script>
</head>
<body οnlοad="init()">
<div id="toolbar" style="display:">
<input type="button" value="放大" οnclick="zoomIn()"/>
<input type="button" value="縮小" οnclick="zoomOut()"/>
<input type="button" value="獲取地圖大小" οnclick="getSize()"/>
<input type="button" value="平移" οnclick="toggleControl('none')"/>
<input type="button" value="線路測量" οnclick="toggleControl('line')"/>
<input type="button" value="測量面積" οnclick="toggleControl('polygon')"/>
<input type="button" value="shift拉框" οnclick="boxExtend()"/>
<input type="button" value="顯示標注" οnclick="addMarker()"/>
<input type="button" value="移除標注" οnclick="removeMarker()"/>
<input type="button" value="畫多邊形獲取經緯度坐標" οnclick="test()"/>
</div>
<div id="map">
</div>
<div id="wrapper">
<div id="location">經緯度坐標</div>
<div id="scale">
</div>
<div id="output">
</div>
</div>
<div id="xystr"></div>
<div id="nodelist">
<em>Click on the map to get feature info</em>
</div>
</body>
</html>
?