Mapview显示空白但片段没问题

时间:2014-11-16 20:55:21

标签: android android-maps-v2

我正在尝试使用Google Map V2。当我使用地图片段..一切正常。 但是,如果我使用mapview,则会显示空白活动。

可能有什么不对? XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mapParent"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
     <com.google.android.gms.maps.MapView 
          android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"/>

     </LinearLayout>

主要活动:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

2 个答案:

答案 0 :(得分:9)

您需要自己初始化地图:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Gets the MapView from the XML layout and creates it
    MapView mapView = (MapView) findViewById(R.id.map);
    mapView.onCreate(savedInstanceState);

    // Gets to GoogleMap from the MapView and does initialization stuff
    GoogleMap map = mapView.getMap();

    // Needs to call MapsInitializer before doing any CameraUpdateFactory calls
    MapsInitializer.initialize(this);

    mapView.onResume();
}

答案 1 :(得分:0)

关于MainActivity - 如果您只想显示简单的地图UI,可以执行以下操作:

private GoogleMap map; // or   private static GoogleMap map;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
[...]
try {
        loadingObjectOfMainMap();
    } catch (Exception e) {
        e.printStackTrace(); // prints error to console/log
    }
[...]
}

然后方法:

protected void loadingObjectOfMainMap() {
    if( map == null) {
        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
               .getMap();
        map.setMyLocationEnabled(true); // will display blue dot at your location
    }
}

关于XML: 我强烈建议您使用谷歌地图对象的片段,如下所示:

 <fragment xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:mapOptions="http://schemas.android.com/apk/res-auto"
      android:id="@+id/map"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:name="com.google.android.gms.maps.MapFragment"
      mapOptions:mapType="hybrid"/>

我推荐你简单的啧啧,你会找到所有答案 http://www.androidhive.info/2013/08/android-working-with-google-maps-v2/ (不,这不是我的网站 - 这是我开始使用谷歌地图api的地方)