2014-06-27 15 views
10

Tôi đang làm việc với Google Maps. Tôi có thể tạo thành công và có thể hiển thị Google Map. Bây giờ tôi muốn thêm CameraUpdate(latitude, longitude). Tôi googled và tôi tìm thấy một số mã nguồn nhưng tôi nhận được một NullPointerException.java.lang.NullPointerException: CameraUpdateFactory không được khởi tạo ngoại lệ logcat

thông báo lỗi Các LogCat là:

java.lang.NullPointerException: CameraUpdateFactory is not initialized 

Đây là nguồn của tôi. Tôi đang làm gì sai?

public class StradaContact extends Fragment { 

public final static String TAG = StradaContact.class.getSimpleName(); 
private MapView mMapView; 
private GoogleMap mMap; 
private Bundle mBundle; 
double longitude = 44.79299800000001, latitude = 41.709981; 

public StradaContact() { 

} 

public static StradaContact newInstance() { 
    return new StradaContact(); 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 

    View rootView = inflater.inflate(R.layout.strada_contact, container,false); 

    mMapView = (MapView) rootView.findViewById(R.id.pointMap); 

    mMapView.onCreate(mBundle); 
    setUpMapIfNeeded(rootView); 

    return rootView; 
} 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    mBundle = savedInstanceState; 
} 

private void setUpMapIfNeeded(View inflatedView) { 
    if (mMap == null) { 
     mMap = ((MapView) inflatedView.findViewById(R.id.pointMap)).getMap(); 
     if (mMap != null) { 
      CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(latitude, longitude)); 
      CameraUpdate zoom = CameraUpdateFactory.zoomTo(15); 
      mMap.moveCamera(center); 
      mMap.animateCamera(zoom); 
     } 
    } 
} 

@Override 
public void onResume() { 
    super.onResume(); 
    mMapView.onResume(); 
} 

@Override 
public void onPause() { 
    super.onPause(); 
    mMapView.onPause(); 
} 

@Override 
public void onDestroy() { 
    mMapView.onDestroy(); 
    super.onDestroy(); 
} 

}

<com.google.android.gms.maps.MapView 
     android:id="@+id/pointMap" 
     android:name="com.google.android.gms.maps.MapFragment" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 

     class="com.google.android.gms.maps.MapFragment" /> 
+0

kiểm tra xem nó: http: //stackoverflow.com/questions/19541915/google-maps-cameraupdatefactor y-not-initalized – Ranjit

Trả lời

6

Hãy thử với phương pháp sau đây khởi tạo google map api trước khi sử dụng

MapsInitializer.initialize(getActivity()); 
+0

Tại sao điều này tốt hơn 'getMap()'? –

19

Hãy thử điều này trong "onCreate":

try { 
MapsInitializer.initialize(this); 
} catch (GooglePlayServicesNotAvailableException e) { 
e.printStackTrace(); 
} 
+0

nó làm việc cho tôi =) –

+0

Tôi đã gọi phương thức 'getMap()' của SupportMapFragment. Tại sao tôi cũng cần MapsInitializer? –

Các vấn đề liên quan