openlayers 简单地将鼠标悬停在标记上

发布于 2024-12-21 07:55:17 字数 127 浏览 2 评论 0原文

听起来很简单,但我找不到任何新手教程:任何人都可以给我一个简单的示例,如何在 OpenLayers 中创建(矢量)标记,在鼠标悬停时打开信息窗口,甚至在鼠标移出时关闭它?

我发现其中部分内容已得到解释,但并非全部......

It sounds so simple but I can't find any newbie tutorial: Could anybody give me a simple example how I create (vektor)markers in OpenLayers that open an infowindow on mouseover and even close it on mouseout?

I found parts of this explained but not all of it....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

深海夜未眠 2024-12-28 07:55:17

作为如何执行此操作的简单示例,您需要执行以下操作:

创建一个矢量图层来包含标记并将其添加到地图中:

this.markerLayer = new OpenLayers.Layer.Vector(
    "My Marker Layer",
    { /* configuration options are set here */ }
);
map.addLayer(this.markerLayer);

创建标记并将其添加到地图中:

var marker = new OpenLayers.Feature.Vector(point, attributes, markerStyle);
this.markerLayer.addFeatures([marker]);

为您的标记创建一个选择控件层,并注册一个函数来在用户将鼠标悬停在标记上时构建弹出窗口:

var selectControl = new OpenLayers.Control.SelectFeature(this.markerLayer, {
    hover: true
});
selectControl.events.register('featurehighlighted', null, onFeatureHighlighted);

构建弹出窗口:

onFeatureHighlighted: function (evt) {
    // Needed only for interaction, not for the display.
    var onPopupClose = function (evt) {
        // 'this' is the popup.
        var feature = this.feature;
        if (feature.layer) {
            selectControl.unselect(feature);
        }  
        this.destroy();
    }

    feature = evt.feature;
    popup = new OpenLayers.Popup.FramedCloud("featurePopup",
            feature.geometry.getBounds().getCenterLonLat(),
            new OpenLayers.Size(100,100),
            "<h2>"+feature.attributes.station_na + "</h2>" +
            "Location: " + feature.attributes.location + '<br/>' +
            "Elevation: " + feature.attributes.elev_,
            null, true, onPopupClose);
    feature.popup = popup;
    popup.feature = feature;
    map.addPopup(popup, true);
}, // ...

For a simple example of how to do this, you need to do a couple of things:

Create a vector layer to contain your markers and add it to the map:

this.markerLayer = new OpenLayers.Layer.Vector(
    "My Marker Layer",
    { /* configuration options are set here */ }
);
map.addLayer(this.markerLayer);

Create your marker and add it to the map:

var marker = new OpenLayers.Feature.Vector(point, attributes, markerStyle);
this.markerLayer.addFeatures([marker]);

Create a select control for your layer, and register a function to build your popup when the user hovers over your marker:

var selectControl = new OpenLayers.Control.SelectFeature(this.markerLayer, {
    hover: true
});
selectControl.events.register('featurehighlighted', null, onFeatureHighlighted);

Build your popup:

onFeatureHighlighted: function (evt) {
    // Needed only for interaction, not for the display.
    var onPopupClose = function (evt) {
        // 'this' is the popup.
        var feature = this.feature;
        if (feature.layer) {
            selectControl.unselect(feature);
        }  
        this.destroy();
    }

    feature = evt.feature;
    popup = new OpenLayers.Popup.FramedCloud("featurePopup",
            feature.geometry.getBounds().getCenterLonLat(),
            new OpenLayers.Size(100,100),
            "<h2>"+feature.attributes.station_na + "</h2>" +
            "Location: " + feature.attributes.location + '<br/>' +
            "Elevation: " + feature.attributes.elev_,
            null, true, onPopupClose);
    feature.popup = popup;
    popup.feature = feature;
    map.addPopup(popup, true);
}, // ...
陪你搞怪i 2024-12-28 07:55:17

您可以使用 markerpopup,如下所示。

var popup;
var marker_layer = new OpenLayers.Layer.Markers( "Markers" );
var size = new OpenLayers.Size(32,32);
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
var icon_marker = new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png',
                                        size, 
                                        offset);
marker = new OpenLayers.Marker(new OpenLayers.LonLat(5.6, 50.6), icon_marker);

//here add mouseover event
marker.events.register('mouseover', marker, function(evt) {
    popup = new OpenLayers.Popup.FramedCloud("Popup",
        new OpenLayers.LonLat(5.6, 50.6),
        null,
        '<div>Hello World! Put your html here</div>',
        null,
        false);
    map.addPopup(popup);
});
//here add mouseout event
marker.events.register('mouseout', marker, function(evt) {popup.hide();});

marker_layer.addMarker(marker);
map.addLayer(marker_layer);

You can use marker and popup, as below.

var popup;
var marker_layer = new OpenLayers.Layer.Markers( "Markers" );
var size = new OpenLayers.Size(32,32);
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
var icon_marker = new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png',
                                        size, 
                                        offset);
marker = new OpenLayers.Marker(new OpenLayers.LonLat(5.6, 50.6), icon_marker);

//here add mouseover event
marker.events.register('mouseover', marker, function(evt) {
    popup = new OpenLayers.Popup.FramedCloud("Popup",
        new OpenLayers.LonLat(5.6, 50.6),
        null,
        '<div>Hello World! Put your html here</div>',
        null,
        false);
    map.addPopup(popup);
});
//here add mouseout event
marker.events.register('mouseout', marker, function(evt) {popup.hide();});

marker_layer.addMarker(marker);
map.addLayer(marker_layer);
﹎☆浅夏丿初晴 2024-12-28 07:55:17

这对我有用。最终很简单,但花了一些时间:

 var marker = new OpenLayers.Marker(position, icon.clone());           
 boothLayer.addMarker(marker);                                         

 marker.events.register('mouseover', marker, function() {           
   var msg = booth.get('name') +' - ' + booth.get('premises');      
   var popup = new OpenLayers.Popup.FramedCloud("Popup",            
       position, null, '<div>'+msg+'</div>', null, false);          
   map.addPopup(popup);                                             
   marker.events.register('mouseout', marker,                       
     setTimeout( function() { popup.destroy(); }, 4000));           
   });                                                              

请注意鼠标移出事件的 4000 微秒延迟 - 也许可能更短,具体取决于您的使用情况。

This works for me. Ended up being simple, but took a while:

 var marker = new OpenLayers.Marker(position, icon.clone());           
 boothLayer.addMarker(marker);                                         

 marker.events.register('mouseover', marker, function() {           
   var msg = booth.get('name') +' - ' + booth.get('premises');      
   var popup = new OpenLayers.Popup.FramedCloud("Popup",            
       position, null, '<div>'+msg+'</div>', null, false);          
   map.addPopup(popup);                                             
   marker.events.register('mouseout', marker,                       
     setTimeout( function() { popup.destroy(); }, 4000));           
   });                                                              

Note the 4000 microsecond delay on the mouse out event - maybe could be shorter, depends on your use.

灼疼热情 2024-12-28 07:55:17

您需要使用 selectControl 来创建弹出窗口。要使其响应悬停而不是单击,请在构造函数中设置悬停:true。

You need to use a selectControl to create your popup. To make it respond to hover instead of click set hover:true in the constructor.

后来的我们 2024-12-28 07:55:17

我使用一个函数来添加它,这是一个简化版本。请注意,您设置详细信息并调用底部的函数。另请注意,您不能在多层上有多个选择器 - 我认为只有最后添加的选择器才有效,因此如果您想在一层中使用多个功能,则必须对其进行调整:

function addMarkerLayer(markerInfo){
    var details= markerInfo.details || "<h3>"+markerInfo.title+"</h3>"+
        "[Location] Lat:"+markerInfo.latitude + " Lon:"+markerInfo.longitude;

    var features=[];
    features.push(new OpenLayers.Feature.Vector(
        new OpenLayers.Geometry.Point(markerInfo.longitude, markerInfo.latitude),
        {title: markerInfo.title, details:details, externalGraphic:markerInfo.icon},
        {
            externalGraphic:markerInfo.icon,
            fillColor: markerInfo.markerColor || '#ff0',
            fillOpacity: markerInfo.iconOpacity || 0.8,
            graphicWidth   : markerInfo.iconSize || 24,
            graphicHeight  : markerInfo.iconSize || 24,
            strokeColor: markerInfo.markerStrokeColor || "#ee9900",
            strokeOpacity: 1,
            strokeWidth: 1,
            pointRadius: 7
        }
    ));

    // create the layer with listeners to create and destroy popups
    var vector = new OpenLayers.Layer.Vector(markerInfo.layerName, {
        eventListeners: {
            'featureselected': function(evt) {
                var feature = evt.feature;
                var popup = new OpenLayers.Popup.FramedCloud("popup",
                    OpenLayers.LonLat.fromString(feature.geometry.toShortString()),
                    null,
                    feature.attributes.details,
                    null,
                    true);
                feature.popup = popup;
                map.addPopup(popup);
            },
            'featureunselected': function(evt) {
                var feature = evt.feature;
                map.removePopup(feature.popup);
                feature.popup.destroy();
                feature.popup = null;
            }
        }
    });
    vector.addFeatures(features);

    var selector = new OpenLayers.Control.SelectFeature(vector, {
        hover: true
    });

    map.addLayer(vector);
    map.addControl(selector);
}


var markerInfo={
    title:'Washington DC',
    latitude:38.8,
    longitude:-77,
    icon:"/icons/event.png",
    iconSize:24
};
addMarkerLayer(markerInfo);

I use a function to add it, here's a simplified version. Note that you set the details and call the function at the bottom. Also note that you can't have multiple selectors on multiple layers - I think only the last one added will work, so you'll have to tweak it if you want multiple features in one layer:

function addMarkerLayer(markerInfo){
    var details= markerInfo.details || "<h3>"+markerInfo.title+"</h3>"+
        "[Location] Lat:"+markerInfo.latitude + " Lon:"+markerInfo.longitude;

    var features=[];
    features.push(new OpenLayers.Feature.Vector(
        new OpenLayers.Geometry.Point(markerInfo.longitude, markerInfo.latitude),
        {title: markerInfo.title, details:details, externalGraphic:markerInfo.icon},
        {
            externalGraphic:markerInfo.icon,
            fillColor: markerInfo.markerColor || '#ff0',
            fillOpacity: markerInfo.iconOpacity || 0.8,
            graphicWidth   : markerInfo.iconSize || 24,
            graphicHeight  : markerInfo.iconSize || 24,
            strokeColor: markerInfo.markerStrokeColor || "#ee9900",
            strokeOpacity: 1,
            strokeWidth: 1,
            pointRadius: 7
        }
    ));

    // create the layer with listeners to create and destroy popups
    var vector = new OpenLayers.Layer.Vector(markerInfo.layerName, {
        eventListeners: {
            'featureselected': function(evt) {
                var feature = evt.feature;
                var popup = new OpenLayers.Popup.FramedCloud("popup",
                    OpenLayers.LonLat.fromString(feature.geometry.toShortString()),
                    null,
                    feature.attributes.details,
                    null,
                    true);
                feature.popup = popup;
                map.addPopup(popup);
            },
            'featureunselected': function(evt) {
                var feature = evt.feature;
                map.removePopup(feature.popup);
                feature.popup.destroy();
                feature.popup = null;
            }
        }
    });
    vector.addFeatures(features);

    var selector = new OpenLayers.Control.SelectFeature(vector, {
        hover: true
    });

    map.addLayer(vector);
    map.addControl(selector);
}


var markerInfo={
    title:'Washington DC',
    latitude:38.8,
    longitude:-77,
    icon:"/icons/event.png",
    iconSize:24
};
addMarkerLayer(markerInfo);
一萌ing 2024-12-28 07:55:17

我用 ol 5.2 example“自定义交互”编写了一个工作示例
openlayers.org/en/latest/examples/select-features.html

因此,您将功能添加到图层并将其添加到地图中,然后创建一个像这样的新交互

const interact = new ol.interaction.Select({condition: ol.events.condition.pointerMove});

它指定它将在悬停时选择一个功能(指针移动)
然后,将其添加到地图中,并关联当交互选择某个功能时(即,当您将鼠标悬停在某个功能上时)应调用的函数。

map.addInteraction(interact);
interact.on('select', showInfoWindow);

并且您声明显示信息窗口的函数

function showInfoWindow(evt){
    if(evt.selected.length>0){
        const feature = evt.selected[0];
        const id = feature.getId();

        infoWindow.innerHTML = '<p>' + id + '</p>';
        infoWindow.show();//if you have something like that, you could use an openLayers overlay
    }
}

您应该注意,该事件将返回(在本例中)一个对象,当您将鼠标悬停在其中时,您可以在“selected”属性中找到选定的功能。在这种情况下,当您将鼠标悬停时,“取消选择”属性中将提供相同的对象,直到您选择一个新对象为止

I wrote a working exemple of this with ol 5.2 exemple "Custom Interaction"
openlayers.org/en/latest/examples/select-features.html

So you add features to a layer and add it to the map and then you create a new Interaction like this

const interact = new ol.interaction.Select({condition: ol.events.condition.pointerMove});

It specifies that it will select a feature on hover (pointermove)
Then you add it to your map and associate the function that should be called when the interaction selects a feature (i.e. when you hovers over one).

map.addInteraction(interact);
interact.on('select', showInfoWindow);

And you declare your function that shows the info window

function showInfoWindow(evt){
    if(evt.selected.length>0){
        const feature = evt.selected[0];
        const id = feature.getId();

        infoWindow.innerHTML = '<p>' + id + '</p>';
        infoWindow.show();//if you have something like that, you could use an openLayers overlay
    }
}

You should note that the event will return (in this case) an object where you can find the selected feature in the 'selected' attribute when you hover in it. When you hover out, in this case, the same object will be available in the 'deselected' attribute until you select a new one

囍笑 2024-12-28 07:55:17

这个来自用户列表的示例非常有助于展示如何将悬停和单击事件分配给矢量图层。

This example from a userlist was very helpful in showing how to have both hover and click events assigned to a vector layer.

梦萦几度 2024-12-28 07:55:17

听起来您想查看“OpenLayers.Popup()”,

此示例在绘制多边形后显示一个弹出窗口,然后单击它,但您应该能够更改它以响应悬停。
http://openlayers.org/dev/examples/select-feature-openpopup.html

It sounds like you want to look at "OpenLayers.Popup()"

this example shows a popup after you draw a polygon, then click on it, but you should be able to change it to respond to hover instead.
http://openlayers.org/dev/examples/select-feature-openpopup.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文