OpenLayers-添加Marker

在OpenLayers Map添加Marker。

1.创建Marker图层

Maker由Marker图层进行管理

var marker_layer = new OpenLayers.Layer.Markers("markers");

2. 创建Marker对象

复制代码
 1 //创建Marker 位置
 2 var pos = new new OpenLayers.LonLat (x, y);  3 //创建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事件的响应函数为onMakerMouseDown。

3、定义Marker鼠标事件

function onMakerMouseDown(evt)
{
    alert(marker.CLASS_NAME);    //弹出Marker的类名
    OpenLayers.Event.stop(evt);  //停止事件 }

OpenLayers-添加Marker_第1张图片

鼠标点击后,添加一个红色的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 //创建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的响应函数 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("

转载于:https://www.cnblogs.com/hanhuibing/articles/4177637.html

你可能感兴趣的:(javascript,ViewUI)