在鼠标单击时添加标记并删除openlayers中的现有标记?

时间:2013-11-11 12:32:41

标签: javascript maps openlayers marker

我正在使用Openlayers地图。我想要一个功能,当用户点击地图时应该创建标记,但同时应该删除或删除已经在地图上的现有标记,并且只显示最新的标记。

  var markers = new OpenLayers.Layer.Markers( "Markers" );
    markers.id = "Markers";
    me.OpenLayers.addLayer(markers);
    /*myMarker = new OpenLayers.Marker(new OpenLayers.Marker( 56.512438257836,27.335700987698 ));
     markers.addMarker(myMarker);*/

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

    //map.setCenter (lonLat, zoom);
    me.OpenLayers.events.register("click", kijs_map_container, function(evt) {
        var lonlat = me.OpenLayers.getLonLatFromViewPortPx(evt.xy).transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
        $("#edit-field-jena-seta-map-openlayers-wkt").val('GEOMETRYCOLLECTION(POINT('+lonlat.lat+'  '+lonlat.lon+'))');
        var pos = me.OpenLayers.getLonLatFromPixel(evt.xy);
        alert(baltic_long);
        var marker = new OpenLayers.Marker(new OpenLayers.LonLat(baltic_lat, baltic_long),icon);
        markers.addMarker(marker);
        marker.events.register("click", marker, function(e){

        });
        //updateMaker(myMarker, pos);
    });

2 个答案:

答案 0 :(得分:1)

在创建和添加新标记之前删除图层上的所有标记:

markers.clearMarkers(); 
markers.addMarker(marker);

有关详细信息,请参阅clearMarkers

答案 1 :(得分:0)

当您放置var marker并在me.OpenLayers.events.register();范围之外初始化图标时,可能会在您再次点击新标记时重新启动。

var marker;
icon = new OpenLayers.Icon( ... );

me.OpenLayers.events.register("click", kijs_map_container, function(evt) {
    var pos = me.OpenLayers.getLonLatFromPixel(evt.xy);
    marker = new OpenLayers.Marker(pos, icon);
    markers.addMarker(marker);
});

至少我没有在这里测试过这个特殊的例子,但是我正在使用我正在制作的地图编辑器。