实际上我的问题是我没有得到当前位置的纬度和经度我尝试了很多方法。我知道这个问题已经问过所以我也尝试过这些答案仍然没有得到答案。请帮助我。
我想在 Map 中获取我当前的位置并将其设置在 location 变量中
这是我的代码:
- onCreate 方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_your_location);
// 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);
infoTextView = (TextView) findViewById(R.id.infoTextView);
requestKorsaButton = (Button) findViewById(R.id.requestKorsa);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), true);
if(provider == null) {
Toast.makeText(this, "No Location for you", Toast.LENGTH_SHORT).show();
}
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},
PERMISSION_LOCATION_REQUEST_CODE);
}
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
- onMapReady 方法
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
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},
PERMISSION_LOCATION_REQUEST_CODE);
}
mMap.setMyLocationEnabled(true);
location = locationManager.getLastKnownLocation(provider);
if (location != null) {
updateLocation(location);
}
}
发生这个问题是因为我试图在模拟器中运行我的应用程序,但是当我在我的设备中运行时,它可以工作。谢谢...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句