8

私は公式の文書に従っているため、現在の位置情報を定期的に(2分ごとに)取得したいと思いますが、このコードを書いていますが、私はrequestLocationUpdatesに渡しているなLocationRequestオブジェクト()に指定され、ここではコードです:FusedLocationProviderClientを使用してGoogleMapで現在地を取得する方法

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, 
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{ 

private FusedLocationProviderClient FusedLocationClient; 
private GoogleApiClient mGoogleApiClient; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_maps); 
    if (mGoogleApiClient == null) { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
    } 

SupportMapFragment map = 
    getSupportFragmentManager().findFragmentById(R.id.map)); 

    map.getMapAsync(this); 

    FusedLocationClient LocationServices.getFusedLocationProviderClient(this); 
} 


@Override 
public void onConnected(Bundle bundle) { 
    FusedLocationClient.getLastLocation() 
      .addOnSuccessListener(this, new OnSuccessListener<Location>() { 
       @Override 
       public void onSuccess(Location location) { 

        if (location != null) { 
         Log.i("MainActivity ", "" + location.getLongitude()) 
        } 
       } 
      }); 
FusedLocationClient = LocationServices.getFusedLocationProviderClient(this); 
FusedLocationClient.requestLocationUpdates(requestLocation(), 
new LocationCallback(){ 
     @Override 
     public void onLocationResult(LocationResult locationResult) { 
      for (Location location : locationResult.getLocations()) { 
       Log.i("MainActivity ", "" + location.getLongitude()); 
       //not getting current location updates every 2 minutes 
      } 
     }; 

    },null); 

} 

@Override 
public void onConnectionSuspended(int i) {} 

@Override 
public void onConnectionFailed(ConnectionResult connectionResult) {} 

答えて

-1
private LocationRequest locationRequest; 

    public class MapsActivity extends FragmentActivity implements LocationListener{ 

    locationRequest = new LocationRequest(); 
    locationRequest.setInterval(60 * 1000); 
    locationRequest.setFastestInterval(15 * 1000); 
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 


@Override 
public void onLocationChanged(Location location) { 

    latitude = location.getLatitude(); 
    longitude = location.getLongitude(); 

} 

場所変更リスナーを実装し、あなたが変更OnLocationではを上書きすることができるようになりますが...

16

これは、私のに似て、最近導入されたFusedLocationProviderClientクラスを使用するように更新されました。 Googleマップと連動してFusedLocationProviderClientを使用するためには

  1. 待ち

  2. 要求を必要に応じて、Googleマップは

  3. 準備、実行時に要求場所許可されるまで許可が与えられると、位置の更新が行われます

  4. ユーザの位置に一度マップが

まず得られ、古いバージョンではFusedLocationProviderClientクラスを持っていないとして、サービスはGoogle Playのバージョン11を使用していることを確認してください:ここで

dependencies { 
    compile 'com.google.android.gms:play-services-maps:11.8.0' 
    compile 'com.google.android.gms:play-services-location:11.8.0' 
    //........ 
} 

がいっぱいですActivityクラス:

public class MapsActivity extends AppCompatActivity 
     implements OnMapReadyCallback { 

    GoogleMap mGoogleMap; 
    SupportMapFragment mapFrag; 
    LocationRequest mLocationRequest; 
    Location mLastLocation; 
    Marker mCurrLocationMarker; 
    FusedLocationProviderClient mFusedLocationClient; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     getSupportActionBar().setTitle("Map Location Activity"); 

     mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); 

     mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
     mapFrag.getMapAsync(this); 
    } 

    @Override 
    public void onPause() { 
     super.onPause(); 

     //stop location updates when Activity is no longer active 
     if (mFusedLocationClient != null) { 
      mFusedLocationClient.removeLocationUpdates(mLocationCallback); 
     } 
    } 

    @Override 
    public void onMapReady(GoogleMap googleMap) 
    { 
     mGoogleMap=googleMap; 
     mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); 

     mLocationRequest = new LocationRequest(); 
     mLocationRequest.setInterval(120000); // two minute interval 
     mLocationRequest.setFastestInterval(120000); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 

     if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      if (ContextCompat.checkSelfPermission(this, 
        Manifest.permission.ACCESS_FINE_LOCATION) 
        == PackageManager.PERMISSION_GRANTED) { 
       //Location Permission already granted 
       mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper()); 
       mGoogleMap.setMyLocationEnabled(true); 
      } else { 
       //Request Location Permission 
       checkLocationPermission(); 
      } 
     } 
     else { 
      mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper()); 
      mGoogleMap.setMyLocationEnabled(true); 
     } 
    } 

    LocationCallback mLocationCallback = new LocationCallback(){ 
     @Override 
     public void onLocationResult(LocationResult locationResult) { 
      for (Location location : locationResult.getLocations()) { 
       Log.i("MapsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude()); 
       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.newLatLngZoom(latLng, 11)); 
      } 
     }; 

    }; 

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; 
    private void checkLocationPermission() { 
     if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) 
       != PackageManager.PERMISSION_GRANTED) { 

      // Should we show an explanation? 
      if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
        Manifest.permission.ACCESS_FINE_LOCATION)) { 

       // Show an explanation to the user *asynchronously* -- don't block 
       // this thread waiting for the user's response! After the user 
       // sees the explanation, try again to request the permission. 
       new AlertDialog.Builder(this) 
         .setTitle("Location Permission Needed") 
         .setMessage("This app needs the Location permission, please accept to use location functionality") 
         .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
          @Override 
          public void onClick(DialogInterface dialogInterface, int i) { 
           //Prompt the user once explanation has been shown 
           ActivityCompat.requestPermissions(MapsActivity.this, 
             new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
             MY_PERMISSIONS_REQUEST_LOCATION); 
          } 
         }) 
         .create() 
         .show(); 


      } else { 
       // No explanation needed, we can request the permission. 
       ActivityCompat.requestPermissions(this, 
         new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
         MY_PERMISSIONS_REQUEST_LOCATION); 
      } 
     } 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, 
              String permissions[], int[] grantResults) { 
     switch (requestCode) { 
      case MY_PERMISSIONS_REQUEST_LOCATION: { 
       // If request is cancelled, the result arrays are empty. 
       if (grantResults.length > 0 
         && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

        // permission was granted, yay! Do the 
        // location-related task you need to do. 
        if (ContextCompat.checkSelfPermission(this, 
          Manifest.permission.ACCESS_FINE_LOCATION) 
          == PackageManager.PERMISSION_GRANTED) { 

         mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper()); 
         mGoogleMap.setMyLocationEnabled(true); 
        } 

       } else { 

        // permission denied, boo! Disable the 
        // functionality that depends on this permission. 
        Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show(); 
       } 
       return; 
      } 

      // other 'case' lines to check for other 
      // permissions this app might request 
     } 

    } 

} 

ユーザーが場所の許可を受け入れるように求められます。

enter image description here

場所は、アプリの起動、および2分ごとに更新されます。

enter image description here

+0

おかげで、このコードを入れて、私たちは移動してリアルタイム – blackHawk

+0

に現在位置更新を取得しているように、我々は、移動するごとに10段階もわずかに何があるについて最初のように座標を変更する25.3767231以降25.3756256デバイスの場所が変更されていなくても2回の更新が遅れても遅延が増えています – blackHawk

+0

@blackHawk最初のコメントでは、より短い時間間隔を設定し、 'setSmallestDisplacement( ) 'メソッドを使用します:https://developers.google.com/android/reference/com/google/android/gms/location/LocationRequesthtml#setSmallestDisplacement(float) –

2
mLocationCallback = new LocationCallback() { 
     @Override 
     public void onLocationResult(LocationResult locationResult) { 
      super.onLocationResult(locationResult); 
      currentLocation = locationResult.getLastLocation(); 

     } 
    }; 

この作品は私のために。

0

このライブラリで試してみてください。https://github.com/mrmans0n/smart-location-libこれは、融合ロケーションプロバイダを使用します。我々は、デバイスの現在位置を取得したい場合

あなただけ

SmartLocation.with(context).location(new LocationBasedOnActivityProvider(callback)) 
    .start(new OnLocationUpdatedListener() { ... }); 
関連する問題