【问题标题】:android (Support)MapFragment getMap() return nullandroid (支持)MapFragment getMap() 返回 null
【发布时间】:2013-09-26 08:20:37
【问题描述】:

我已经阅读了很多关于这个问题的主题,但没有任何帮助。 所以我想在 SupportMapFragment 中对 GoogleMap 进行操作。在 FragmentActivity 中,我在 onCreate 方法中初始化了地图

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_frame);

    // Initialize Google Maps Android API
    try {
        MapsInitializer.initialize(this);
    } catch (GooglePlayServicesNotAvailableException e) {
        e.printStackTrace();
    }
...

我的 MapFragment 的代码看起来就像这样

public class MapFragment extends SupportMapFragment {

private final String TAG = getClass().getSimpleName();


public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    return inflater.inflate(R.layout.map, null);
}

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    GoogleMap gMap = this.getMap();

    Log.d(TAG,
            "getMap() " + ((gMap == null) ? "null" : gMap.toString()));

    // Setting Location and Zoom
    gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
            40.76793169992044f, -73.98180484771729f), 14.0f));
}

}

每次我使用 getMap 方法得到 null 时......有什么想法吗?

€dit:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"
map:cameraBearing="112.5"
map:cameraTargetLat="-33.796923"
map:cameraTargetLng="150.922433"
map:cameraTilt="30"
map:cameraZoom="50"
map:mapType="normal"
map:uiCompass="false"
map:uiRotateGestures="true"
map:uiScrollGestures="false"
map:uiTiltGestures="true"
map:uiZoomControls="false"
map:uiZoomGestures="true" />

【问题讨论】:

  • 你的布局中有地图吗?
  • 不是直接的。我有一个片段布局文件。在编辑后的帖子中查看。
  • 您是否尝试过将 getMap() 代码移至 onStart 或 onResume?请参阅我的回答stackoverflow.com/a/20747717/2364687,尽管它可能不适用于您的情况。此外,您肯定安装了 Google Play 服务(即,您没有在 onCreate 中捕获并忽略异常)?

标签: android android-mapview mapfragment


【解决方案1】:

在将 google play 服务更新到最新版本后遇到了类似的问题。 通过在清单中添加元数据解决了我的问题

<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

https://developers.google.com/maps/documentation/android/start#add_a_map

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多