1

У меня возникла странная проблема с GoogleMap in Fragment.GoogleMap не загружается внутри ViewPager

Я реализовал какое-то меню с элементами, отображаемыми через ViewPager. Некоторые элементы могут показывать короткий просмотр в GoogleMap. Элементы - это фрагменты, которые загружаются ViewPager. Чтобы показать предыдущие и следующие элементы, ViewPager также завернут внутри контейнера FrameLayout (например, ViewPager with previous and next page boundaries).

Проблема в том, что карта не загружается. В прошлом году я выпустил версию с Eclipse, и проблем не было. Теперь я использую другой mac и импортировал проект в Android Studio. Все работало. Я получил сообщение об ошибке в LogCat, но карта показывает в другой деятельности с MapFragment:

E/dalvikvm﹕ Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.common.GooglePlayServicesUtil.zza 
E/dalvikvm﹕ Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.common.hg.a 

Метод 1: MapView в пользовательском Фрагменте (android MapView in Fragment) MapView было показано, но вы можете видеть только сетку карта. Когда вы просматриваете ViewPager, на том месте, где была карта, появляется черный прямоугольник.

<LinearLayout 
    android:id="@+id/itemInfo" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_below="@id/itemSubTitle" 
    android:layout_centerHorizontal="true" 
    android:orientation="vertical" 
    >  


    <TextView 
    android:id="@+id/itemDistanceInfo" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:paddingBottom="0dp" 
    android:paddingTop="0dp" 
    android:textSize="6pt" 
    android:textColor="@color/white" 
    android:text="ca. 89 km" 
    android:visibility="gone" 
     /> 

     <RelativeLayout 
    android:id="@+id/itemInfoPrice" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerHorizontal="true" 
    android:background="@color/white“ 
    android:layout_marginTop="8dp" 
    android:padding="5dp" 
    android:visibility="gone" 
    > 

    <include layout="@layout/price_menu_fragment"/> 

    </RelativeLayout> 


<FrameLayout 
    android:id="@+id/itemInfoPicture" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerHorizontal="true" 
    android:background="@color/white“ 
    android:layout_marginTop="8dp" 
    android:padding="5dp" 
    android:visibility="visible" 
    > 

    <ImageView 
     android:id="@+id/itemImage" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_horizontal" 
     android:src="@drawable/menue_info" 
     android:visibility="invisible" 
     /> 

    <com.google.android.gms.maps.MapView 
     android:id="@+id/mapview" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" /> 

</FrameLayout> 
</LinearLayout> 

enter image description here

Метод 2: SupportMapFragment в пользовательском Фрагменте Здесь есть только черный вид, но с логотипом Google, показанным в левом углу. Прокрутка в ViewPager не показывает черный прямоугольник, как в методе 1.

Я надеюсь, что кто-то может помочь мне.

+0

ли вы использовать различные хранилища ключей для подписи, как если вы строите ваше приложение с затмением? Майе, вы должны перенастроить свой API Google на консоли разработчика Google? – Christopher

+0

Да, новое хранилище ключей было построено. Но я переконфигурировал ключ Google в консоли. Карта показана в двух других действиях. Возможно, я снова попытаюсь установить eclipse, но я внес некоторые другие изменения. – corban

ответ

2
import com.google.android.gms.maps.SupportMapFragment; 

SupportMapFragment mMapFragment = SupportMapFragment.newInstance();  
FragmentManager fm = fragment.getChildFragmentManager(); 
fm.beginTransaction().add(R.id.map, mMapFragment).commit(); 
mMapFragment.getMapAsync(this); 

@Override 
public void onMapReady(GoogleMap googleMap) { 
    mGoogleMap = googleMap; 

    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     //           int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     return; 
    } 
    mGoogleMap.setMyLocationEnabled(true); 

    buildGoogleApiClient(); 

    mGoogleApiClient.connect(); 
} 

protected synchronized void buildGoogleApiClient() { 

    mGoogleApiClient = new GoogleApiClient.Builder(getContext()) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build(); 
} 

@Override 
public void onConnected(Bundle bundle) { 

    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     //           int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     return; 
    } 
    Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
      mGoogleApiClient); 
    if (mLastLocation != null) { 
     //place marker at current position 
     mGoogleMap.clear(); 
     //setLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude()); 
    } 


    mLocationRequest = new LocationRequest(); 
    mLocationRequest.setInterval(50000); //50 seconds 
    mLocationRequest.setFastestInterval(30000); //30 seconds 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 
    //mLocationRequest.setSmallestDisplacement(0.1F); //1/10 meter 

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
} 

@Override 
public void onConnectionSuspended(int i) { 
    Toast.makeText(customAdapter.getContext(), "onConnectionSuspended", Toast.LENGTH_SHORT).show(); 
} 

@Override 
public void onConnectionFailed(ConnectionResult connectionResult) { 
    Toast.makeText(customAdapter.getContext(), "onConnectionFailed", Toast.LENGTH_SHORT).show(); 
} 

@Override 
public void onLocationChanged(Location location) { 
    sourceLat = location.getLatitude(); 
    sourceLng = location.getLongitude(); 
    getRestaurantDetails(); 
    latLng = new LatLng(location.getLatitude(), location.getLongitude()); 
    //latLng = new LatLng(lat, lng); 
    //Log.wtf("Lat lng", lat + " " + lng); 
    mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18)); 
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
} 

где фрагмент экземпляра вашего viewPagerFragment

в XML

<LinearLayout 
android:id="@+id/map" 
android:layout_width="match_parent" 
android:layout_height="250dp" /> 
Смежные вопросы