2012-01-12 5 views
12

Actualmente estoy buscando una solución para seleccionar (o resaltar) un vector en un OpenLayers.Layer.Vector.¿Cómo seleccionar una característica programáticamente en una capa vectorial en OpenLayers?

He creado una cuadrícula simple donde un usuario puede elegir un vector (dado como cadena con formato WKT) que debe resaltar el vector correspondiente en la capa. Todos los vectores en la tabla de grillas se dibujan a la capa vectorial en el mapa cuando el usuario visita el sitio.

descubrí que yo tampoco necesito el OpenLayers.Control.ModifyFeature 's selectFeature(feature) función o la OpenLayers.Control.SelectFeature (ver dev.openlayers.org/apidocs/files/OpenLayers/Control/SelectFeature-js.html's función de selección (función) (¿Qué probablemente no existe o ya no existe?). Consulte una publicación de una lista de correo: osgeo-org.1803224.n2.nabble.com/Programatically-Select-a-Feature-tt2192485.html#a2193928 para obtener más información. Info.

he intentado lo siguiente sin éxito, por lo que esperan que alguien podría capturar estas líneas de código y me podría mostrar un fragmento de código de trabajo ;-)

// ... some initializing code 
this.vlayer = new OpenLayers.Layer.Vector("VectorLayer"); // VectorLayer 

// some controls 
this.openLayerControlPoint = new OpenLayers.Control.DrawFeature(this.vlayer, OpenLayers.Handler.Point); 
this.openLayerControlPolygon = new OpenLayers.Control.DrawFeature(this.vlayer, OpenLayers.Handler.Polygon); 
this.openLayerControlModify = new OpenLayers.Control.ModifyFeature(this.vlayer, { 
    mode: OpenLayers.Control.ModifyFeature.RESHAPE | OpenLayers.Control.ModifyFeature.DRAG, 
    standalone: false 
}); 

// just deactivate to make sure everything is really deactivated 
this.openLayerControlPoint.deactivate(); 
this.openLayerControlPolygon.deactivate(); 
this.openLayerControlModify.deactivate(); 

// add the just created layer to the map 
this.map.addLayer(this.vlayer); 

// add all (deactivated) controls to the map 
this.map.addControl(this.openLayerControlPoint); 
this.map.addControl(this.openLayerControlPolygon); 
this.map.addControl(this.openLayerControlModify); 

Más adelante en código:

// ... another function doing the action 
selectVector: function(wktVector) { 
    this.openLayerControlModify.activate(); 

    // this is no elegant solution, this should only show how I would 
    // test the functionallity. 
    for (var i = 0; i < this.vlayer.features.length; ++i) { 
    // returns a WKT formatted string: 
    // 'POLYGON((xxxx.xxx xxxx.xxx), (xxxx.xxx xxxx.xxx))' 
    var wktVectorCurrent = this.vlayer.features[i].geometry.toString(); 
    if (wktVector == wktVectorCurrent) { 
     // \/ doesn't work :-(
     this.openLayerControlModify.selectFeature(this.vlayer.features[i]); 
     break; 
    } 
    } 
} 

Respuesta

20

No entiendo por qué está utilizando ModifyFeature para seleccionar una función. OpenLayers.Control.SelectFeature se realiza específicamente para seleccionar características, por lo que le sugiero que utilice este control.

Por lo tanto, crear el control SelectFeature:

var selectFeature = new OpenLayers.Control.SelectFeature(this.vlayer); 
selectFeature.activate(); 

Luego, en que la sentencia if (supongo que trabaja para encontrar una característica que desea seleccionar mediante la comparación de geometrías?) Usar select método:

if (wktVector == wktVectorCurrent) { 
    selectFeature.select(this.vlayer.features[i]); 
} 

de acuerdo con la documentación de este método debe marcar como característica seleccionada y provocar eventos apropiados:

* Method: select 
* Add feature to the layer's selectedFeature array, render the feature as 
* selected, and call the onSelect function. 

Si usted quiere hacer algo en el mapa cuando la función es seleccionado (como mostrar una ventana emergente), usted debe suscribirse capa vectorial para seleccionar al evento cuando se crea:

this.vlayer.events.on({'featureselected': function(){ 
    //Handle select event 
}}); 
+1

Gracias por su respuesta Esto funcionó para mí! Descubrí que el OpenLayers API Doc en la versión actual está roto (y no había ningún método 'select'). Aquí está trabajando [enlace a la API de OpenLayers] (http://dev.openlayers.org/docs/files/OpenLayers/Control/SelectFeature-js.html#OpenLayers.Control.SelectFeature.select) –

+4

mi consejo para el futuro es demasiado mira el código fuente de Openlayers en lugar de documentos. es fácil encontrar lo que necesita allí y obtendrá una mejor comprensión de cómo funcionan las cosas. a menudo encontrará valiosos comentarios en el código fuente que no verá en los documentos. – igorti

+4

tenga en cuenta que tendrá que agregar el control "selectFeature" al mapa antes de poder invocar activate en él. map.addControl (selectFeature); – JSancho

Cuestiones relacionadas