在页面上添加地图,首先要引入相应的OpenLayers的函数库,而后创建地图Map对象,为Map对象添加地图服务后,页面就可以显示地图了。代码如下:
< head>
< meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="skin.css" type="text/css">
<script src="../lib/OpenLayers.js"></script>
<script type="text/javascript">
var map = null;
function init(){
var options = {
controls:[new OpenLayers.Control.KeyboardDefaults]
};
map = new OpenLayers.Map("map",options);
var wms = new OpenLayers.Layer.WMS("LayerName","http://vmap0.tiles.osgeo.org/wms/vmap0?",{layers:"basic"});
map.addLayer(wms);
map.zoomToMaxExtent();
}
</script>
< /head>
< body οnlοad="init()">
<div id="map" class="smallmap"></div>
< /body>
</html>
代码中的div为显示地图的容器,地图要加载到哪个容器中所用方式为map = new OpenLayers.Map("map",options),这里的map为容器的id,options为地图参数。
map的定义方式有以下几种方式:
// create a map with default options in an element with the id "map1" var map = new OpenLayers.Map("map1"); // create a map with non-default options in an element with id "map2" var options = { maxExtent: new OpenLayers.Bounds(-200000, -200000, 200000, 200000), maxResolution: 156543, units: 'm', projection: "EPSG:41001" }; var map = new OpenLayers.Map("map2", options); // map with non-default options - same as above but with a single argument var map = new OpenLayers.Map({ div: "map_id", maxExtent: new OpenLayers.Bounds(-200000, -200000, 200000, 200000), maxResolution: 156543, units: 'm', projection: "EPSG:41001" }); // create a map without a reference to a container - call render later var map = new OpenLayers.Map({ maxExtent: new OpenLayers.Bounds(-200000, -200000, 200000, 200000), maxResolution: 156543, units: 'm', projection: "EPSG:41001" });