简体   繁体   中英

How to parse KML file in Android

我想知道一种解析KML文件并将其数据存储在对象中的简单方法,以便我可以立即访问其数据,这是我的kml文件

You can use KmlContainer from Google Maps KML Importing Utility to access any property in a container:

...
KmlLayer layer = new KmlLayer(getMap(), kmlInputStream, getApplicationContext());

Iterable containers = layer.getContainers();
for (KmlContainer container : containers ) {
    if (container.hasProperty("property_name")) {
        // process property
        Log.d(TAG, "" + container.getProperty("property_name"));
    }
}
...

For exactly yours kml file for standard geometry you can use something like this:

@Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;
    mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(17.425868, 78.459761), 16));

    // change next line for your kml source
    InputStream kmlInputStream = getResources().openRawResource(R.raw.data);
    try {
        KmlLayer kmlLayer = new KmlLayer(mGoogleMap, kmlInputStream, getApplicationContext());
        kmlLayer.addLayerToMap();

        ArrayList<LatLng> pathPoints = new ArrayList();

        if (kmlLayer != null && kmlLayer.getContainers() != null) {
            for (KmlContainer container : kmlLayer.getContainers()) {
                if (container.hasPlacemarks()) {
                    for (KmlPlacemark placemark : container.getPlacemarks()) {
                        Geometry geometry = placemark.getGeometry();
                        if (geometry.getGeometryType().equals("Point")) {
                            KmlPoint point = (KmlPoint) placemark.getGeometry();
                            LatLng latLng = new LatLng(point.getGeometryObject().latitude, point.getGeometryObject().longitude);
                            pathPoints.add(latLng);
                        } else if (geometry.getGeometryType().equals("LineString")) {
                            KmlLineString kmlLineString = (KmlLineString) geometry;
                            ArrayList<LatLng> coords = kmlLineString.getGeometryObject();
                            for (LatLng latLng : coords) {
                                pathPoints.add(latLng);
                            }
                        }
                    }
                } 
            }

            for (LatLng latLng : pathPoints) {
                mGoogleMap.addMarker(new MarkerOptions().position(latLng));
            }
        } 

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

and get something like that:

KML路径

but for <ExtendedData> you should use external library with KML parsing support like GeoTools or parse your KML file as XML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM