⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 kmlwriter.java

📁 电子地图服务器,搭建自己的地图服务
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
		final int rulesLength = rules.length;

		for (int j = 0; j < rulesLength; j++) {
			Rule r = rules[j];

			if (ignoreScale) {
				if (r.hasElseFilter()) {
					elseRuleList.add(r);
				} else {
					ruleList.add(r);
				}
			} else {
				if (isWithinScale(r)) {
					if (r.hasElseFilter()) {
						elseRuleList.add(r);
					} else {
						ruleList.add(r);
					}
				}
			}
		}
	}

	private void writeDescription(Feature feature, final FeatureType schema)
			throws IOException {
		if (mapContext.getRequest().getKMattr()) {
			// descriptions are "templatable" by users, so see if there is a
			// template available for use
			GeoServerTemplateLoader templateLoader = new GeoServerTemplateLoader(
					getClass());
			templateLoader.setFeatureType(schema);

			Template template = null;

			// Configuration is not thread safe
			synchronized (templateConfig) {
				templateConfig.setTemplateLoader(templateLoader);
				template = templateConfig.getTemplate("kmlDescription.ftl");
			}

			try {
			    template.setEncoding("UTF-8");
				template.process(feature, this);
			} catch (TemplateException e) {
				String msg = "Error occured processing template.";
				throw (IOException) new IOException(msg).initCause(e);
			}
		}
	}

	private void processVectorSymbolizers(final Feature feature,
			final Symbolizer[] symbolizers, Range scaleRange,
			StringBuffer featureLabel) throws IOException, TransformerException {
		final int length = symbolizers.length;

		// for each Symbolizer (text, polygon, line etc...)
		for (int m = 0; m < length; m++) {
			LOGGER.finer(new StringBuffer("applying symbolizer ").append(
					symbolizers[m]).toString());

			if (symbolizers[m] instanceof TextSymbolizer) {
				TextSymbolizer ts = (TextSymbolizer) symbolizers[m];
				Expression ex = ts.getLabel();
				featureLabel
						.append((String) ex.evaluate(feature, String.class)); // attach
																				// the
																				// lable
																				// title

				Style2D style = styleFactory.createStyle(feature,
						symbolizers[m], scaleRange);
				writeStyle(style, feature.getID(), symbolizers[m]);
			} else { // all other symbolizers

				Style2D style = styleFactory.createStyle(feature,
						symbolizers[m], scaleRange);
				writeStyle(style, feature.getID(), symbolizers[m]);
			}
		} // end for loop
	}

	/**
	 * Writes out the KML for a ground overlay. The image is processed later on.
	 * 
	 * This will style the KML for raster output. There are no descriptions with
	 * vector output, as that would make the result really large (assuming that
	 * they chose raster output because a lot of features were requested).
	 * 
	 * 
	 * @param feature
	 * @param symbolizers
	 * @param order
	 * @throws IOException
	 * @throws TransformerException
	 */
	private void processRasterSymbolizers(final Feature feature,
			final Symbolizer[] symbolizers, final int order)
			throws IOException, TransformerException {
		if (symbolizers.length < 1) {
			return; // no symbolizers so return
		}

		LOGGER.finer("applying one symbolizer: " + symbolizers[0].toString());

		com.vividsolutions.jts.geom.Envelope envelope = this.mapContext
				.getRequest().getBbox();
		write(new StringBuffer("<GroundOverlay>").append("<name>").append(
				feature.getID()).append("</name>").append("<drawOrder>")
				.append(order).append("</drawOrder>").append("<Icon>")
				.toString());

		final double[] BBOX = new double[] { envelope.getMinX(),
				envelope.getMinY(), envelope.getMaxX(), envelope.getMaxY() };
		write(new StringBuffer("<href>layer_").append(order).append(
				".png</href>").append(
				"<viewRefreshMode>never</viewRefreshMode>").append(
				"<viewBoundScale>0.75</viewBoundScale>").append("</Icon>")
				.append("<LatLonBox>").append("<north>").append(BBOX[3])
				.append("</north>").append("<south>").append(BBOX[1]).append(
						"</south>").append("<east>").append(BBOX[2]).append(
						"</east>").append("<west>").append(BBOX[0]).append(
						"</west>").append("</LatLonBox>").append(
						"</GroundOverlay>").toString());
	}

	/**
	 * Writes out the KML for a ground overlay. The image is processed later on.
	 * 
	 * @param feature
	 * @param symbolizers
	 * @param order
	 * @throws IOException
	 * @throws TransformerException
	 */
	private void processRasterSymbolizersForCoverage(final Feature feature,
			final Symbolizer[] symbolizers, final MapLayer layer)
			throws IOException, TransformerException {
		if (symbolizers.length < 1) {
			return; // no symbolizers so return
		}

		LOGGER.finer("applying one symbolizer: " + symbolizers[0].toString());

		final AbstractGridCoverage2DReader gcReader = (AbstractGridCoverage2DReader) feature
				.getAttribute("grid");

		// TODO add read parameters feature.getAttribute("params")
		final HttpServletRequest request = this.mapContext.getRequest()
				.getHttpServletRequest();
		final String baseURL = org.vfny.geoserver.util.Requests.getBaseUrl(
				request, null);

		com.vividsolutions.jts.geom.Envelope envelope = this.mapContext
				.getRequest().getBbox();
		write(new StringBuffer("<GroundOverlay>").append("<name>").append(
				feature.getID()).append("</name>").append("<Icon>").toString());

		final double[] BBOX = new double[] { envelope.getMinX(),
				envelope.getMinY(), envelope.getMaxX(), envelope.getMaxY() };

		final StringBuffer getMapRequest = new StringBuffer(baseURL)
				.append("wms?bbox=")
				.append(BBOX[0])
				.append(",")
				.append(BBOX[1])
				.append(",")
				.append(BBOX[2])
				.append(",")
				.append(BBOX[3])
				.append("&amp;styles=")
				.append(layer.getStyle().getName())
				.append("&amp;Format=image/png&amp;request=GetMap&amp;layers=")
				.append(layer.getTitle())
				.append(
						"&amp;width="
								+ this.mapContext.getMapWidth()
								+ "&amp;height="
								+ this.mapContext.getMapHeight()
								+ "&amp;srs=EPSG:4326&amp;transparent=true&amp;");

		write(new StringBuffer("<href>").append(getMapRequest)
				.append("</href>").append(
						"<viewRefreshMode>never</viewRefreshMode>").append(
						"<viewBoundScale>0.75</viewBoundScale>").append(
						"</Icon>").append("<LatLonBox>").append("<north>")
				.append(BBOX[3]).append("</north>").append("<south>").append(
						BBOX[1]).append("</south>").append("<east>").append(
						BBOX[2]).append("</east>").append("<west>").append(
						BBOX[0]).append("</west>").append("</LatLonBox>")
				.append("</GroundOverlay>").toString());
	}

	/**
	 * Applies each of a set of symbolizers in turn to a given feature.
	 * <p>
	 * This is an internal method and should only be called by processStylers.
	 * </p>
	 * 
	 * The KML color tag: The order of expression is alpha, blue, green, red
	 * (ABGR). The range of values for any one color is 0 to 255 (00 to ff). For
	 * opacity, 00 is fully transparent and ff is fully opaque.
	 * 
	 * @param feature
	 *            The feature to be rendered
	 * @param symbolizers
	 *            An array of symbolizers which actually perform the rendering.
	 * @param scaleRange
	 *            The scale range we are working on... provided in order to make
	 *            the style factory happy
	 */
	private boolean processSymbolizers(final FeatureCollection features,
			final Feature feature, final Symbolizer[] symbolizers,
			Range scaleRange, final MapLayer layer, final int order,
			final int layerCounter, StringBuffer title, boolean vectorResult)
			throws IOException, TransformerException {
		boolean res = false;

		// String title=null;
		final int length = symbolizers.length;

		// for each Symbolizer (text, polygon, line etc...)
		for (int m = 0; m < length; m++) {
			LOGGER.finer(new StringBuffer("applying symbolizer ").append(
					symbolizers[m]).toString());

			if (symbolizers[m] instanceof RasterSymbolizer) {
				// LOGGER.info("Removed by bao for testing");
				/*
				 * final GridCoverage gc = (GridCoverage)
				 * feature.getAttribute("grid"); final HttpServletRequest
				 * request =
				 * this.mapContext.getRequest().getHttpServletRequest(); final
				 * String baseURL =
				 * org.vfny.geoserver.util.Requests.getBaseUrl(request);
				 * com.vividsolutions.jts.geom.Envelope envelope =
				 * this.mapContext.getRequest().getBbox();
				 */

				/**
				 * EXAMPLE OUTPUT: <GroundOverlay> <name>Google Earth - New
				 * Image Overlay</name> <Icon>
				 * <href>http://localhost:8081/geoserver/wms?bbox=-130,24,-66,50&amp;styles=raster&amp;Format=image/tiff&amp;request=GetMap&amp;layers=nurc:Img_Sample&amp;width=550&amp;height=250&amp;srs=EPSG:4326&amp;</href>
				 * <viewRefreshMode>never</viewRefreshMode>
				 * <viewBoundScale>0.75</viewBoundScale> </Icon> <LatLonBox>
				 * <north>50.0</north> <south>24.0</south> <east>-66.0</east>
				 * <west>-130.0</west> </LatLonBox> </GroundOverlay>
				 */

				/*
				 * write(new StringBuffer("<GroundOverlay>"). append("<name>").append(((GridCoverage2D)gc).getName()).append("</name>").
				 * append("<drawOrder>").append(order).append("</drawOrder>").
				 * append("<Icon>").toString()); final double[] BBOX = new
				 * double[] { envelope.getMinX(), envelope.getMinY(),
				 * envelope.getMaxX(), envelope.getMaxY() }; if (layerCounter<0) {
				 * final StringBuffer getMapRequest = new
				 * StringBuffer(baseURL).append("wms?bbox=").append(BBOX[0]).append(",").
				 * append(BBOX[1]).append(",").append(BBOX[2]).append(",").append(BBOX[3]).append("&amp;styles=").
				 * append(layer.getStyle().getName()).append("&amp;Format=image/png&amp;request=GetMap&amp;layers=").
				 * append(layer.getTitle()).append("&amp;width="+this.mapContext.getMapWidth()+"&amp;height="+this.mapContext.getMapHeight()+"&amp;srs=EPSG:4326&amp;");
				 * write("<href>"+getMapRequest.toString()+"</href>"); } else {
				 * write("<href>layer_"+order+".png</href>"); } write(new
				 * StringBuffer("<viewRefreshMode>never</viewRefreshMode>").
				 * append("<viewBoundScale>0.75</viewBoundScale>"). append("</Icon>").
				 * append("<LatLonBox>"). append("<north>").append(BBOX[3]).append("</north>").
				 * append("<south>").append(BBOX[1]).append("</south>").
				 * append("<east>").append(BBOX[2]).append("</east>").
				 * append("<west>").append(BBOX[0]).append("</west>").
				 * append("</LatLonBox>"). append("</GroundOverlay>").toString());
				 * //Geometry g = findGeometry(feature, symbolizers[m]);
				 * //writeRasterStyle(getMapRequest.toString(),
				 * feature.getID());
				 */
				res = true;
			} else if (vectorResult) {
				// TODO: come back and sort out crs transformation
				// CoordinateReferenceSystem crs = findGeometryCS(feature,
				// symbolizers[m]);
				if (symbolizers[m] instanceof TextSymbolizer) {
					TextSymbolizer ts = (TextSymbolizer) symbolizers[m];
					Expression ex = ts.getLabel();
					String value = (String) ex.evaluate(feature, String.class);
					title.append(value);

					Style2D style = styleFactory.createStyle(feature,
							symbolizers[m], scaleRange);
					writeStyle(style, feature.getID(), symbolizers[m]);
				} else {
					Style2D style = styleFactory.createStyle(feature,
							symbolizers[m], scaleRange);
					writeStyle(style, feature.getID(), symbolizers[m]);
				}
			} else if (!vectorResult) {
				com.vividsolutions.jts.geom.Envelope envelope = this.mapContext
						.getRequest().getBbox();
				write(new StringBuffer("<GroundOverlay>").append("<name>")
						.append(feature.getID()).append("</name>").append(
								"<drawOrder>").append(order).append(
								"</drawOrder>").append("<Icon>").toString());

				final double[] BBOX = new double[] { envelope.getMinX(),
						envelope.getMinY(), envelope.getMaxX(),
						envelope.getMaxY() };
				write(new StringBuffer("<href>layer_").append(order).append(
						".png</href>").append(
						"<viewRefreshMode>never</viewRefreshMode>").append(
						"<viewBoundScale>0.75</viewBoundScale>").append(
						"</Icon>").append("<LatLonBox>").append("<north>")
						.append(BBOX[3]).append("</north>").append("<south>")
						.append(BBOX[1]).append("</south>").append("<east>")
						.append(BBOX[2]).append("</east>").append("<west>")
						.append(BBOX[0]).append("</west>").append(
								"</LatLonBox>").append("</GroundOverlay>")
						.toString());
			} else {
				LOGGER
						.info("KMZ processSymbolizerz unknown case. Please report error.");
			}
		}

		return res;
	}

	/**
	 * Adds the <style> tag to the KML document.
	 * 
	 * @param style
	 * @param id
	 * @throws IOException
	 */
	private void writeStyle(final Style2D style, final String id, Symbolizer sym)
			throws IOException {
		if (style instanceof PolygonStyle2D && sym instanceof PolygonSymbolizer) {
			if ((((PolygonStyle2D) style).getFill() == null)
					&& (((PolygonStyle2D) style).getStroke() == null)) {
				LOGGER
						.info("Empty PolygonSymbolizer, using default fill and stroke.");
			}

			final StringBuffer styleString = new StringBuffer();

			PolygonSymbolizer polySym = (PolygonSymbolizer) sym;

			// ** LABEL **
			styleString.append("<IconStyle>");

			if (!mapContext.getRequest().getKMattr()) { // if they don't want
														// attributes
				styleString.append("<color>#00ffffff</color>"); // fully
																// transparent
			}

			styleString
					.append("<Icon><href>root://icons/palette-3.png</href><x>224</x><w>32</w><h>32</h></Icon>");
			styleString.append("</IconStyle>");

			// ** FILL **
			styleString.append("<PolyStyle><color>");

			if (polySym.getFill() != null) // if they specified a fill
			{
				int opacity = 255; // default to full opacity

				if (polySym.getFill().getOpacity() != null) {
					float op = getOpacity(polySym.getFill().getOpacity());
					opacity = (new Float(255 * op)).intValue();
				}

				Paint p = ((PolygonStyle2D) style).getFill();

				if (p instanceof Color) {
					styleString.append("#").append(intToHex(opacity)).append(
							colorToHex((Color) p)); // transparancy needs to
													// come from the opacity
													// value.
				} else {
					styleString.append("#ffaaaaaa"); // should not occure in
														// normal parsing
				}
			} else { // no fill specified, make transparent
				styleString.append("#00aaaaaa");
			}

			// if there is an outline, specify that we have one, then style it
			styleString.append("</color>");

			if (polySym.getStroke() != null) {
				styleString.append("<outline>1</outline>");
			} else {
				styleString.append("<outline>0</outline>");
			}

			styleString.append("</PolyStyle>");

			// ** OUTLINE **
			if (polySym.getStroke() != null) // if there is an outline
			{
				styleString.append("<LineStyle><color>");

				int opacity = 255; // default to full opacity

				if (polySym.getStroke().getOpacity() != null) {
					float op = getOpacity(polySym.getStroke().getOpacity());
					opacity = (new Float(255 * op)).intValue();
				}

				Paint p = ((PolygonStyle2D) style).getContour();

				if (p instanceof Color) {
					styleString.append("#").append(intToHex(opacity)).append(
							colorToHex((Color) p)); // transparancy needs to
													// come from the opacity
													// value.
				} else {
					styleString.append("#ffaaaaaa"); // should not occure in
														// normal parsing
				}

				styleString.append("</color>");

				// stroke width
				if (polySym.getStroke().getWidth() != null) {
					int width = getWidth(polySym.getStroke().getWidth());
					styleString.append("<width>").append(width).append(
							"</width>");
				}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -