How to read kmz file of google map in android

允我心安 提交于 2021-02-19 03:45:08

问题


I have the KMZ file and I want to parse that KMZ file so that I can read the data of that file I tried to use KmlLayer but didn't get any help from it here is my code

InputStream inputStream = new FileInputStream(path);
KmlLayer layer = new KmlLayer(mMap, inputStream, getApplicationContext());
layer.addLayerToMap();

but I got Parsing exception while I am creating the object of KmlLayer any solution.


回答1:


Because KMZ is zipped KML you should unzip .kmz file to .kml before reading data or use ZipInputStream instead of FileInputStream like in this createLayerFromKmz() method:

private KmlLayer createLayerFromKmz(String kmzFileName) {
    KmlLayer kmlLayer = null;

    InputStream inputStream;
    ZipInputStream zipInputStream;

    try {
        inputStream = new FileInputStream(kmzFileName);
        zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));
        ZipEntry zipEntry;

        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            if (!zipEntry.isDirectory()) {
                String fileName = zipEntry.getName();
                if (fileName.endsWith(".kml")) {
                    kmlLayer = new KmlLayer(mGoogleMap, zipInputStream, getApplicationContext());
                }
            }

            zipInputStream.closeEntry();
        }

        zipInputStream.close();
    }
    catch(IOException e)
    {
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    }

    return kmlLayer;
}

And you can use it e.g. this way:

@Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;

    // path to your kmz file 
    String kmzFileName = Environment.getExternalStorageDirectory() + "/KMZ/markers.kmz";
    try {
        KmlLayer kmlLayer = createFromKmz(kmzFileName);
        kmlLayer.addLayerToMap();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    }

}

NB! createLayerFromKmz() works only on "flat" KMZ structure.



来源:https://stackoverflow.com/questions/53625721/how-to-read-kmz-file-of-google-map-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!