无需引用任何第三方GIS库,自定义组织kml结构,然后导出。
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.9</version>
</dependency>
import cn.hutool.core.io.IoUtil;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.List;
public class KMLUtils {
public static String getKmlStr(List<GvClue> gvClueList) {
String dateStr = DateUtils.dateTimeNow();
String kml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
"<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n" +
"<Document id=\"root_doc\">\n" +
"<Schema name=\"" + dateStr + "\" id=\"" + dateStr + "\">\n" +
"\t<SimpleField name=\"name\" type=\"string\"></SimpleField>\n" +
"\t<SimpleField name=\"code\" type=\"string\"></SimpleField>\n" +
"\t<SimpleField name=\"category\" type=\"string\"></SimpleField>\n" +
"\t<SimpleField name=\"region\" type=\"string\"></SimpleField>\n" +
"\t<SimpleField name=\"shapeArea\" type=\"string\"></SimpleField>\n" +
"</Schema>\n" +
"<Folder><name>" + dateStr + "</name>\n" +
"%s\n" +
"</Folder>\n" +
"</Document>\n" +
"</kml>";
StringBuilder placemarks = new StringBuilder();
for (GvClue gvClue : gvClueList) {
String placemark = "\t<Placemark>\n" +
"\t<ExtendedData><SchemaData schemaUrl=\"" + dateStr + "\">\n" +
"\t\t<SimpleData name=\"name\">%s</SimpleData>\n" +
"\t\t<SimpleData name=\"code\">%s</SimpleData>\n" +
"\t\t<SimpleData name=\"category\">%s</SimpleData>\n" +
"\t\t<SimpleData name=\"region\">%s</SimpleData>\n" +
"\t\t<SimpleData name=\"shapeArea\">%s</SimpleData>\n" +
"\t</SchemaData></ExtendedData>\n" +
"\t%s\n" +
"\t</Placemark>\n";
placemark = String.format(placemark, gvClue.getName(), gvClue.getCode(), gvClue.getCategory(), gvClue.getRegion(), gvClue.getShapeArea(), gvClue.getKml());
placemarks.append(placemark);
}
kml = String.format(kml, placemarks);
return kml;
}
public static void downloadKml(HttpServletResponse response, List<GvClue> gvClueList) {
String kml = getKmlStr(gvClueList);
// 文件下载
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
response.setContentType("application/vnd.google-earth.kml+xml");
response.setHeader("Content-Disposition", "attachment;filename=" + DateUtils.dateTimeNow() + ".kml");
response.setContentType("application/octet-stream;charset=UTF-8");
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
IoUtil.write(outputStream, true, kml.getBytes(Charset.defaultCharset()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}