0
我試圖獲取一個谷歌地圖的當前位置,但我在如何獲取當前位置的谷歌地圖?
得到這個錯誤FATAL EXCEPTION: main java.lang.NullPointerException
map= ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
Java代碼
public class MapFragment extends Fragment{
private TextView locationText;
private TextView addressText;
private GoogleMap map;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragment_map, container, false);
locationText = (TextView) rootview.findViewById(R.id.location);
addressText = (TextView) rootview.findViewById(R.id.address);
//replace GOOGLE MAP fragment in this Activity
return rootview;
}
public void onMapReady(GoogleMap map) {
//make the call here. it will be called once the map is ready
replaceMapFragment();
}
private void replaceMapFragment() {
map= ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// Enable Zoom
map.getUiSettings().setZoomGesturesEnabled(true);
//set Map TYPE
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//enable Current location Button
map.setMyLocationEnabled(true);
//set "listener" for changing my location
map.setOnMyLocationChangeListener(myLocationChangeListener());
}
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener() {
return new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Marker marker;
marker = map.addMarker(new MarkerOptions().position(loc));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
locationText.setText("You are at [" + longitude + " ; " + latitude + " ]");
//get current address by invoke an AsyncTask object
//new GetAddressTask(getActivity()).execute(String.valueOf(latitude), String.valueOf(longitude));
}
};
}
}
這是同樣的問題。標記仍然隱藏。我的代碼是否正確? –
爲了確保onMapReady()被調用,您需要以不同的方式聲明類,請參閱我編輯的答案。之前發佈不完整答案的道歉。 –