OpenLayers 动态添加标记(Marker)和信息窗(Popup)

方式一:使用marker方式

1、在地图上添加标记图层

var markers =newOpenLayers.Layer.Markers("Markers");
map.addLayer(markers);//地图初始化添加

2、动态添加标记和Popup方法:

//add map initial method

 map.events.register('click', this, function(e) {

    var LonLat=new OpenLayers.getLonLatFromPixel(e.xy);

    autoAddMarker(LontLat);

    OpenLayers.Event.stop(e); 

   }

);

//others method

function getIcon(){

  var size =newOpenLayers.Size(21,25);
  var offset =newOpenLayers.Pixel(-(size.w/2),-size.h);
  var icon =newOpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png', size, offset);

  return icon;

}

function createPopup(marker,LonLat){

    var size=new OpenLayers.Size(200,120);

    var html="Lon:"+LonLat.Lon+"
Lat:"+LonLat.Lat; var popup=new OpenLayers.Popup(marker,LonLat,size,html,true); } function autoAddMarker(LontLat){ var marker=newOpenLayers.Marker(LonLat,getIcon); var popup=createPopup(marker,LonLat); marker.events.register('click',this,function(){ map.addPopup(popup,true);popup.show(); }); markers.addMarker(marker); }

3、事件触发,点击地图获得marker 及其信息窗口。

如果click不是OpenLayers.Events的register方法,就需要activate Click方法。

方式二:使用feature本身提供的特性

 //显示矢量信息
            'pointVectorLayer':new OpenLayers.Layer.Vector("加点图层", {eventListeners:{
                'featureselected':function(evt){
                    var feature = evt.feature;
                    if(myPopup) this.map.removePopup(myPopup);
                    myPopup=createPopup(feature.point);
                    feature.popup = myPopup;
                    this.map.addPopup(myPopup);
                },
                'featureunselected':function(evt){
                    var feature = evt.feature;
                    this.map.removePopup(feature.popup);
                    feature.popup.destroy();
                    feature.popup = null;
                }
            }
            }),

 直接注册矢量层的事件,推荐使用第二种方式,它可以与整体弹出框的样式保持一致,都是popup类型的。

转载于:https://www.cnblogs.com/boonya/archive/2012/03/18/2404731.html

你可能感兴趣的:(OpenLayers 动态添加标记(Marker)和信息窗(Popup))