简体   繁体   English

LatLng GPS位置的NullPointerException

[英]NullPointerException for LatLng GPS location

I am using Google Maps to obtain my current location and display a red marker on my location. 我正在使用Google地图获取我的当前位置,并在我的位置上显示一个红色标记。 So far it only the mMap.setMyLocation(true); 到目前为止,只有mMap.setMyLocation(true); works for my location. 适用于我的位置。 I am getting NullPointerException for the object userLocation towards the end of my code and the output to the console for userLocation is null too. 我在代码结尾处获取对象userLocation NullPointerException,并且userLocation到控制台的输出userLocation为null。

How do I set the userLocation as soon as I load the map ? 加载地图后,如何设置userLocation?

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    LocationManager locationManager;

    LocationListener locationListener;
    LatLng userLocation;
    private FusedLocationProviderClient mFusedLocationClient;
    public  float DEFAULT_ZOOM = 15f;
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1) {

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    {

                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

                    }

                }

            }

        }

    }

    @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;
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

                userLocation = new LatLng(location.getLatitude(), location.getLongitude());

                mMap.clear();
                mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location"));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
                System.out.println("the latitude onLocationChanged is "+ userLocation.latitude);


            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

            }
        };



        if (Build.VERSION.SDK_INT < 23) {
        try {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
        }
        catch (SecurityException e){
            e.printStackTrace();
        }
        } else {

            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);

            } else {

                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, locationListener);
              //  LatLng latLng = new LatLng(40.741895,-73.989308);
                mMap.setMyLocationEnabled(true);
            //outputs the latitude is null 
                System.out.println("the latitude is "+userLocation);
              mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location"));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));


            }


        }


    }


}

You can't. 你不能 Getting a location takes time. 获取位置需要时间。 It won't be available until your callback is called, which means you can't load it until then. 在调用回调之前,它将不可用,这意味着您无法在那时加载它。 You could try calling getLastKnownLocation, but it will return null the majority of the time as well. 您可以尝试调用getLastKnownLocation,但大多数情况下它也会返回null。 The best solution is not to rely on it until the callback is made. 最好的解决方案是在进行回调之前不要依赖它。

on method, OnMapReady use this code 在方法上,OnMapReady使用此代码

if (!mMap.isMyLocationEnabled())
        mMap.setMyLocationEnabled(true);

    Location userLocation = getLocation();

and use this method to get the last location if you want it 并使用此方法来获取最后的位置

public Location getLocation() {
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (myLocation == null) {
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            String provider = lm.getBestProvider(criteria, true);
            myLocation = lm.getLastKnownLocation(provider);
        }
        return myLocation;
    }

Note : GPS_PROVIDER does not work indoors, so you should try it outdoor. 注意GPS_PROVIDER不能在室内使用,因此您应该在室外使用。

maybe you want to start the callback just if the last location before more than one minute. 也许您只是想在最后一分钟之前才启动回调。 use this code 使用此代码

if (System.currentTimeMillis()-myLocation.getTime()>60000){
 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, locationListener);

       };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM