实际上我的问题是我没有尝试多种方法获取当前位置的纬度和经度。我知道这个问题已经在SO中问过了,我尝试了答案也仍然没有得到答案。请帮助我
代码:
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
googleMap.setMyLocationEnabled(true);
Location myLocation = googleMap.getMyLocation(); //Nullpointer exception.........
LatLng myLatLng = new LatLng(myLocation.getLatitude(),
myLocation.getLongitude());
CameraPosition myPosition = new CameraPosition.Builder()
.target(myLatLng).zoom(17).bearing(90).tilt(30).build();
googleMap.animateCamera(
CameraUpdateFactory.newCameraPosition(myPosition));
最佳答案
请检查Google Maps Android API v2的示例代码。使用此方法可以解决您的问题。
private void setUpMapIfNeeded() {
// 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) {
mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
}
});
}
}
}
在
onCreate
函数中调用此函数。