[Gvsig_desarrolladores] como crear una vista por codigo

Sergio Piñón sergiopinhon en gmail.com
Lun Ene 12 17:56:46 CET 2009


O Monday 12 January 2009 11:31:17 fsalas escribiu:
> algien me puede orientar como crear una vista por codigo.
>
> saludos Salas
>
> ___________________________________
> Dpto de Sistemas Informáticos
> Oficina Central Grupo Empresarial GEOCUBA
> Este mensaje esta libre de virus.
> Revisado por Kaspersky Antivirus
> ----------------------------------------------------------------------
> Engine version:  4.0.1.14
> Engine date:  2002/06/25
> Definition count:  1441530
> Definition date:  2009/01/12
> MDAV version: 2.2.8
Hola, te paso un ejemplo de la creación de un proyecto por código, no te va a 
funcionar a la primera, tendrás que quitarle las llamadas a varios métodos.
Para la creación de una vista lo que yo hago es definir una clae que extienda a 
Project, después creo un documento ProjectView y se lo añado a la instancia 
del proyecto.
Si quieres ver más ejemplos concretos sobre la creación de documentos, y 
asignación de leyendas puedes echarle un vistazo a mi proyecto para la 
valoración de localizaciones para empresas en:

https://forxa.mancomun.org/projects/sixempresas/

y allí navegar por el repositorio.

/****************************************************************************
 *   Copyright (C) 2008 by Sergio Piñón Campañó  						  					   	*
 *   sergiopinhon en gmail.com   											   								   	*
 *                                                                         				
										   	*
 *   This program is free software; you can redistribute it and/or modify  		   
	*
 *   it under the terms of the GNU General Public License as published by  	   
	*
 *   the Free Software Foundation; either version 2 of the License, or     		   
	*
 *   (at your option) any later version.                                   				
					*
 *                                                                         				
											*
 *   This program is distributed in the hope that it will be useful,       				
	*
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        	*
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the       *
 *   GNU General Public License for more details.                          				
		*
 *                                                                         				
											*
 *   You should have received a copy of the GNU General Public License     		*
 *   along with this program; if not, write to the                         				
				*
 *   Free Software Foundation, Inc.,                                       				
					*
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             			
*
 ***************************************************************************/
package proyecto;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.net.Inet4Address;
import java.net.Socket;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

import org.apache.log4j.Logger;
import org.cresques.cts.IProjection;

import utiles.ManejadorErrores;

import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
import com.iver.andami.PluginServices;
import com.iver.andami.ui.mdiManager.IWindow;
import com.iver.cit.gvsig.fmap.DriverException;
import com.iver.cit.gvsig.fmap.MapControl;
import com.iver.cit.gvsig.fmap.core.v02.FConstant;
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
import com.iver.cit.gvsig.fmap.layers.FLayer;
import com.iver.cit.gvsig.fmap.layers.FLyrDefault;
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
import com.iver.cit.gvsig.fmap.layers.FLyrWMS;
import com.iver.cit.gvsig.fmap.layers.layerOperations.ClassifiableVectorial;
import com.iver.cit.gvsig.fmap.rendering.FInterval;
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
import com.iver.cit.gvsig.fmap.rendering.VectorialIntervalLegend;
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
import com.iver.cit.gvsig.project.Project;
import com.iver.cit.gvsig.project.documents.ProjectDocument;
import com.iver.cit.gvsig.project.documents.view.MapOverview;
import com.iver.cit.gvsig.project.documents.view.ProjectViewFactory;
import com.iver.cit.gvsig.project.documents.view.gui.View;
import com.iver.utiles.extensionPoints.ExtensionPoint;
import com.iver.utiles.extensionPoints.ExtensionPoints;
import com.iver.utiles.extensionPoints.ExtensionPointsSingleton;

import controlador.Controlador;
import controlador.FachadaMapa;
import controlador.configuracion.ConfigTabla;
import controlador.configuracion.Configuracion;
import emplazamientos.Emplazamiento;

/**
 * @author Sergio Piñón Campañó
 *
 */

/**
 * Clase singleton utilizada para la creación de un proyecto al iniciar la 
guia de empresas
 */
public class ProyectoEmpresas extends Project /*implements LayerListener*/{
	/**
	 * 
	 */
	public static final int TAMANHO_PUNTOS_DEFECTO = 2;
	public static final int TAMANHO_ICONOS_DEFECTO = 8;
	
	private static final long serialVersionUID = 7951655722940671380L;
	private static Logger log = Logger.getLogger(ProyectoEmpresas.class);
	
	public static final String NOMBRE_PROJECT = "empreSIX";
	public static final String NOMBRE_PROJECTVIEW = "empreSIX-vista";

	//referencia a la instancia del proyecto
	private static ProyectoEmpresas instancia;
	
	/*la vista asociada con este proyecto*/
	private View vista;
	/*asociación de nombres de tabla con capas*/
	private HashMap<String, FLayer> tablasCapas = new HashMap();
	/*el cargador de las capas desde postgis*/
	CargadorCapas cargador;
	
	private ArrayList<ListenerVistaImpl> listenersWMS = new 
ArrayList<ListenerVistaImpl>();
	
	/**
	 * 	Devuelve una instancia del proyecto, si éste todavía no fue creado
	 * se crea uno.
	 * Las tablas a cargar se obtienen de la clase Configuracion
	 * 
	 * @return el proyecto de empresas
	 */ 
	public static synchronized ProyectoEmpresas getProyecto() {
		if(instancia == null)
			instancia = new ProyectoEmpresas();
		return instancia;
	}
	
	
	private ProyectoEmpresas() {
		super();
		try {
			this.setName(NOMBRE_PROJECT);
			//creamos un documento de tipo vista para añadir a nuestro proyecto
			ExtensionPoints extensionPoints = ExtensionPointsSingleton.getInstance();
			ExtensionPoint extensionPoint 
=(ExtensionPoint)extensionPoints.get("Documents");
			ProjectViewFactory projectViewFactory = (ProjectViewFactory) 
extensionPoint.create("ProjectView");
			ProjectDocument documento = projectViewFactory.create(this);
			documento.setProjectDocumentFactory(projectViewFactory);
			documento.setName(NOMBRE_PROJECTVIEW);
			//añadimos el ProjectView al proyecto
			this.addDocument(documento);
			
			/*creamos la vista del mapa*/
			this.abrir();
			
			//cargamos las capas desde las  tablas de la BD
			cargador = new CargadorCapas();
			Configuracion confXML = Controlador.getConfiguracion();
			for(ConfigTabla tablaConf : confXML.getListaTablas()) {
				log.info("Cargando tabla: "+tablaConf.getNombre());
				FLyrVect f = cargador.cargarTabla( tablaConf.getNombre(), 
tablaConf.getPosicion(), vista);

				f.setName(tablaConf.getNombreCapa());
				tablasCapas.put(tablaConf.getNombre(), f);
				/*le ponemos la leyenda*/
				log.info("Asignando leyenda para tabla: "+tablaConf.getNombre());
				asignarLeyenda(tablaConf.getNombre(), tablaConf.getCampoLeyenda(), 
tablaConf.getColor(),
						tablaConf.getTamanhoFuente(), tablaConf.getIcono(), 
tablaConf.getIconoURI());
				
			}
			/*cargamos las capas WMS*/
			for(HashMap m : confXML.getListaWMS()) {
				log.info("Cargando capa WMS: "+m.get("host"));
				try {
				Inet4Address.getByName(getHostFromURL((String)m.get("host")));
				m.put("FullExtent", 
vista.getMapControl().getMapContext().getFullExtent());
				FLyrWMS capaWMS = new FLyrWMS(m);
				capaWMS.setCachingDrawnLayers(true);
				capaWMS.setName((String)(m.get("nombre")));
				capaWMS.setTransparency((Integer)m.get("transparencia"));
				
vista.getMapControl().getMapContext().getLayers().addLayer((Integer)m.get("posicion"), 
capaWMS);
				ListenerVistaImpl listenerWMS = new ListenerVistaImpl(capaWMS, 
(Double)m.get("areaExtent"));
				vista.getMapControl().getViewPort().addViewPortListener(listenerWMS);
				listenersWMS.add(listenerWMS);
				capaWMS.setInTOC(false);
				tablasCapas.put((String)m.get("host"), capaWMS);
				}catch (UnknownHostException e) {
					ManejadorErrores.mostrar("No hay conexion con host: "+m.get("host")+"\n"+
							"La capa "+m.get("nombre")+" no se cargará.");
				}
			}

			/*asignamos proyecciones según fichero de configuración*/
			IProjection projDefecto = tablasCapas.get( 
confXML.getNombreTablaProyeccion() ).getProjection();
			/*asignamos la proyección de la vista al proyecto*/
			this.setProjection(projDefecto);
			/*al asignar la proyección a la vista se asigna también al mapControl y al 
mapContext*/
			vista.setProjection(projDefecto);
			/*comprobamos si el resto de capas están en la misma proyección que la de 
la capa por defecto
			 * y reproyectamos si no lo están*/
			for(FLayer f : tablasCapas.values()) {
				if(f.isReprojectable() && !
(f.getProjection().getAbrev().equals(projDefecto.getAbrev()))) {
					log.warn("Se reproyecta la capa: "+f.getName());
					ManejadorErrores.mostrar("Se reproyectará la capa: "+f.getName());
					f.reProject(vista.getMapControl());
				}
			}
			
			/*añadimos las capas vectoriales al mapOverview*/
			MapOverview mapOverview = vista.getMapOverview();
			for(FLayer f : tablasCapas.values())
				mapOverview.getMapContext().getLayers().addLayer(f);
			
mapOverview.getViewPort().setExtent(vista.getMapControl().getMapContext().getFullExtent());

			
	
			System.out.println("");
		} catch (Exception e) {
			ManejadorErrores.mostrar(e);
		}
		
	}
	
	/**
	 * devuelve una capa dado el nombre de la tabla o null si no se encontró
	 * @param nombreTabla
	 * @return
	 */
	public FLayer getCapaByTabla(String nombreTabla) {
		return tablasCapas.get(nombreTabla);
	}
	
	public View getVista() {
		return vista;
	}
	

	/**
	 * 
	 * @return el SRID de la proyección del proyecto
	 */
	public int getSrid() {
		return(Integer.parseInt( getProjection().getAbrev().substring(5))) ;
	}

	
	/**
	 * Crea la vista de un nuevo project view
	 * @todo: modificarlo y ponerlo "bien bien"
	 */
	private void abrir() {
		ProjectDocument doc = null;
		/*recuperamos el ProjectView*/
		for( ProjectDocument d : (ArrayList<ProjectDocument>) this.getDocuments()) {
			if(d.getName().equals(NOMBRE_PROJECTVIEW))
				 doc = d;
		}
		/*creamos la ventana */
		IWindow window=doc.createWindow();
		
		if (window == null){
			JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), 
PluginServices.getText(this, "error_opening_the_document"));
			return;
		}
		vista =(View) window;
	}


	

-- 
Un saludo,
   Sergio.



Más información sobre la lista de distribución gvSIG_desarrolladores