谷歌地图v2没有初始化片段

时间:2017-10-07 04:13:24

标签: android google-maps-android-api-2

我想使用fragment中的Google地图v2显示我当前的位置,但Google地图在启动时未初始化。当我运行应用程序时,它也没有崩溃,但地图没有显示我当前的位置,也没有显示任何内容。我在我的活动中使用了这个代码,它完全正常运行。

以下是我的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 个答案:

答案 0 :(得分:0)

首先检查您的权限以及清单中的Google 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代码和&amp;更多请阅读:

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

答案 1 :(得分:0)

首先是清单中的Chaeck权限

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

然后检查当前位置的方法

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);

并且耐心地图取决于你的网络速度

评论是否有任何查询