【问题标题】:Google maps v2 not initializing in fragment谷歌地图 v2 未在片段中初始化
【发布时间】:2017-10-07 04:13:24
【问题描述】:

我想使用来自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) {

    }

【问题讨论】:

  • @Anshul 我有互联网和 access_fine_location
  • 你在google上创建过项目吗?
  • 是的,当我将静态 LatLng onMapReady 内部函数放入 onCreate 时,它​​工作正常
  • @NoumanCh 我认为这不是重复的问题

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


【解决方案1】:

首先检查清单中的权限

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

耐心地图加载时间取决于你的网速

如有疑问请留言

【讨论】:

    【解决方案2】:

    首先检查您的权限和清单中的 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 代码等请阅读:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-26
      • 1970-01-01
      • 2013-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多