Android 如何使用谷歌地图Api获取最精确的位置
我正在尝试使用谷歌地图API获取用户的当前位置,但即使打开GPS,我也无法获得最精确的当前位置,尽管我没有得到任何错误。首先,我检查权限,然后检查GPS是否启用,然后在当前位置显示标记 我的代码Android 如何使用谷歌地图Api获取最精确的位置,android,google-maps,google-maps-android-api-2,Android,Google Maps,Google Maps Android Api 2,我正在尝试使用谷歌地图API获取用户的当前位置,但即使打开GPS,我也无法获得最精确的当前位置,尽管我没有得到任何错误。首先,我检查权限,然后检查GPS是否启用,然后在当前位置显示标记 我的代码 public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback { public static final int DEFAULT_ZOOM = 15; public stati
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
public static final int DEFAULT_ZOOM = 15;
public static final int PERMISSION_REQUEST_CODE = 9001;
private static final int PLAY_SERVICES_ERROR_CODE = 9002;
public static final String TAG = "MyTag";
private boolean mLocationPermissionGranted;
private FusedLocationProviderClient mLocationClient;
Toolbar toolbar;
String LatitudeBack;
String LongitudeBack;
Double LATITUDE,LONGITUDE;
private double Delhi_LAT = 28.630597;
private double Delhi_LONG= 77.218978;
private GoogleMap mGoogleMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
toolbar = findViewById(R.id.myToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
isServicesOk();
mLocationClient = new FusedLocationProviderClient(this);
SupportMapFragment supportMapFragment= (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_fragment);
assert supportMapFragment != null;
supportMapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
}
private void initGoogleMap() {
if(isServicesOk()){
if (isGPSEnabled()) {
if (checkLocationPermission()) {
SupportMapFragment supportMapFragment = SupportMapFragment.newInstance();
getCurrentLocation();
} else {
requestLocationPermission();
}
}
}
}
private void requestLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
}
}
}
private void gotoLocation(double lat,double lng){
LatLng latLng=new LatLng(lat,lng);
CameraUpdate cameraUpdate= CameraUpdateFactory.newLatLngZoom(latLng,DEFAULT_ZOOM);
mGoogleMap.moveCamera(cameraUpdate);
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
private boolean checkLocationPermission() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED;
}
private boolean isServicesOk() {
GoogleApiAvailability googleApi = GoogleApiAvailability.getInstance();
int result= googleApi.isGooglePlayServicesAvailable(this);
if(result == ConnectionResult.SUCCESS){
return true;
}else if(googleApi.isUserResolvableError(result)){
Dialog dialog=googleApi.getErrorDialog(this,result,PLAY_SERVICES_ERROR_CODE, task->
Toast.makeText(this, "Dialog is cancelled by User", Toast.LENGTH_SHORT).show());
dialog.show();
}else{
Toast.makeText(this, "Play services are required by this application", Toast.LENGTH_SHORT).show();
}
return false;
}
private void showMarker(double lat, double lng) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(new LatLng(lat, lng));
mGoogleMap.addMarker(markerOptions);
}
@Override
public void onBackPressed() {
super.onBackPressed();
Intent intent =new Intent(MapsActivity.this,Upload_New_Product.class);
startActivity(intent);
}
private void getCurrentLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
// TODO: Consider calling
// ActivityCompat#requestPermissions
// 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 ActivityCompat#requestPermissions for more details.
return;
}
mLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
if (task.isSuccessful())
{
Location location = task.getResult();
assert location != null;
Log.d(TAG,"Map 2 , "+String.valueOf(location.getLatitude())+ location.getLongitude());
LATITUDE =location.getLatitude();
LONGITUDE =location.getLongitude();
gotoLocation(LATITUDE,LONGITUDE);
showMarker(LATITUDE,LONGITUDE);
// LocationEditText.setText(MyLat+","+MyLong);
// geoCoder(location.getLatitude(),location.getLongitude());
}
else
{
Log.d(TAG, "getCurrentLocation: Error: " + task.getException().getMessage());
Toast.makeText(MapsActivity.this, "Can't get Location", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_map, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.CurrentLocation) {
initGoogleMap();
}
return super.onOptionsItemSelected(item);
}
private boolean isGPSEnabled() {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean providerEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (providerEnabled) {
return true;
} else {
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle("GPS Permissions")
.setMessage("GPS is required for accessing the Shop location. Please enable GPS.")
.setPositiveButton("OK", ((dialogInterface, i) -> {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, GPS_REQUEST_CODE);
}))
.setCancelable(false)
.show();
}
return false;
}
}
公共类MapsActivity扩展了AppCompatActivity在MapReadyCallback上的实现{
公共静态最终整数默认值_ZOOM=15;
公共静态最终内部许可请求代码=9001;
私有静态最终整数播放服务错误代码=9002;
公共静态最终字符串TAG=“MyTag”;
已授予私有布尔MLocationPermissions;
私有FusedLocationProviderClient mLocationClient;
工具栏;
字符串纬度回退;
字符串纵向回退;
双纬度,经度;
私人双德里拉特=28.630597;
私人双德里奥朗=77.218978;
私有谷歌地图mGoogleMap;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
toolbar=findviewbyd(R.id.myToolbar);
设置支持操作栏(工具栏);
getSupportActionBar().setTitle(“”);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
完成();
}
});
isServicesOk();
mlLocationClient=新FusedLocationProviderClient(此);
SupportMapFragment SupportMapFragment=(SupportMapFragment)getSupportFragmentManager();
断言supportMapFragment!=null;
supportMapFragment.getMapAsync(此文件);
}
@凌驾
4月1日公开作废(谷歌地图谷歌地图){
mGoogleMap=谷歌地图;
}
私有void initGoogleMap(){
if(isServicesOk()){
if(isGPSEnabled()){
if(checkLocationPermission()){
SupportMapFragment SupportMapFragment=SupportMapFragment.newInstance();
getCurrentLocation();
}否则{
requestLocationPermission();
}
}
}
}
私有void requestLocationPermission(){
if(ContextCompat.checkSelfPermission(这个,Manifest.permission.ACCESS\u FINE\u位置)
!=PackageManager.权限(已授予){
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.M){
requestPermissions(新字符串[]{Manifest.permission.ACCESS\u FINE\u LOCATION},权限\u请求\u代码);
}
}
}
私人空位(双lat、双lng){
LatLng LatLng=新LatLng(lat,lng);
CameraUpdate CameraUpdate=CameraUpdateFactory.newLatLngZoom(latLng,默认缩放);
mGoogleMap.moveCamera(cameraUpdate);
mGoogleMap.setMapType(GoogleMap.MAP\u TYPE\u NORMAL);
}
私有布尔值checkLocationPermission(){
返回ContextCompat.checkSelfPermission(这是Manifest.permission.ACCESS\u FINE\u位置)
==PackageManager.PERMISSION\u已授予;
}
私有布尔值isServicesOk(){
GoogleAppAvailability googleApi=GoogleAppAvailability.getInstance();
int result=googleApi.isGooglePlayServicesAvailable(此);
if(result==ConnectionResult.SUCCESS){
返回true;
}else if(googleApi.isUserResolvableError(result)){
Dialog Dialog=googleApi.getErrorDialog(此,结果,播放\u服务\u错误\u代码,任务->
Toast.makeText(这个“对话框被用户取消”,Toast.LENGTH_SHORT.show());
dialog.show();
}否则{
Toast.makeText(这是“此应用程序需要播放服务”,Toast.LENGTH_SHORT).show();
}
返回false;
}
专用空隙显示标记器(双lat、双lng){
MarkerOptions MarkerOptions=新MarkerOptions();
标记选项位置(新板条(板条,板条));
mGoogleMap.addMarker(markerOptions);
}
@凌驾
public void onBackPressed(){
super.onBackPressed();
Intent Intent=newintent(MapsActivity.this,Upload\u new\u Product.class);
星触觉(意向);
}
私有void getCurrentLocation(){
if(ActivityCompat.checkSelfPermission(这是Manifest.permission.ACCESS\u FINE\u位置)
!=PackageManager.PERMISSION\u已授予和&ActivityCompat.checkSelfPermission(
此,Manifest.permission.ACCESS\u\u位置)!=PackageManager.permission\u已授予)
{
考虑到呼叫
//ActivityCompat#请求权限
//在此处请求缺少的权限,然后覆盖
//public void onRequestPermissionsResult(int-requestCode,字符串[]权限,
//int[]格兰特结果)
//处理用户授予权限的情况。请参阅文档
//对于ActivityCompat,请请求权限以获取更多详细信息。
返回;
}
mLocationClient.getLastLocation().addOnCompleteListener(新的OnCompleteListener(){
@凌驾
未完成的公共void(@NonNull任务){
if(task.issusccessful())
{
位置=task.getResult();
断言位置!=null;
Log.d(标记“Map2”+String.valueOf(location.getLatitude())+location.getLatitude());
纬度=位置。getLatitude();
LONGITUDE=location.getLongitude();
地理位置(纬度、经度);
显示标记(纬度、经度);
//LocationEditText.setText(MyLat