-1

ive пыталась центрировать карту на местоположении пользователей, но она продолжает говорить, что переменная latLng имеет значение null. Я читал, что это происходит, потому что я использую getLastKnownLocation, но я не могу найти другой способ сделать это (я новичок в программировании). Я работаю с google api на Jellybean. Вот код, который я использую.Пытаясь сосредоточить мою карту на местоположении пользователя (говорит, что это пустое место)

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

ответ

0

попробовать этот

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

Implenment 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); 
    } 
} 
0

Проверить разрешение в «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 провайдера и оператора сети. Если мы получим нулевое местоположение через провайдера GPS, измените его на 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(); 
}