Как добавить обработчик MouseOver в VectorFeature в GWT-Openlayers

Я хочу показать пользовательскую всплывающую подсказку (всплывающее окно), когда пользователь наводит курсор на векторный объект на карте GWT-openlayers. Я знаю, что SelectFeature.setHover() позволит мне это сделать, но это также выберет функцию, которую я не хочу иметь.

это похоже на то, когда пользователь наводит курсор, должна отображаться всплывающая подсказка, а когда он нажимает на функцию, происходит выбор музы.

как этого можно добиться?

С уважением Джатин


person user2163450    schedule 16.12.2013    source источник


Ответы (2)


Проверьте этот код. Это также будет добавлено в нашу витрину, но на данный момент у нас есть небольшая проблема с сервером. Будет кричать здесь, когда он будет загружен.

Обратите внимание, что важен порядок добавления элементов управления SelectFeature.

public void buildPanel() {
    // create some MapOptions
    MapOptions defaultMapOptions = new MapOptions();
    defaultMapOptions.setNumZoomLevels(16);

    // Create a MapWidget
    final MapWidget mapWidget = new MapWidget("500px", "500px",
            defaultMapOptions);

    // Create an EmptyLayer as base layer
    EmptyLayer.Options emptyLayerOptions = new EmptyLayer.Options();
    emptyLayerOptions.setAttribution("EmptyLayer (c) GWT-Openlayers");
    emptyLayerOptions.setIsBaseLayer(true); // make it a baselayer.
    EmptyLayer emptyLayer = new EmptyLayer("Empty layer", emptyLayerOptions);
    mapWidget.getMap().addLayer(emptyLayer);

    // Add a clickable vectors to the map

    // create a layer to add the vectors to
    final Vector vectorLayer = new Vector("Vectorlayer");
    mapWidget.getMap().addLayer(vectorLayer);

    // SelectFeature control to capture clicks on the vectors
    final SelectFeature selectFeature = new SelectFeature(vectorLayer);
    selectFeature.setAutoActivate(true);

    // SelectFeature control to capture hover on the vectors
    SelectFeatureOptions selectFeatureHoverOptions = new SelectFeatureOptions();
    // use the tempory style to be defined in the StyleMap      
    selectFeatureHoverOptions.setRenderIntent(RenderIntent.TEMPORARY); 
    selectFeatureHoverOptions.setHighlightOnly(true);
    selectFeatureHoverOptions.setHover();
    SelectFeature selectHoverFeature = new SelectFeature(vectorLayer,
            selectFeatureHoverOptions);
    selectHoverFeature.setClickOut(false);
    selectHoverFeature.setAutoActivate(true);

    mapWidget.getMap().addControl(selectHoverFeature);
    mapWidget.getMap().addControl(selectFeature);

    // Define a style for the vectors
    Style style = new Style();
    style.setFillColor("red");
    style.setStrokeColor("green");
    style.setStrokeWidth(2);
    style.setFillOpacity(0.9);
    style.setPointRadius(30);

    Style selectedStyle = new Style();
    selectedStyle.setFillColor("yellow");
    selectedStyle.setStrokeColor("yellow");
    selectedStyle.setStrokeWidth(2);
    selectedStyle.setFillOpacity(0.9);
    selectedStyle.setPointRadius(30);

    Style hoverStyle = new Style();
    hoverStyle.setFillColor("blue");
    hoverStyle.setStrokeColor("pink");
    hoverStyle.setStrokeWidth(2);
    hoverStyle.setFillOpacity(0.9);
    hoverStyle.setPointRadius(30);

    StyleMap styleMap = new StyleMap(style, selectedStyle, hoverStyle);
    vectorLayer.setStyleMap(styleMap);

    // Add a point
    Point point = new Point(146.7, -41.8);
    final VectorFeature pointFeature = new VectorFeature(point);
    vectorLayer.addFeature(pointFeature);

    // capture clicks on the vectorlayer
    vectorLayer
            .addVectorFeatureSelectedListener(new VectorFeatureSelectedListener() {
                public void onFeatureSelected(
                        FeatureSelectedEvent eventObject) {
                    Window.alert("The vector is now selected.\nIt will get de-selected when closing this popup.");
                    selectFeature.unSelect(eventObject.getVectorFeature());
                }
            });

    // Attach a popup to the point, we use null as size cause we set
    // autoSize to true
    // Note that we use FramedCloud... This extends a normal popup and
    // creates is styled as a baloon
    // We want to display this popup on hover, and hide it when hovering
    // ends

    final Popup popup = new FramedCloud("id1",
            pointFeature.getCenterLonLat(), null,
            "<h1>Some popup text</H1><BR/>And more text", null, false);
    popup.setPanMapIfOutOfView(true); // this set the popup in a strategic
                                        // way, and pans the map if needed.
    popup.setAutoSize(true);
    pointFeature.setPopup(popup);

    // capture hover by adding a listener to the control, and display the
    // popup
    selectHoverFeature
            .addFeatureHighlightedListener(new FeatureHighlightedListener() {

                public void onFeatureHighlighted(VectorFeature vectorFeature) {
                    mapWidget.getMap().addPopup(vectorFeature.getPopup());
                }
            });

    // capture unhover, and remove popup
    selectHoverFeature
            .addFeatureUnhighlightedListener(new FeatureUnhighlightedListener() {

                public void onFeatureUnhighlighted(
                        VectorFeature vectorFeature) {
                    mapWidget.getMap()
                            .removePopup(vectorFeature.getPopup());
                }
            });

    // Center and zoom to a location
    mapWidget.getMap().setCenter(new LonLat(146.7, -41.8), 6);

    contentPanel
            .add(new HTML(
                    "<p>This example shows how to add a Vector (point) to map, and do some action when hovering, and another when clicking.</p>"
                            + "<p>"
                            + "<LI>Hover over the point. This will cause a popup to show, and change the style of the point to the temporary style.</LI>"
                            + "<LI>Then when you click the Vector gets selected, gets another style, and a Window.alert is displayed.</LI>"
                            + "<LI>When closing the Window.alert, the Vector gets de-selected.</p>"));

    contentPanel.add(mapWidget);

    initWidget(contentPanel);

    mapWidget.getElement().getFirstChildElement().getStyle().setZIndex(0); 
}
person Knarf    schedule 18.12.2013
comment
Демонстрационный пример в Интернете: demo.gwt- openlayers.org/gwt_ol_showcase/ - person Knarf; 19.12.2013

Вы действительно должны использовать SelectFeature для достижения этого. Секрет в том, что вы должны передать SelectFeatureOptions только с включенным выделением.

Что-то типа

   SelectFeatureOptions selectFeatureOptions = new SelectFeatureOptions();
   selectFeatureOptions.setHighlightOnly(true);

   SelectFeature selectFeature = new SelectFeature(vectorLayer,selectFeatureOptions);
person Knarf    schedule 17.12.2013
comment
Здравствуйте Knarn, спасибо за ответ. ваше предложение работает, но тогда есть другая проблема. когда я устанавливаю предлагаемые настройки, теперь я не могу выбрать функцию по щелчку мыши. как только я это сделаю и подвигаю мышью, эта функция не будет выбрана. как сказано в моем вопросе, мне нужны две вещи: 1. при наведении я должен показывать всплывающую подсказку, не выбирая функцию, и 2. когда я нажимаю на функцию, она должна быть выбрана. любая дальнейшая помощь приветствуется. С уважением, Джатин - person user2163450; 18.12.2013
comment
Я подробно изучу это в один из следующих дней. (обратите внимание, что я являюсь одним из участников GWT-OpenLayers). я буду держать вас в курсе - person Knarf; 18.12.2013