Mapview renders empty, but fragment is fine.

I am trying to use Google Map V2. When I use a map fragment .. Everything works. However, if I use mapview instead, it displays an empty activity.

What could be wrong? 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>

      

Primary activity:

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

      

+3


source to share


2 answers


You need to initialize the map yourself:



@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();
}

      

+8


source


about MainActivity - If you only want to display a simple map interface, you can do the following:

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
    }
[...]
}

      

and then the method:

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

      



About XML: I highly recommended that you use snippets for Google Maps objects, for example:

 <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"/>

      

I recommend you a simple tut, you will find all the answers there http://www.androidhive.info/2013/08/android-working-with-google-maps-v2/ (no, this is not my site - this is where I am started working with google maps api)

0


source







All Articles