Android導出Kml

轉載請註明出處:http://blog.csdn.net/hnyzwtf/article/details/51956714
請先閱讀:

這裏就直接給出代碼了

package com.soil.soilsampling.ui.parsekml;

import android.content.Context;
import android.content.res.Resources;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.soil.soilsampling.R;
import com.soil.soilsampling.base.BaseApplication;
import com.soil.soilsampling.model.CoordinateAlterSample;
import com.soil.soilsampling.support.utils.ToastUtil;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by GIS on 2016/5/19 0019.
 * 
 */
public class WriteKml {
    private String TAG = "WriteKml";

    /*
    * 傳入兩個參數,一是kml的名稱,第二個是座標點的list
    * */
    public void createKml(String kmlName, List<CoordinateAlterSample> alterSamples) throws Exception
    {
        Element root = DocumentHelper.createElement("kml");  //根節點是kml
        Document document = DocumentHelper.createDocument(root);
        //給根節點kml添加屬性
        root.addAttribute("xmlns", "http://www.opengis.net/kml/2.2")
                .addAttribute("xmlns:gx", "http://www.google.com/kml/ext/2.2")
                .addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
                .addAttribute("xsi:schemaLocation",
                        "http://www.opengis.net/kml/2.2 http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd http://www.google.com/kml/ext/2.2 http://code.google.com/apis/kml/schema/kml22gx.xsd");

        //給根節點kml添加子節點  Document
        Element documentElement = root.addElement("Document");

        documentElement.addElement("name").addText(kmlName); //添加name節點
        documentElement.addElement("Snippet").addText(""); //Snippet節點
        Element folderElement = documentElement.addElement("Folder");//Folder節點
        folderElement.addAttribute("id", "FeatureLayer0");
        //給Folder節點添加子節點
        folderElement.addElement("name").addText(kmlName);
        folderElement.addElement("Snippet").addText("");
        //循環添加每一個Placemark節點,有幾個座標點就有幾個Placemark節點
        for (int i = 0; i < alterSamples.size(); i++) {
            Element placeMarkElement = folderElement.addElement("Placemark");
            placeMarkElement.addAttribute("id", alterSamples.get(i).getName());
            placeMarkElement.addElement("name").addText(alterSamples.get(i).getName());
            placeMarkElement.addElement("Snippet").addText("");
            placeMarkElement.addElement("description").addCDATA(getCdataContent(alterSamples.get(i).getName(),
                    alterSamples.get(i).getName(), String.valueOf(alterSamples.get(i).getX()), String.valueOf(alterSamples.get(i).getY()),
                    alterSamples.get(i).getCostValue()));
            placeMarkElement.addElement("styleUrl").addText("#IconStyle00");
            Element pointElement = placeMarkElement.addElement("Point");
            pointElement.addElement("altitudeMode").addText("clampToGround");
            //添加每一個座標點的經緯度座標
            //pointElement.addElement("coordinates").addText("119.39986000,31.13396700000143,0");
            pointElement.addElement("coordinates").addText(String.valueOf(alterSamples.get(i).getX()) + "," +
                    String.valueOf(alterSamples.get(i).getY()) + "," + "0");
        }
        Element styleElement = documentElement.addElement("Style");//Style節點
        styleElement.addAttribute("id", "IconStyle00");
        // IconStyle
        Element iconStyleElement = styleElement.addElement("IconStyle");
        Element iconElement = iconStyleElement.addElement("Icon");
        iconElement.addElement("href").addText("layer0_symbol.png");
        iconStyleElement.addElement("scale").addText("0.250000");
        // LabelStyle
        Element labelStyleElement = styleElement.addElement("LabelStyle");
        labelStyleElement.addElement("color").addText("00000000");
        labelStyleElement.addElement("scale").addText("0.000000");
        // PolyStyle
        Element polyStyleElement = styleElement.addElement("PolyStyle");
        polyStyleElement.addElement("color").addText("ff000000");
        polyStyleElement.addElement("outline").addText("0");

        //將生成的kml寫出本地
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");//設置編碼格式
        //將doc.kml寫入到/data/data/<package name>/files目錄
        FileOutputStream outputStream = BaseApplication.getContext().openFileOutput("doc.kml", Context.MODE_PRIVATE);
        XMLWriter xmlWriter = new XMLWriter(outputStream,format);

        xmlWriter.write(document);

        xmlWriter.close();
        //開始對文件進行壓縮,一個kml文件其實是一個壓縮文件,裏面包含一個kml文件和一個png圖標

        String docKmlPath = BaseApplication.getContext().getFilesDir().getAbsolutePath() + "//doc.kml";

        zipWriteKml(docKmlPath, kmlName);
        ToastUtil.show(BaseApplication.getContext(), "導出kml成功");

    }
    /*
    * 將生成的kml文件和drawable下的某個png圖標進行壓縮,生成最終的kml文件,並保存在/data/data/<package name>/files目錄
    * */
    public void zipWriteKml(String docKmlPath, String kmlName) throws IOException
    {
        // 最終生成的kml文件
        FileOutputStream fileOutput = BaseApplication.getContext().openFileOutput(kmlName + ".kmz", Context.MODE_PRIVATE);

        OutputStream os = new BufferedOutputStream( fileOutput);
        ZipOutputStream zos = new ZipOutputStream(os);
        byte[] buf = new byte[8192];
        int len;

        //壓縮data/data/package name/files目錄下的doc.kml
        File file = new File(docKmlPath);
        if ( !file.isFile() )
            Log.d(TAG, "doc.kml is nonexist");
        ZipEntry ze = new ZipEntry( file.getName() );
        zos.putNextEntry( ze );
        BufferedInputStream bis = new BufferedInputStream( new FileInputStream( file ) );
        while ( ( len = bis.read( buf ) ) > 0 ) {
            zos.write( buf, 0, len );

        }
        zos.closeEntry();


        // 壓縮drawable目錄下的圖片
        Resources r = BaseApplication.getContext().getResources();
        Bitmap bitmap = BitmapFactory.decodeResource(r, R.drawable.layer0_symbol);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        InputStream input = new ByteArrayInputStream(baos.toByteArray());
        int temp = 0;
        ZipEntry entry2 = new ZipEntry("layer0_symbol.png");
        zos.putNextEntry(entry2);
        while ((temp = input.read()) != -1)
        {
            zos.write(temp);
        }
        input.close();
        zos.closeEntry();

       /* for (int i=0;i < files.length;i++) {
            File file = new File(files[i]);
            if ( !file.isFile() )
                continue;
            ZipEntry ze = new ZipEntry( file.getName() );
            zos.putNextEntry( ze );
            BufferedInputStream bis = new BufferedInputStream( new FileInputStream( file ) );
            while ( ( len = bis.read( buf ) ) > 0 ) {
                zos.write( buf, 0, len );
                Log.d(TAG, "we are zipping "+ file.getName());
            }
            zos.closeEntry();
        }*/


        zos.closeEntry();
        zos.close();


    }
    /*
    * 生成kml的html備註,在description節點下
    * */
    public String getCdataContent(String id, String placeMarkName, String x, String y, String costValue)
    {
        StringBuffer buffer = new StringBuffer();
        buffer.append("<html xmlns:fo=\"http://www.w3.org/1999/XSL/Format\" xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\">");
        buffer.append("<head>");
        buffer.append("<META http-equiv=\"Content-Type\" content=\"text/html\">");
        buffer.append("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
        buffer.append("</head>");
        buffer.append("<body style=\"margin:0px 0px 0px 0px;overflow:auto;background:#FFFFFF;\">");
        buffer.append("<table style=\"font-family:Arial,Verdana,Times;font-size:12px;text-align:left;width:100%;border-collapse:collapse;padding:3px 3px 3px 3px\">");
        buffer.append("<tr style=\"text-align:center;font-weight:bold;background:#9CBCE2\">");
        buffer.append("<td>").append(placeMarkName).append("</td>");
        buffer.append("</tr>");
        buffer.append("<tr>");
        buffer.append("<td>");
        buffer.append("<table style=\"font-family:Arial,Verdana,Times;font-size:12px;text-align:left;width:100%;border-spacing:0px; padding:3px 3px 3px 3px\">");
        buffer.append("<tr bgcolor=\"#D4E4F3\">");
        buffer.append("<td>ID</td>");
        buffer.append("<td>").append(id).append("</td>");
        buffer.append("</tr>");
        buffer.append("<tr>");
        buffer.append("<td>name</td>");
        buffer.append("<td>").append(placeMarkName).append("</td>");
        buffer.append("</tr>");
        buffer.append("<tr bgcolor=\"#D4E4F3\">");
        buffer.append("<td>X</td>");
        buffer.append("<td>").append(x).append("</td>");
        buffer.append("</tr>");
        buffer.append("<tr>");
        buffer.append("<td>Y</td>");
        buffer.append("<td>").append(y).append("</td>");
        buffer.append("</tr>");
        buffer.append("<tr bgcolor=\"#D4E4F3\">");
        buffer.append("<td>CostValue</td>");
        buffer.append("<td>").append(costValue).append("</td>");
        buffer.append("</tr>");
        buffer.append("</table>");
        buffer.append("</td>");
        buffer.append("</tr>");
        buffer.append("</table>");
        buffer.append("</body>");
        buffer.append("</html>");

        String cDataContent = buffer.toString();
        return cDataContent;
    }

}

CoordinateAlterSample類如下

/*
 * 服務器返回的樣點,每一個樣點包括一個name,x,y,costValue
 * */
public class CoordinateAlterSample implements Serializable {
    private double x;
    private double y;
    private String name;
    private String costValue;

    public String getCostValue() {
        return costValue;
    }

    public void setCostValue(String costValue) {
        this.costValue = costValue;
    }

    public double getX() {
        return x;
    }
    public void setX(double x) {
        this.x = x;
    }
    public double getY() {
        return y;
    }
    public void setY(double y) {
        this.y = y;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章