如何打开KML文件(从资产文件夹)

时间:2019-05-27 10:30:45

标签: google-maps android-intent kml

我在Assets文件夹中有一个KML文件。我想将其打开到Google Earth或Google Map中。但是这些都不起作用。 这是我尝试过的:

对于Google Map

private GoogleMap map;
KmlLayer layer;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_locations);


    try {
        layer = new KmlLayer(map,getAssets().open("locations.kml"),context);
        layer.addLayerToMap();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

对于Google Earth

    File KML = null;
    try {
        KML = new File(String.valueOf(getAssets().open("locations.kml")));
    } catch (IOException e) {
        e.printStackTrace();
    }
    Intent i = 
getPackageManager().getLaunchIntentForPackage("com.google.earth");
    i.setDataAndType(Uri.fromFile(KML), "xml");
    startActivity(i);

1 个答案:

答案 0 :(得分:0)

  1. 使用Google Map Activity创建一个新项目。
  2. 现在在 onMapReady()方法中使用 retrieveFileFromResource()

    private void retrieveFileFromResource() {
            try {
                KmlLayer kmlLayer = new KmlLayer(mMap, R.raw.kml, getApplicationContext());
                kmlLayer.addLayerToMap();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            }
        }
    

    3。完整代码

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    
    private GoogleMap mMap;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    
    
    }
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
    
        retrieveFileFromResource();
    }
    
    private void retrieveFileFromResource() {
        try {
            KmlLayer kmlLayer = new KmlLayer(mMap, R.raw.kml, getApplicationContext());
            kmlLayer.addLayerToMap();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }
    }
    }