Android 无法使用google地图获取当前位置
我在一个项目中使用谷歌地图,我想得到我的当前位置,但它不能正常工作 MyActivity.java代码:Android 无法使用google地图获取当前位置,android,google-maps,currentlocation,Android,Google Maps,Currentlocation,我在一个项目中使用谷歌地图,我想得到我的当前位置,但它不能正常工作 MyActivity.java代码: LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); if (enabl
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;
}
}
但是每次它都返回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 Map 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!"));
}
});
}
}
}
使用这个GoogleMapAPIv2方法
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!"));
}
});
}
}
}
在这里,您可以从
googlemaps
->
在这里,您可以找到如何获取最后一个已知位置(如果您的设备第一次使用它,它可以是
null,但目前尚未保存)->在这里,您可以从谷歌地图找到关于如何使用位置数据的文档
在这里,您可以找到如何获取最后一个已知位置(如果您的设备第一次使用它,它可以是null
,但目前尚未保存)->私有静态最终整数请求\u location=1;
私人场所经理场所经理;
//...
//在你的onCreate中
locationManager=(locationManager)
this.getSystemService(Context.LOCATION\u服务);
//...
void getLocation(){
如果(ActivityCompat.checkSelfPermission)(此,
android.Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予&&
ActivityCompat.checkSelfPermission(此,
android.Manifest.permission.ACCESS\u\u位置)!=PackageManager.permission\u已授予){
ActivityCompat.requestPermissions(此,
新字符串[]{android.Manifest.permission.ACCESS\u\u位置,
android.Manifest.permission.ACCESS\u FINE\u LOCATION},
请求地址);
}否则{
Location Location=locationManager.getLastKnownLocation(locationManager.NETWORK\u提供程序);
如果(位置!=null){
双纬度=location.getLatitude();
double longi=location.getLongitude();
Geocoder Geocoder=新的Geocoder(这个,Locale.getDefault());
试一试{
//你可以像这样检索任何你想要的地址。。。
列表地址=geocoder.getFromLocation(lati,longi,1);
字符串地址=地址.get(0).getAdminArea()+“,”+地址.get(0)
.getCountryName();
位置\u text.setText(地址);
系统输出打印项次(地址);
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
}
//创建位置请求并设置参数
//要存储对融合位置提供程序的请求的参数,请创建LocationRequest。
//这些参数决定了定位请求的准确度。
//创建位置请求并设置参数
@凌驾
public void onRequestPermissionsResult(int-requestCode,@NonNull-String[]permissions,@NonNull-int[]grantResults){
super.onRequestPermissionsResult(请求代码、权限、授权结果);
开关(请求代码){
案例请求位置:
getLocation();
打破
}
}
私有静态最终整数请求位置=1;
私人场所经理场所经理;
//...
//在你的onCreate中
locationManager=(locationManager)
this.getSystemService(Context.LOCATION\u服务);
//...
void getLocation(){
如果(ActivityCompat.checkSelfPermission)(此,
android.Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予&&
ActivityCompat.checkSelfPermission(此,
android.Manifest.permission.ACCESS\u\u位置)!=PackageManager.permission\u已授予){
ActivityCompat.requestPermissions(此,
新字符串[]{android.Manifest.permission.ACCESS\u\u位置,
android.Manifest.permission.ACCESS\u FINE\u LOCATION},
请求地址);
}否则{
Location Location=locationManager.getLastKnownLocation(locationManager.NETWORK\u提供程序);
如果(位置!=null){
双纬度=location.getLatitude();
double longi=location.getLongitude();
Geocoder Geocoder=新的Geocoder(这个,Locale.getDefault());
试一试{
//你可以像这样检索任何你想要的地址。。。
列表地址=geocoder.getFromLocation(lati,longi,1);
字符串地址=地址.get(0).getAdminArea()+“,”+地址.get(0)
.getCountryName();
位置\u text.setText(地址);
系统输出打印项次(地址);
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
}
//创建位置请求并设置参数
//要存储对融合位置提供程序的请求的参数,请创建LocationRequest。
//这些参数决定了定位请求的准确度。
//创建位置请求并设置参数
@凌驾
public void onRequestPermissionsResult(int-requestCode,@NonNull-String[]permissions,@NonNull-int[]grantResults){
super.onRequestPermissionsResult(请求代码、权限、授权结果);
开关(请求代码){
案例请求位置:
getLocation();
打破
}
}
我就是这样在我的应用程序中实现的:
首先声明:
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;
}
}
}
if(googleApiClient.isConnected()){
LocationServices.FusedLocationApi.getLastLocation(GoogleAppClient);
LocationRequest LocationRequest=新的LocationRequest();
位置请求设置间隔(3000);
locationRequest.SetFastTestInterval(3000);
locationRequest.setPriority(locationRequest.PRIORITY\u高精度);
位置设置请求生成器bu