Load local KML file using ArcGIS api for android

992 views Asked by At

I am using ArcGIS api for android and I want to load a local KML file.I use the following code sample

String url = Environment.getExternalStorageDirectory() + "\\Android\\data\\com.tehranuni.hazard.hazard\\us_states.kml";

    SpatialReference sr = SpatialReference.create(102100);
    System.out.println("kmlurl: " + url);

    KMLLayer kmlLayer = new KMLLayer(url, sr); 
    mMapView.addLayer(kmlLayer);

This code gives me following error

KML layer fails to initializecom.esri.core.io.EsriServiceException: File not found. Wrong url or out of memory.

But when I use an online version of the same KML it works fine.I mean when I change url to a url it works great

I know the error means that the kml does not exist in the location but I have copied it already Can you help me find a good solution to it?thanks you so much

1

There are 1 answers

2
Gary Sheppard On BEST ANSWER

Make these changes:

  • Use KmlLayer instead of KMLLayer. KMLLayer supports only KML URLs on the public Internet, and it is deprecated. It will not work for a local KML file. KmlLayer supports both local KML files and KML URLs.
  • Be sure you've given your app permission to access local files:

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    or

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

  • Use forward slashes, not backslashes. Backslashes are not used as path separators except on Windows.

  • Use the File class to construct your file path, just in case getExternalStorageDirectory() includes a slash at the end on some devices.

Here's your new code:

File kmlFile = new File(
    Environment.getExternalStorageDirectory(),
    "Android/data/com.tehranuni.hazard.hazard/us_states.kml");
//Here you could check kmlFile.exists() to see if the app can actually see the file.
//If it's false, maybe you didn't grant permissions, or maybe the file path is wrong.

KmlLayer kmlLayer = new KmlLayer(kmlFile.getAbsolutePath()); 
mMapView.addLayer(kmlLayer);