无法使用 google 地图获取当前位置
Unable to get current location with google map
我在一个项目中使用 google 地图,我想在其中获取当前位置但无法正常工作,
MyActivity.java代码:
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (enabled) {
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
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;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
return;
}
}
但它每次都 returns 为 null,首先我想知道问题是什么以及获取当前位置的最佳方法是什么?
AndroidManifest.xml代码
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
使用这个 Google 地图 API v2 方法
private void getCurrentLocation() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
mMap.setMyLocationEnabled(true);
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
}
});
}
}
}
在这里您可以找到关于如何使用 Location Data
来自 Google Maps
-> https://developers.google.com/maps/documentation/android-sdk/location
的文档
在这里你可以找到如何获取最后一个已知位置(如果你的设备是第一次使用它可以是 null
现在它还没有被保存)-> https://developer.android.com/training/location/retrieve-current#java
private static final int REQUEST_LOCATION = 1;
private LocationManager locationManager;
//...
// In your onCreate
locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
//...
void getLocation() {
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) {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
} else {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
double lati = location.getLatitude();
double longi = location.getLongitude();
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
//You can retrieve any address you want like this...
List<Address> addresses = geocoder.getFromLocation(lati, longi, 1);
String address = addresses.get(0).getAdminArea() + ", " + addresses.get(0)
.getCountryName();
location_text.setText(address);
System.out.println(address);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//Create the location request and set the parameters
//To store parameters for requests to the fused location provider, create a LocationRequest.
// The parameters determine the level of accuracy for location requests.
//Create the location request and set the parameters
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_LOCATION:
getLocation();
break;
}
}
嗯,这就是我在我的应用程序中的做法:
首先声明:
private Location mylocation;
private GoogleApiClient googleApiClient;
private final static int REQUEST_CHECK_SETTINGS_GPS = 0x1;
private final static int REQUEST_ID_MULTIPLE_PERMISSIONS = 0x2;
public double latitude, longitude;
然后,在你的代码中写:
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
最后,
if (googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(3000);
locationRequest.setFastestInterval(3000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
LocationServices.FusedLocationApi
.requestLocationUpdates(googleApiClient, locationRequest, this);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi
.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
mylocation = LocationServices.FusedLocationApi
.getLastLocation(googleApiClient);
latitude = mylocation.getLatitude();
longitude = mylocation.getlongitude();
}
break;
}
}
}
试试这个,希望它有效。
}
我在一个项目中使用 google 地图,我想在其中获取当前位置但无法正常工作,
MyActivity.java代码:
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (enabled) {
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
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;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
return;
}
}
但它每次都 returns 为 null,首先我想知道问题是什么以及获取当前位置的最佳方法是什么?
AndroidManifest.xml代码
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
使用这个 Google 地图 API v2 方法
private void getCurrentLocation() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
mMap.setMyLocationEnabled(true);
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
}
});
}
}
}
在这里您可以找到关于如何使用 Location Data
来自 Google Maps
-> https://developers.google.com/maps/documentation/android-sdk/location
在这里你可以找到如何获取最后一个已知位置(如果你的设备是第一次使用它可以是 null
现在它还没有被保存)-> https://developer.android.com/training/location/retrieve-current#java
private static final int REQUEST_LOCATION = 1;
private LocationManager locationManager;
//...
// In your onCreate
locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
//...
void getLocation() {
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) {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
} else {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
double lati = location.getLatitude();
double longi = location.getLongitude();
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
//You can retrieve any address you want like this...
List<Address> addresses = geocoder.getFromLocation(lati, longi, 1);
String address = addresses.get(0).getAdminArea() + ", " + addresses.get(0)
.getCountryName();
location_text.setText(address);
System.out.println(address);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//Create the location request and set the parameters
//To store parameters for requests to the fused location provider, create a LocationRequest.
// The parameters determine the level of accuracy for location requests.
//Create the location request and set the parameters
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_LOCATION:
getLocation();
break;
}
}
嗯,这就是我在我的应用程序中的做法:
首先声明:
private Location mylocation;
private GoogleApiClient googleApiClient;
private final static int REQUEST_CHECK_SETTINGS_GPS = 0x1;
private final static int REQUEST_ID_MULTIPLE_PERMISSIONS = 0x2;
public double latitude, longitude;
然后,在你的代码中写:
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
最后,
if (googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(3000);
locationRequest.setFastestInterval(3000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
LocationServices.FusedLocationApi
.requestLocationUpdates(googleApiClient, locationRequest, this);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi
.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
mylocation = LocationServices.FusedLocationApi
.getLastLocation(googleApiClient);
latitude = mylocation.getLatitude();
longitude = mylocation.getlongitude();
}
break;
}
}
}
试试这个,希望它有效。 }