如何在应用程序中检索当前用户的位置?

时间:2019-04-23 21:01:29

标签: android google-maps

如何在应用程序中检索当前用户位置?我正在尝试,但是我尝试从错误中采用的任何代码有人对任何解决方案有任何想法?我尝试了此解决方案---> https://androidclarified.com/display-current-location-google-map-fusedlocationproviderclient/,但是代码中有错误

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    // Where the map data lives in Firebase
    public static final String MAP_PATH = "/map/";

    // A cache of map points displayed on the map
    private HashMap<String, Marker> markers = new HashMap<String, Marker>();

    public static final String TAG = MapsActivity.class.getSimpleName();
    private GoogleMap mMap;
    private LocationManager locationManager;
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference mFirebaseRef;

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

        mFirebaseDatabase = FirebaseDatabase.getInstance();
        mFirebaseRef = mFirebaseDatabase.getReference(MAP_PATH);

        mFirebaseRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                LatLng myLatLon = dataSnapshot.getValue(LatLngWrapper.class).toLatLng();

                // stash the key in the title, for recall later

                Marker myMarker = mMap.addMarker(new MarkerOptions()
                        .position(myLatLon).draggable(true).title(dataSnapshot.getKey()));

                // cache the marker locally
                markers.put(dataSnapshot.getKey(), myMarker);
            }


            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                LatLng myLatLon = dataSnapshot.getValue(LatLngWrapper.class).toLatLng();

                // Move markers on the map if changed on Firebase
                Marker changedMarker = markers.get(dataSnapshot.getKey());
                changedMarker.setPosition(myLatLon);
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
                // When markers are removed from
                Marker deadMarker = markers.get(dataSnapshot.getKey());
                deadMarker.remove();

                markers.remove(dataSnapshot.getKey());
            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                // This won't happen to our simple list, but log just in case
                Log.v(TAG, "moved !" + dataSnapshot.getValue());
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                // Ignore cancelations (but log just in case)
                Log.v(TAG, "canceled!" + databaseError.getMessage());
            }
        });
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        // Listen for marker clicks
        googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                // Remove map markers from Firebase when tapped
                String firebaseId = marker.getTitle();
                mFirebaseRef.child(firebaseId).removeValue();
                return true;
            }
        });

        // Listen for map clicks
        googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(final LatLng latLng) {
                // Taps create new markers in Firebase
                // This works because jackson can figure out LatLng
                mFirebaseRef.push().setValue(new LatLngWrapper(latLng));
            }
        });
        // Listen for marker drags
        mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
            @Override
            public void onMarkerDragStart(Marker marker) {
                // not implemented
            }

            @Override
            public void onMarkerDrag(Marker marker) {
                // not implemented
            }

            @Override
            public void onMarkerDragEnd(Marker marker) {
                mFirebaseRef.child(marker.getTitle()).setValue(new LatLngWrapper(marker.getPosition()));
            }
        });



        // Zoom to device's current location
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
                ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);


            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            String provider = locationManager.getBestProvider(new Criteria(), true);
            Location myLocation = locationManager.getLastKnownLocation(provider);
            if(myLocation != null) {
                LatLng currentLatLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
                mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLatLng));
                mMap.moveCamera(CameraUpdateFactory.zoomTo(14));
            } else {
                Log.v(TAG, "Can't figure out current location :(");
                mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(29.9648943,-90.1095941)));
                mMap.moveCamera(CameraUpdateFactory.zoomTo(14));
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

FusedLocationProviderClient API用于获取用户设备的当前位置。创建实例

private FusedLocationProviderClient mFusedLocationClient;

并将其初始化

mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

确保已在应用程序中向用户授予了位置许可,或者在运行时要求位置许可。

onRequestPermissionsResult被覆盖以处理权限请求的结果。

在下面的类中,您可以看到...在OnActivityResult中,我们获得了当前的纬度和经度。

public class MainActivity extends AppCompatActivity {

private FusedLocationProviderClient mFusedLocationClient;

private double wayLatitude = 0.0, wayLongitude = 0.0;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
private android.widget.Button btnLocation;
private TextView txtLocation;
private android.widget.Button btnContinueLocation;
private TextView txtContinueLocation;
private StringBuilder stringBuilder;

private boolean isContinue = false;
private boolean isGPS = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    this.txtContinueLocation = (TextView) findViewById(R.id.txtContinueLocation);
    this.btnContinueLocation = (Button) findViewById(R.id.btnContinueLocation);
    this.txtLocation = (TextView) findViewById(R.id.txtLocation);
    this.btnLocation = (Button) findViewById(R.id.btnLocation);

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(10 * 1000); // 10 seconds
    locationRequest.setFastestInterval(5 * 1000); // 5 seconds

    new GpsUtils(this).turnGPSOn(new GpsUtils.onGpsListener() {
        @Override
        public void gpsStatus(boolean isGPSEnable) {
            // turn on GPS
            isGPS = isGPSEnable;
        }
    });

    locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            if (locationResult == null) {
                return;
            }
            for (Location location : locationResult.getLocations()) {
                if (location != null) {
                    wayLatitude = location.getLatitude();
                    wayLongitude = location.getLongitude();
                    if (!isContinue) {
                        txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
                    } else {
                        stringBuilder.append(wayLatitude);
                        stringBuilder.append("-");
                        stringBuilder.append(wayLongitude);
                        stringBuilder.append("\n\n");
                        txtContinueLocation.setText(stringBuilder.toString());
                    }
                    if (!isContinue && mFusedLocationClient != null) {
                        mFusedLocationClient.removeLocationUpdates(locationCallback);
                    }
                }
            }
        }
    };

    btnLocation.setOnClickListener(v -> {

        if (!isGPS) {
            Toast.makeText(this, "Please turn on GPS", Toast.LENGTH_SHORT).show();
            return;
        }
        isContinue = false;
        getLocation();
    });

    btnContinueLocation.setOnClickListener(v -> {
        if (!isGPS) {
            Toast.makeText(this, "Please turn on GPS", Toast.LENGTH_SHORT).show();
            return;
        }
        isContinue = true;
        stringBuilder = new StringBuilder();
        getLocation();
    });
}

private void getLocation() {
    if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                AppConstants.LOCATION_REQUEST);

    } else {
        if (isContinue) {
            mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
        } else {
            mFusedLocationClient.getLastLocation().addOnSuccessListener(MainActivity.this, location -> {
                if (location != null) {
                    wayLatitude = location.getLatitude();
                    wayLongitude = location.getLongitude();
                    txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
                } else {
                    mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
                }
            });
        }
    }
}

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

                if (isContinue) {
                    mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
                } else {
                    mFusedLocationClient.getLastLocation().addOnSuccessListener(MainActivity.this, location -> {
                        if (location != null) {
                            wayLatitude = location.getLatitude();
                            wayLongitude = location.getLongitude();
                            txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
                        } else {
                            mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
                        }
                    });
                }
            } else {
                Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
            }
            break;
        }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == AppConstants.GPS_REQUEST) {
            isGPS = true; // flag maintain before get location
        }
    }
}

}

现在使用这些经纬度,您可以在地图上添加标记以显示当前位置。请确保在服务或后台获取用户当前位置。

另外,您可以使用:

private void getDeviceLocation() {
/*
 * Get the best and most recent location of the device, which may be null in rare
 * cases when a location is not available.
 */
try {
    if (mLocationPermissionGranted) {
        Task locationResult = mFusedLocationProviderClient.getLastLocation();
        locationResult.addOnCompleteListener(this, new OnCompleteListener() {
            @Override
            public void onComplete(@NonNull Task task) {
                if (task.isSuccessful()) {
                    // Set the map's camera position to the current location of the device.
                    mLastKnownLocation = task.getResult();
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                            new LatLng(mLastKnownLocation.getLatitude(),
                                    mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
                } else {
                    Log.d(TAG, "Current location is null. Using defaults.");
                    Log.e(TAG, "Exception: %s", task.getException());
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
                    mMap.getUiSettings().setMyLocationButtonEnabled(false);
                }
            }
        });
    }
} catch(SecurityException e)  {
    Log.e("Exception: %s", e.getMessage());
}

}

调用onMapReady(GoogleMap map)函数中的getDeviceLocation()方法。