【问题标题】:Trying to center my map on user location (Says location is null)试图将我的地图集中在用户位置上(说位置为空)
【发布时间】:2016-01-13 18:21:55
【问题描述】:

我一直试图将地图放在用户位置的中心,但它一直说 latLng 变量为空。我已经读到发生这种情况是因为我正在使用 getLastKnownLocation,但我找不到任何其他方法来做到这一点(我是编程新手)。我正在使用 Jellybean 上的 google api。这是我正在使用的代码。

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);

 LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
      Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria,true);
        Location myLocation = locationManager.getLastKnownLocation(provider);

        //Latitude y longitud
        double latitude = myLocation.getLatitude();
        double longitude = myLocation.getLongitude();
        LatLng latLng = new LatLng(latitude,longitude);
        //Mover el mapa a la posicion actual del usuario
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        //Zoom
        mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
        mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!").snippet("Consider yourself located"));






      } else {
            // Show rationale and request permission.
        }

【问题讨论】:

    标签: android google-maps google-api location android-4.3-jelly-bean


    【解决方案1】:

    试试这个

    protected synchronized void buildGoogleApiClient() {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
            mGoogleApiClient.connect();
        }
    
      //Initialize Google Play Services
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (bPermissionGranted) {
                    buildGoogleApiClient();
                    if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    public void requestPermissions(@NonNull String[] permissions, int requestCode)
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for Activity#requestPermissions for more details.
                        return;
                    }
                    mGoogleMap.setMyLocationEnabled(true);
                }
            } else {
                buildGoogleApiClient();
                mGoogleMap.setMyLocationEnabled(true);
            }
    

    实现接口GoogleApiClient.ConnectionCallbacks并覆盖方法 onConnected 和 onConnectionSuspended 在 onConnected 中

     mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(1000);
            mLocationRequest.setFastestInterval(1000);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    public void requestPermissions(@NonNull String[] permissions, int requestCode)
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for Activity#requestPermissions for more details.
                    return;
                }
            }
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    

    在其中实现LocationListener接口和覆盖方法

    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }
    
        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
    
        //move map camera
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));
    
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }
    

    【讨论】:

      【解决方案2】:

      检查“AndroidManifest.xml”中的权限

      <user-permission android:name="android.permission.ACCESS_FINE_LOCATION />
      <user-permission android:name="android.permission.ACCESS_COARSE_LOCATION />
      <user-permission android:name="android.permission.INTERNET />
      

      主要我们可以通过 GPS Provider 和 NETWORK Provider 获取位置。 如果我们通过 GPS 提供商获得空位置,则将 Provider 更改为 NETWORK。

      LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
      String provideGps = locationManager.GPS_PROVIDER;
      String provideNetwork = locationManager.NETWORK_PROVIDER;
      
      Location location = locationManager.getLastKnownLocation(providerGps);
      
      If (location == null) {
          location = locationManager.getLastKnownLocation(providerNetwork);
          location.getLatitude();
          location.getLongitude();
      } else {
          location.getLatitude();
          location.getLongitude();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-18
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-21
        • 2019-10-26
        相关资源
        最近更新 更多