Android Google Maps setMyLocationEnabled(true)

前端 未结 2 897
攒了一身酷
攒了一身酷 2021-01-24 20:24

I\'m working through a tutorial and my app is basically working except for one small detail. I have an Options menu to demonstrate things like showing the map as a Satellite vie

相关标签:
2条回答
  • 2021-01-24 21:02

    From developers doc,

    A GoogleMap can only be acquired using getMap() when the underlying maps system is loaded and the underlying view in the fragment exists. This class automatically initializes the maps system and the view; however you cannot be guaranteed when it will be ready because this depends on the availability of the Google Play services APK. If a GoogleMap is not available, getMap() will return null.

    • This can happen if the fragment lifecyle have not gone through onCreateView(LayoutInflater, ViewGroup, Bundle) yet.
    • This can also happen if Google Play services is not available.

    Further pointing out,

    If Google Play services becomes available afterwards and the fragment have gone through onCreateView(LayoutInflater, ViewGroup, Bundle), calling this method again will initialize and return the GoogleMap.

    As there is no indication that from where did you got your map and at exactly which method call so I assume that your getmap() is returning null. That means the map is not ready. Either because the fragment is not ready or your are running on a device without Google Play services available.

    See getMap for more info.

    0 讨论(0)
  • 2021-01-24 21:14

    Initially when first time your GoogleMap loads takes some time and there fore Location will be null.

    So for your both menu options check this way.

    if(map!=null){
     map.setMyLocationEnabled(true);
    }
    
    
    if(map!=null){
        Location myLocation = map.getMyLocation();
    
        if(myLocation !=null){
        LatLng myLatLng = new LatLng(myLocation.getLatitude(),
                myLocation.getLongitude());
    
    
        CameraPosition myPosition = new CameraPosition.Builder()
                .target(myLatLng).zoom(17).bearing(90).tilt(30).build();
        map.animateCamera(CameraUpdateFactory.newCameraPosition(myPosition));
       }
    }
    
    0 讨论(0)
提交回复
热议问题