/** * Parse the string and convert it to a {@link java.awt.Color}. See class description for details * on the supported color formats. * * @param colorString the color string encoded. */ public static Color toColor(final String colorString) { String trimmedString = colorString.trim(); Color color = null; if (trimmedString.startsWith("#")) { final int shortHexCode = 4; if (trimmedString.length() == shortHexCode) { StringBuilder builder = new StringBuilder("#"); for (int i = 1; i < trimmedString.length(); i++) { builder.append(trimmedString.charAt(i)); builder.append(trimmedString.charAt(i)); } color = SLD.toColor(builder.toString()); } else { color = SLD.toColor(trimmedString); } } if (color == null) { color = parseRgbColor(trimmedString); } if (color == null) { color = parseRgbaColor(trimmedString); } if (color == null) { color = parseHslColor(trimmedString); } if (color == null) { color = parseHslaColor(trimmedString); } if (color == null) { final Field[] fields = Color.class.getFields(); for (Field field : fields) { if (field.getType() == Color.class && Modifier.isFinal(field.getModifiers()) && Modifier.isStatic(field.getModifiers()) && field.getName().equalsIgnoreCase(trimmedString)) { try { return (Color) field.get(null); } catch (IllegalAccessException e) { throw new Error(e); } } } color = Color.decode(trimmedString); } return color; }
private static void constructMapUI(final File shapefile) { JMapFrame frame; MapContent map = new MapContent(); FileDataStore dataStore; SimpleFeatureSource shapefileSource; try { dataStore = FileDataStoreFinder.getDataStore(shapefile); shapefileSource = dataStore.getFeatureSource(); } catch (IOException e) { e.printStackTrace(); return; } Style shpStyle = SLD.createPolygonStyle(Color.RED, null, 0.0f); Layer shpLayer = new FeatureLayer(shapefileSource, shpStyle); map.addLayer(shpLayer); frame = new JMapFrame(map); frame.enableLayerTable(true); frame.setSize(1000, 800); frame.enableStatusBar(true); frame.enableToolBar(true); frame.setTitle("Map Viewer (courtesy of GeoTools"); JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); frame.setVisible(true); frame.setDefaultCloseOperation(JMapFrame.HIDE_ON_CLOSE); }
public void handleAction(final FlowModel flowModel) throws OgcFlowException { WFSLayer wfsLayer = findWFSLayer(flowModel); log.debug("Drawing image for wfs layer '" + wfsLayer.getName(locale) + "'"); List<Future<WFSResponseCapsule>> futures = new ArrayList<Future<WFSResponseCapsule>>(); /* Create workers */ log.debug("We have " + wfsLayer.getSelectedFeatureTypes().size() + " selected feature types"); for (SelectedFeatureType sft : wfsLayer.getSelectedFeatureTypes()) { FeatureType ft = sft.getFeatureType(); log.debug("Processing featuretype '", ft.getTitle(locale), "'..."); /* Create filter */ String geomName = ft.getBboxParameterName(); FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints()); GetFeaturesWorker worker = new GetFeaturesWorker(sft, getExtendedMapViewBbox(ff, geomName, flowModel), false); Future<WFSResponseCapsule> future = WfsExecutorService.schedule(worker); futures.add(future); } /* collect results */ FeatureCollection<SimpleFeatureType, SimpleFeature> features = WfsExecutorService.collectFeaturesFromFutures(futures); String[] bbox = getBbox(flowModel); Double bboxMinX = Double.parseDouble(bbox[0]); Double bboxMinY = Double.parseDouble(bbox[1]); Double bboxMaxX = Double.parseDouble(bbox[2]); Double bboxMaxY = Double.parseDouble(bbox[3]); MapContext mapContext = buildMapContext(); ReferencedEnvelope bounds = new ReferencedEnvelope( bboxMaxX, bboxMinX, bboxMaxY, bboxMinY, mapContext.getCoordinateReferenceSystem()); /* Add all found features */ if (features != null && features.size() > 0) { log.debug("Parsing found " + features.size() + " features."); String styleString = wfsLayer.getStyle(); // TODO: sld styles should be stored in the database if (styleString == null || "".equals(styleString)) { styleString = SLDStore.getSLD( wfsLayer .getWmsName()); // MapLayerServiceNoDbImpl.getSldStyle(wfsLayer.getWmsName()); } Style style = SLD.styles(createSLDStyle(styleString))[0]; mapContext.addLayer(features, style); } else { log.debug("Parsing found no features."); } BufferedImage image = renderImageFromFeatures(flowModel, mapContext, bounds); /*image.getGraphics().setColor(new Color(1f, 0, 0)); image.getGraphics().drawRect(1, 1, image.getWidth()-1, image.getHeight()-1);*/ flowModel.put("image", image); }
/** The constructor. */ public ViewTest() { // Create a map content and add our shapefile to it map = new MapContent(); map.setTitle("simple map content"); // hey, try for an image aswell String path = "/Users/ian/Desktop/ukrasterchart/2_BRITISH_ISLES.tif"; File chartFile = new File(path); if (!chartFile.exists()) System.err.println("CANNOT FILE THE CHART FILE!!!"); WorldImageFormat format = new WorldImageFormat(); AbstractGridCoverage2DReader tiffReader = format.getReader(chartFile); if (tiffReader != null) { StyleFactoryImpl sf = new StyleFactoryImpl(); RasterSymbolizer symbolizer = sf.getDefaultRasterSymbolizer(); Style defaultStyle = SLD.wrapSymbolizers(symbolizer); GeneralParameterValue[] params = null; GridReaderLayer res = new GridReaderLayer(tiffReader, defaultStyle, params); map.addLayer(res); } try { URL url = GtActivator.getDefault().getBundle().getEntry("data/50m_admin_0_countries.shp"); String filePath = FileLocator.resolve(url).getFile(); File file = new File(filePath); if (!file.exists()) System.err.println("can't find file!!!"); FileDataStore store = FileDataStoreFinder.getDataStore(file); if (store != null) { SimpleFeatureSource featureSource = store.getFeatureSource(); Style style = SLD.createSimpleStyle(featureSource.getSchema()); Layer layer = new FeatureLayer(featureSource, style); map.addLayer(layer); } } catch (IOException e) { } // }
/** * Parses SLD style from an InputStream (XML) * * @param xml * @return sld */ private Style createSLDStyle(InputStream xml) { Configuration config = new SLDConfiguration(); Parser parser = new Parser(config); StyledLayerDescriptor sld = null; try { sld = (StyledLayerDescriptor) parser.parse(xml); } catch (Exception e) { log.error(e, "Failed to create SLD Style"); return null; } return SLD.styles(sld)[0]; }
@SuppressWarnings("unchecked") private static Style createStyle(SimpleFeatureSource source, String fieldName) throws Exception { StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory(); FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(); Function colourFn = ff.function("colorlookup", ff.literal(source), ff.property(fieldName)); Stroke stroke = styleFactory.createStroke( colourFn, ff.literal(1.0f), // line // width ff.literal(1.0f)); // opacity Fill fill = styleFactory.createFill(colourFn, ff.literal(1.0f)); // opacity Class<?> geomClass = source.getSchema().getGeometryDescriptor().getType().getBinding(); Symbolizer sym = null; Geometries geomType = Geometries.getForBinding((Class<? extends Geometry>) geomClass); switch (geomType) { case POLYGON: case MULTIPOLYGON: sym = styleFactory.createPolygonSymbolizer(stroke, fill, null); break; case LINESTRING: case MULTILINESTRING: sym = styleFactory.createLineSymbolizer(stroke, null); break; case POINT: case MULTIPOINT: Graphic gr = styleFactory.createDefaultGraphic(); gr.graphicalSymbols().clear(); Mark mark = styleFactory.getCircleMark(); mark.setFill(fill); mark.setStroke(stroke); gr.graphicalSymbols().add(mark); gr.setSize(ff.literal(10.0f)); sym = styleFactory.createPointSymbolizer(gr, null); break; default: throw new IllegalArgumentException("Unsupported geometry type"); } Style style = SLD.wrapSymbolizers(sym); return style; }
public Style style(IProgressMonitor monitor) { URL url = parent.getIdentifier(); File file = URLUtils.urlToFile(url); String shp = file.getAbsolutePath(); StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory(GeoTools.getDefaultHints()); // strip off the extension and check for sld String sld = shp.substring(0, shp.length() - 4) + ".sld"; // $NON-NLS-1$ File f = new File(sld); if (!f.exists()) { // try upper case sld = shp.substring(0, shp.length() - 4) + ".SLD"; // $NON-NLS-1$ f = new File(sld); } if (f.exists()) { // parse it up SLDParser parser = new SLDParser(styleFactory); try { parser.setInput(f); } catch (FileNotFoundException e) { return null; // well that is unexpected since f.exists() } Style[] styles = parser.readXML(); FeatureSource<SimpleFeatureType, SimpleFeature> source; try { source = featureSource(null); } catch (IOException e) { return null; // does not look like there is anything in the shapefile } SimpleFeatureType featureType = source.getSchema(); // put the first one on if (styles != null && styles.length > 0) { Style style = SLD.matchingStyle(styles, featureType); if (style == null) { style = styles[0]; } makeGraphicsAbsolute(file, style); return style; } } return null; // well nothing worked out; make your own style }
public void run() { Display display = Display.getCurrent(); Shell shell = new Shell(display); File openFile = JFileImageChooser.showOpenFile(shell); if (openFile != null && openFile.exists()) { AbstractGridFormat format = GridFormatFinder.findFormat(openFile); AbstractGridCoverage2DReader tiffReader = format.getReader(openFile); StyleFactoryImpl sf = new StyleFactoryImpl(); RasterSymbolizer symbolizer = sf.getDefaultRasterSymbolizer(); Style defaultStyle = SLD.wrapSymbolizers(symbolizer); MapContext mapContext = mapPane.getMapContext(); MapLayer layer = new MapLayer(tiffReader, defaultStyle); layer.setTitle(openFile.getName()); mapContext.addLayer(layer); mapPane.redraw(); } }
@Override public Feature decorate(Feature feature, KmlEncodingContext context) { Placemark pm = (Placemark) feature; // try with the template SimpleFeature sf = context.getCurrentFeature(); String title = null; try { title = context.getTemplate().title(sf); } catch (IOException e) { String msg = "Error occured processing 'title' template."; LOGGER.log(Level.WARNING, msg, e); } // if we got nothing, set the title to the ID, but also try the text symbolizers if (title == null || "".equals(title)) { title = sf.getID(); StringBuffer label = new StringBuffer(); for (Symbolizer sym : context.getCurrentSymbolizers()) { if (sym instanceof TextSymbolizer) { Expression e = SLD.textLabel((TextSymbolizer) sym); String value = e.evaluate(feature, String.class); if ((value != null) && !"".equals(value.trim())) { label.append(value); } } } if (label.length() > 0) { title = label.toString(); } } pm.setName(title); return pm; }