如何将 KML 文件添加到 mapfragment?

How to add KML file onto a mapfragment?

所以我试图在 Google 地图片段上叠加 KML 文件但没有成功(不幸的是文档没有帮助我 https://developers.google.com/maps/documentation/android-sdk/utility/kml)并且我尝试了其他答案的解决方案但没有成功。 .

我的代码如下(根据文档实现,至少我认为..我是 Android dev 的新手,所以我可能是错的):

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

您在 mMap 尚未启动时调用 addLayerToMap...您应该在 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();
    }
}