除了WMS地图外,OpenLayers可以直接添加Google Map, Microsoft Virtual Earth等地图。
1. 添加google map的key
使用google map的数据需要google map的一个key。OpenLayers的examples里面有一个key,可以直接使用。也可以在https://developers.google.com/maps/signup?hl=zh-cn上获取一个自己的key。
<script src='http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAjpkAC9ePGem0lIq5XcMiuhR_wWLPFku8Ix9i2SXYRVK3e45q1BQUd_beF8dtzKET_EteAjPdGDwqpQ'></script> 2)
2. 创建OpenLayers Google 图层对象
<script type="text/javascript"> var map = null; function init() { //创建map对象, map = new OpenLayers.Map("map"); map.addControl(new OpenLayers.Control.LayerSwitcher()); //创建google Map图层对象 var gphy = new OpenLayers.Layer.Google( "Google Physical", //Google Map Physical图层 {type: G_PHYSICAL_MAP} ); var gmap = new OpenLayers.Layer.Google( "Google Streets", //Google Map Streets图层 {numZoomLevels: 20} //设置Google Map的zoom级别 ); var ghyb = new OpenLayers.Layer.Google( "Google Hybrid", //Google Physical图层 {type: G_HYBRID_MAP, numZoomLevels: 20} ); var gsat = new OpenLayers.Layer.Google( "Google Satellite", //Google Map Satellite图层 {type: G_SATELLITE_MAP, numZoomLevels: 22} ); // 添加图层 map.addLayers([gphy, gmap, ghyb, gsat]); // 放大到全屏 map.zoomToMaxExtent(); } </script>
3. 设置html的onload函数
<BODY onload="init()">
然后打开网页就可以看到OpenLayers加载的Google Map地图。通过右侧的Layer Switch可以切换图层。
完整的代码如下所示:
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <HTML> 3 <HEAD> 4 <TITLE> Google Map </TITLE> 5 <link rel="stylesheet" href="./OpenLayers-2.10/theme/default/style.css" type="text/css" /> 6 <link rel="stylesheet" href="css/style.css" type="text/css" /> 7 <script src="./OpenLayers-2.10/lib/OpenLayers.js"></script> 8 <script src='http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAjpkAC9ePGem0lIq5XcMiuhR_wWLPFku8Ix9i2SXYRVK3e45q1BQUd_beF8dtzKET_EteAjPdGDwqpQ'></script> 9 <script type="text/javascript"> 10 11 var map = null; 12 function init() 13 { 14 //创建map对象, 15 map = new OpenLayers.Map("map"); 16 map.addControl(new OpenLayers.Control.LayerSwitcher()); 17 18 //创建google Map图层对象 19 var gphy = new OpenLayers.Layer.Google( 20 "Google Physical", //Google Map Physical图层 21 {type: G_PHYSICAL_MAP} 22 ); 23 var gmap = new OpenLayers.Layer.Google( 24 "Google Streets", //Google Map Streets图层 25 {numZoomLevels: 20} //设置Google Map的zoom级别 26 ); 27 var ghyb = new OpenLayers.Layer.Google( 28 "Google Hybrid", //Google Physical图层 29 {type: G_HYBRID_MAP, numZoomLevels: 20} 30 ); 31 var gsat = new OpenLayers.Layer.Google( 32 "Google Satellite", //Google Map Satellite图层 33 {type: G_SATELLITE_MAP, numZoomLevels: 22} 34 ); 35 36 // 添加图层 37 map.addLayers([gphy, gmap, ghyb, gsat]); 38 // 放大到全屏 39 map.zoomToMaxExtent(); 40 } 41 </script> 42 43 </HEAD> 44 45 <BODY onload="init()"> 46 <div id="map" class="smallmap"></div> 47 </BODY> 48 </HTML>