谷歌地图v2未在片段中初始化

问题描述:

我想使用Google地图v2从fragment中显示我的当前位置,但Google地图在启动时未初始化。当我运行应用程序时,它也没有崩溃,但地图不显示我当前的位置,它也不显示任何东西。我在我的活动中使用了这些代码,它功能完善。谷歌地图v2未在片段中初始化

下面是我的java代码:

public class MapFragment extends Fragment implements LocationListener,GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener,OnMapReadyCallback { 
    SupportMapFragment mSupportMapFragment; 
    MapView mMapView; 
    Location mLastLocation; 
    Marker mCurrLocationMarker; 
    private MarkerOptions markerOptions; 
    protected GoogleApiClient mGoogleApiClient; 
    private LatLng latLng; 
    public GoogleMap mMap; 
    private Marker marker; 
    LocationRequest mLocationRequest; 
    private GoogleMap googleMap; 
    private TextView lastTrip, lastDeliveryText, lastDelivery, lastAmountText, lastAmount, kes, 
      todayTotal, totalDeliveryText, totalDelivery, totalAmount, totalAmountText; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     buildGoogleApiClient(); 
     // inflat and return the layout 
     View v = inflater.inflate(R.layout.map_fragment, container, 
       false); 

     mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapwhere); 
     if (mSupportMapFragment == null) { 
      FragmentManager fragmentManager = getFragmentManager(); 
      FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
      mSupportMapFragment = SupportMapFragment.newInstance(); 
      fragmentTransaction.replace(R.id.mapwhere, mSupportMapFragment).commit(); 
     } 

     if (mSupportMapFragment != null) { 
      mSupportMapFragment.getMapAsync(this); 
     } 


     return v; 
    } 
    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 
     Log.d("one","one"); 

     mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 
     //mMap.getUiSettings().setZoomControlsEnabled(true); 
     if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      if (ContextCompat.checkSelfPermission(getActivity(), 
        Manifest.permission.ACCESS_FINE_LOCATION) 
        == PackageManager.PERMISSION_GRANTED) { 
       Log.d("two","two"); 
       buildGoogleApiClient(); 
       mMap.setMyLocationEnabled(true); 

      } 
     } else { 
      Log.d("three","three"); 
      buildGoogleApiClient(); 
      mMap.setMyLocationEnabled(true); 

     } 
    } 
    protected synchronized void buildGoogleApiClient() { 
     Log.d("four","four"); 
     mGoogleApiClient = new GoogleApiClient.Builder(getActivity()) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .addApi(Places.GEO_DATA_API) 
       .build(); 
     mGoogleApiClient.connect(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     Log.d("five","five"); 
     mLastLocation = location; 

     if (mCurrLocationMarker != null) { 
      mCurrLocationMarker.remove(); 
     } 
     //mMap.getUiSettings().setZoomControlsEnabled(true); 

     final Double lat = location.getLatitude(); 
     final Double lng = location.getLongitude(); 
     Log.d("LATLANGz", lat + "|" + lng); 
     latLng = new LatLng(lat, lng); 
     markerOptions = new MarkerOptions(); 
     markerOptions.position(latLng); 
     markerOptions.title("Current Positionn"); 
     if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), 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; 
     } 
     mMap.setMyLocationEnabled(false); 

     markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.user_location)); 

     marker = mMap.addMarker(markerOptions); 

     //move map camera_main 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
     mMap.animateCamera(CameraUpdateFactory.zoomTo(12)); 
    } 

    @Override 
    public void onResume() { 
     super.onResume(); 
     Log.d("hey2","hey2"); 
//  mMapView.onResume(); 
     mSupportMapFragment.onResume(); 
    } 

    @Override 
    public void onPause() { 

     super.onPause(); 
     Log.d("hey1","hey1"); 
     // mMapView.onPause(); 
     mSupportMapFragment.onPause(); 
    } 

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

    @Override 
    public void onLowMemory() { 
     super.onLowMemory(); 
     // mMapView.onLowMemory(); 
     mSupportMapFragment.onLowMemory(); 
    } 

    @Override 
    public void onDetach() { 
     Log.d("detach", "detach"); 
     super.onDetach(); 
     mSupportMapFragment.onDetach(); 

    } 


    @Override 
    public void onConnected(@Nullable Bundle bundle) { 
     Log.d("six","six"); 
     mLocationRequest = new LocationRequest(); 
     mLocationRequest.setInterval(1000); 
     mLocationRequest.setFastestInterval(1000); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 

     if (mGoogleApiClient.isConnected()){ 
      Log.d("seven","six"); 
      if (ContextCompat.checkSelfPermission(getActivity(), 
        Manifest.permission.ACCESS_FINE_LOCATION) 
        == PackageManager.PERMISSION_GRANTED) { 
       LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
      } 
     } 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

    } 
+2

@Anshul我有互联网和access_fine_location –

+0

你有在谷歌创建项目? –

+0

是的,当我把静态LatLng onMapReady内部函数onCreate它工作正常 –

首先检查您的权限和你的谷歌的API密钥您的清单

xml布局必须是这样的没有别的任何事情:

. <fragment xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:map="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/map" 
    android:name="com.google.android.gms.maps.SupportMapFragment" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.isg_biz.isg_tracking.MainActivity" /> 

你必须实现OnMapReadyCallback,然后 你的代码应该是这样的在的onCreate():

 SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
     .findFragmentById(R.id.map); 
mapFragment.getMapAsync(this); 

不要复制和过去相同的XML代码从字面上,你必须改变(工具:.....)到存在于你的XML

的文件一样, java代码&更多,请阅读:

https://developers.google.com/maps/documentation/android-api/map-with-marker

第一清单中

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
所有Chaeck许可

然后检查方法为当前的位置

private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() { 
    @Override 
    public void onMyLocationChange(Location location) { 
     LatLng loc = new LatLng(location.getLatitude(), location.getLongitude()); 
     marker = map.addMarker(new MarkerOptions().position(loc)); 
     if(map != null){ 
      map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f)); 
     } 
    } 
}; 

然后用

mMap.setOnMyLocationChangeListener(myLocationChangeListener); 

,并耐心地图需要贴膜的时间取决于你的网络速度

评论,如果有任何疑问