mapbox.getStyle() returns null when changing maptype

独自空忆成欢 提交于 2020-03-26 04:06:09

问题


I have a problem with mapbox when changing the mapStyle from Style.MAPBOX_STREETS to Style.SATELLITE_STREETS (and vice versa) quickly in a row. (This happens with other styles too, those are just examples)

My code:

public void btnChangeMapType(View view) {
    this.mapboxMap.getStyle(style -> {
        String styleUri = this.mapboxMap.getStyle().getUri();
        if (this.animator != null)
            this.animator.cancel();

        if (styleUri.equalsIgnoreCase(SATELLITE_STREETS)) {
            changeMapType(Style.MAPBOX_STREETS, this.mapboxMap.getStyle());
        } else {
            changeMapType(Style.SATELLITE_STREETS, this.mapboxMap.getStyle());
        }
    });
}
private void changeMapType(String mapboxMapType, Style mapboxStyle) {
    this.mapboxMap.setStyle(mapboxMapType, style -> {
        if (this.previousLocation != null) {
            this.positionGeoJson = new GeoJsonSource(MAP_LAYER_SOURCE_ID, Feature.fromGeometry(Point.fromLngLat(this.previousLocation.getLongitude(), this.previousLocation.getLatitude())));
        } else {
            this.positionGeoJson = getNewGeoJsonPosition();
        }

        if (this.hasFocus && this.animator != null) {
            drawDrivenLine();
            this.animator.start();
        }
    });
}

And if i click on a Button that calls btnChangeMapType quickly multiple times i get an error on Line String styleUri = this.mapboxMap.getStyle().getUri(); in btnChangeMapType()

Error Log:

2020-02-20 11:31:50.828 14916-14916/at.myprojects.project E/Mbgl-MapChangeReceiver: Exception in onDidFinishLoadingStyle
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.mapbox.mapboxsdk.maps.Style.getUri()' on a null object reference

Is there a way too keep my app from crashing/having this error?


回答1:


In String styleUri = this.mapboxMap.getStyle().getUri(); , the getStyle() is not needed because you're already in the getStyle() block that returns a Style object above that line (the style -> {). So it'd be String styleUri = style.getUri(); instead. I think this will solve the NullPointerException message.

Also, it doesn't look like you're using the Style mapboxStyle parameter anywhere, so you can remove that from changeMapType().



来源:https://stackoverflow.com/questions/60320378/mapbox-getstyle-returns-null-when-changing-maptype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!