Google Map无法定位当前设备位置且不显示经纬度求助
问题:Google Map 启动时不缩放至当前位置也不显示经纬度
我想要实现Activity启动时,地图自动缩放至当前设备位置,同时显示当前位置的经纬度,但实际运行时地图停在(0,0)位置,既不缩放也不显示经纬度。以下是我的实现代码:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; private static final int REQUEST_LOCATION = 1; LocationManager locationManager; Location location; TextView latlngText; Button refreshBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.maps_layout); // 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); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); refreshBtn = (Button) findViewById(R.id.refreshbtn); refreshBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MapsActivity.this, MapsActivity.class); startActivity(intent); finish(); } }); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); 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; } mMap.setMyLocationEnabled(true); getLocation(); } void getLocation() { 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; }else { Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER); if(location != null) { double lat = location.getLatitude(); double lng = location.getLongitude(); latlngText = (TextView) findViewById(R.id.latlngText); latlngText.setText("Latitude: " + lat + "\n" + "Longitude: " + lng); LatLng coordinates = new LatLng(location.getLatitude(), location.getLongitude()); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 13.0f)); } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode){ case REQUEST_LOCATION: getLocation(); break; } } }
解决方案
你的代码有几个关键问题导致地图无法定位到当前位置,我帮你一步步修复:
1. 主动触发权限请求
你的代码只是检查了权限,但没有主动发起权限请求——如果用户还没授予位置权限,onMapReady会直接return,后续的getLocation()根本不会执行。修改onMapReady方法,当权限未授予时主动发起请求:
@Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); // 检查位置权限 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // 主动请求权限 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_LOCATION); return; } mMap.setMyLocationEnabled(true); getLocation(); }
2. 处理getLastKnownLocation返回null的情况
getLastKnownLocation依赖设备缓存的位置信息,如果是第一次启动应用、设备刚开机,这个方法会返回null。我们需要添加LocationListener来监听实时位置更新作为 fallback:
首先在类中添加LocationListener变量:
private LocationListener locationListener;
然后修改getLocation方法,当缓存位置为空时注册位置监听:
void getLocation() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_LOCATION); return; } else { Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { // 有缓存位置,直接更新UI updateLocationUI(location); } else { // 无缓存位置,注册监听获取实时位置 locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { updateLocationUI(location); // 获取到位置后停止监听,节省资源 locationManager.removeUpdates(this); } @Override public void onStatusChanged(String provider, int status, Bundle extras) {} @Override public void onProviderEnabled(String provider) {} @Override public void onProviderDisabled(String provider) {} }; // 注册网络和GPS位置更新监听 locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 10, locationListener); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, locationListener); } } }
3. 提取UI更新逻辑到单独方法
把更新经纬度和地图缩放的逻辑抽出来,避免重复代码,同时提前初始化latlngText:
private void updateLocationUI(Location location) { double lat = location.getLatitude(); double lng = location.getLongitude(); // 只初始化一次TextView if (latlngText == null) { latlngText = findViewById(R.id.latlngText); } latlngText.setText("Latitude: " + lat + "\n" + "Longitude: " + lng); LatLng coordinates = new LatLng(lat, lng); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 13.0f)); }
4. 确保Manifest配置正确
别忘了在AndroidManifest.xml中添加必要的权限和Google Maps配置:
<!-- 位置权限 --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- 网络权限(地图加载需要) --> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-- Google Maps API Key 替换成你自己的 --> <meta-data android:name="com.google.android.geo.API_KEY" android:value="YOUR_GOOGLE_MAPS_API_KEY" />
5. 优化刷新按钮逻辑(可选)
现在的刷新按钮是重启Activity,其实直接调用getLocation()就能更新位置,更高效:
refreshBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getLocation(); } });
内容的提问来源于stack exchange,提问作者Basil Shaikh
相关产品推荐
相关产品推荐

