【问题标题】:NullPointerException for LatLng GPS locationLatLng GPS 位置的 NullPointerException
【发布时间】:2019-01-31 06:56:35
【问题描述】:

我正在使用 Google 地图获取我的当前位置并在我的位置上显示一个红色标记。到目前为止,只有mMap.setMyLocation(true); 适用于我的位置。我在代码末尾收到对象userLocation 的 NullPointerException,userLocation 的控制台输出也为空。

如何在加载地图后立即设置 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));


            }


        }


    }


}

【问题讨论】:

    标签: java android google-maps nullpointerexception android-gps


    【解决方案1】:

    你不能。获取位置需要时间。在调用您的回调之前它不可用,这意味着在此之前您无法加载它。您可以尝试调用 getLastKnownLocation,但大多数情况下它也会返回 null。最好的解决方案是在进行回调之前不要依赖它。

    【讨论】:

    • 那么我如何获得回调呢?函数名称是什么?
    • @Hazed2.0 你不调用它,你等到系统调用它
    • 它是你传入的位置监听器的onLocationChanged函数。你在那儿写了一个,只要你准备好你的权限就可以了。
    • 那么我调用 mMap.addMarker() 等的脚本末尾的代码就没有必要了吗?
    • 此外,回调不起作用,因为似乎确实调用了 onLocationChanged 函数,我已经记录了它并且根本没有输出任何内容。这很奇怪,因为 mMap.setMyLocationEnabled(true) 工作正常并用蓝点显示我的位置。
    【解决方案2】:

    on 方法,OnMapReady 使用这段代码

    if (!mMap.isMyLocationEnabled())
            mMap.setMyLocationEnabled(true);
    
        Location userLocation = getLocation();
    

    如果需要,可以使用此方法获取最后一个位置

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

    注意GPS_PROVIDER 不能在室内使用,所以你应该在室外尝试。

    也许你想在最后一个位置超过一分钟之前开始回调。使用此代码

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多