如何在OnSenSorchanged中使用googlemap.addmarker



当调用onSensorChanged方法时,如何旋转标记?我尝试了此代码,但我得到了一个NullPoInterException。我将mMap声明为全局变量,并将其加载到OnmapReady中。我想在我的onSensorChanged方法中使用它。我该如何解决?

我有一个错误:

java.lang.nullpointerexception:尝试调用虚拟方法 'com.google.android.gms.maps.model.marker com.google.android.gms.maps.googlemap.addmarker(com.google.android.gms.maps.maps.model.markeroptions)'' 在null对象引用

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.getUiSettings().setZoomControlsEnabled(true);
        latLng_dest = getIntent().getExtras().getParcelable("latLng_dest");
        Log.d("LatLng_dest : ", latLng_dest.toString());
        if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST);
            return;
        }
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(false);
        // Call our direction function
        getDeviceLocation();
    }
    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor == mRotationSensor) {
            if (event.values.length > 4) {
                float[] truncatedRotationVector = new float[4];
                System.arraycopy(event.values, 0, truncatedRotationVector, 0, 4);
                updateSensor(truncatedRotationVector);
            } else {
                updateSensor(event.values);
            }
        }
    }
    private void updateSensor(float[] vectors) {
        float[] rotationMatrix = new float[9];
        SensorManager.getRotationMatrixFromVector(rotationMatrix, vectors);
        int worldAxisX = SensorManager.AXIS_X;
        int worldAxisZ = SensorManager.AXIS_Z;
        float[] adjustedRotationMatrix = new float[9];
        SensorManager.remapCoordinateSystem(rotationMatrix, worldAxisX, worldAxisZ, adjustedRotationMatrix);
        float[] orientation = new float[3];
        SensorManager.getOrientation(adjustedRotationMatrix, orientation);
        azimuth = orientation[0]* FROM_RADS_TO_DEGS;
        float pitch = orientation[1] * FROM_RADS_TO_DEGS;
        float roll = orientation[2] * FROM_RADS_TO_DEGS;
        Log.d("", "updateSensor: Pitch "+pitch);
        Log.d("", "updateSensor: Roll "+roll);
        Log.d("", " "+mMap);
        markerOptions = new MarkerOptions().icon(bitmapDescriptorFromVector(MapsActivity.this, R.drawable.ic_navigation_black_24dp));
        ((TextView)findViewById(R.id.svtv2)).setText("Azimuth: "+azimuth+"n"+"Pitch: "+pitch+"n"+"Roll: "+roll);
        mMap.addMarker(markerOptions.rotation(azimuth));
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        initMap();
        //markerOptions = new MarkerOptions().icon(bitmapDescriptorFromVector(MapsActivity.this, R.drawable.ic_navigation_black_24dp));
        Button button = findViewById(R.id.but_dir);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView = findViewById(R.id.svtv);
                textView.setText(instruction);
            }
        });

        /*new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
            }
        },0,1);*/
        //Aquire a reference to the system Location Manager
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED) {
            return;
        }

        final TextView live_inst = findViewById(R.id.svtv2);
        // Define a listener that responds to location updates
        LocationListener locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // Called when a new location is found by the network location provider.
                //makeUseOfNewLocation(location);
                updateDeviceLocation(location);
            }
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }
            @Override
            public void onProviderEnabled(String provider) {
            }
            @Override
            public void onProviderDisabled(String provider) {
            }
        };
        // Register the listener with the Location Manager to receive location updates
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 0, locationListener);
        try {
            mSensorManager = (SensorManager) getSystemService(MapsActivity.SENSOR_SERVICE);
            mRotationSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
            mSensorManager.registerListener(this, mRotationSensor, SENSOR_DELAY);
        } catch (Exception e) {
            Toast.makeText(this, "Hardware compatibility issue", Toast.LENGTH_LONG).show();
        }
    }

通常,一旦您启动应用程序屏幕,OnSenorchanged就会触发。

以这种方式,在更改了传感器值之后,您正在尝试旋转地图对象上的标记,这将是无效的,因为它是一个异步调用。

在调用" rotatemarker'方法之前,请放一个无效检查。

示例:

If (mMap != null) {
  // do rotate Map marker
}

注意:传感器值即使在很小的变化中也会改变。仅用于增强性能,用 或-5。

校准传感器值

希望此信息有帮助!

我解决了它。解决方案是避免在摘要准备之前调用mmap.addmarker。我首先使用它来避免在MMAP上进行null,并且还添加了标记位置上无效的标记错误。

if (save) {
        temp_marker.remove();
        temp_marker = mMap.addMarker(markerOptions.rotation(azimuth));
    }

在我的更新器中,在添加标记中的第一个位置后,在我的getDeviceLocation中添加了它:

save = true;

保存定义为全局并初始化为false。

if (mMap != null)

不起作用。这就是为什么我感到困惑。我没有注意到这是同一语法中的双nullpointerexception。

最新更新