Home > front end >  How to add KML file onto a mapfragment?
How to add KML file onto a mapfragment?

Time:05-19

So I'm trying to overlay KML file on Google Maps fragment with no success (documentation didn't help me unfortunately https://developers.google.com/maps/documentation/android-sdk/utility/kml) and I tried solutions from other answers with no luck..

Code I have is following (implemented according to documentation, atleast i think.. I'm new to Android dev so i might be wrong):

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
private ActivityMapsBinding binding;
KmlLayer layer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    binding = ActivityMapsBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());

    try {
        KmlLayer layer = new KmlLayer(mMap, R.raw.mykmlfile, getApplicationContext());
        layer.addLayerToMap();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }




    // 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;
}
}

CodePudding user response:

you are calling addLayerToMap when mMap isn't initiated yet... you should call this in onMapReady

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    try {
        KmlLayer layer = new KmlLayer(googleMap, R.raw.mykmlfile, getApplicationContext());
        layer.addLayerToMap();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
  • Related