在OpenLayers Map添加Marker。 1.創(chuàng)建Marker圖層 Maker由Marker圖層進行管理 var marker_layer = new OpenLayers.Layer.Markers("markers"); 2. 創(chuàng)建Marker對象 1 //創(chuàng)建Marker 位置 2 var pos = new new OpenLayers.LonLat (x, y); 3 //創(chuàng)建Marker對象 4 var marker = new OpenLayers.Marker ( pos ); 5 //透明度 6 marker.setOpacity(opacity); 7 //注冊鼠標事件 8 marker.events.register( 'mousedown', marker, onMakerMouseDown); 9 //添加marker到marker layer 10 marker_layer.addMarker(marker); 在marker上注冊一個mousedown事件,mousedown事件的響應(yīng)函數(shù)為onMakerMouseDown。 3、定義Marker鼠標事件 function onMakerMouseDown(evt) { alert(marker.CLASS_NAME); //彈出Marker的類名 OpenLayers.Event.stop(evt); //停止事件 } 鼠標點擊后,添加一個紅色的Marker。 完整代碼如下 1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <HTML> 3 <HEAD> 4 <TITLE> OpenLayer : Event Mouse </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 type="text/javascript"> 9 10 var map = null; 11 var wms_url = "http://127.0.0.1:8080/geoserver/wms?"; 12 var wms_version = "1.3.0"; 13 var layer_name = 'country'; 14 15 var wms_layer = null; 16 var marker_layer = null; 17 18 var marker = null; 19 20 function init() 21 { 22 //創(chuàng)建map對象, 23 map = new OpenLayers.Map("map"); 24 wms_layer = new OpenLayers.Layer.WMS("OpenLayers WMS", 25 wms_url, 26 {layers: layer_name}, 27 {singleTile: true}); 28 29 marker_layer = new OpenLayers.Layer.Markers("markers"); 30 31 // 添加圖層 32 map.addLayers([wms_layer, marker_layer]); 33 map.addControl( new OpenLayers.Control.LayerSwitcher() ); 34 //---------------------------------------------------------------// 35 //注冊鼠標事件 36 map.events.register('mousedown', map, onMakerMouseDown); 37 38 // 放大到全屏 39 map.zoomToMaxExtent(); 40 } 41 42 function addMarker(x, y, opacity) 43 { 44 45 marker = new OpenLayers.Marker(new OpenLayers.LonLat(x, y)); 46 //透明度 47 marker.setOpacity(opacity); 48 //注冊鼠標事件 49 marker.events.register('mousedown', marker, onMakerMouseDown); 50 marker_layer.addMarker(marker); 51 } 52 53 /* 54 * 鼠標點擊Marker的響應(yīng)函數(shù) 55 */ 56 function onMakerMouseDown(evt) 57 { 58 //alert(evt.x); 59 alert(marker.CLASS_NAME); 60 OpenLayers.Event.stop(evt); 61 } 62 63 function onAddMarker() 64 { 65 var x = document.getElementById("X").value; 66 var y = document.getElementById("Y").value; 67 var opacity = document.getElementById("opacity").value; 68 69 addMarker(x, y, opacity); 70 } 71 72 </script> 73 74 </HEAD> 75 76 <BODY onload="init()"> 77 <div> 78 <div>X<input type="text" id="X" value="0"> 79 Y<input type="text" id="Y" value="0"> 80 透明度<input type="text" id="opacity" value="255"> 81 <input type="button" value="Add Marker" onClick="onAddMarker();"></div> 82 <div id="map" class="smallmap"></div> 83 </div> 84 </BODY> 85 </HTML>
|
|
來自: 冷泉閣 > 《Openlayers》