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

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

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

Как это может быть достигнуто?

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

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); 
}

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

Что-то вроде

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

   SelectFeature selectFeature = new SelectFeature(vectorLayer,selectFeatureOptions);
Другие вопросы по тегам