简体   繁体   中英

Zoom to the current location not working with navigation drawer

I'm developing an Android Application which is consists of a Navigation drawer and a Google Map. I have successfully developed my Navigation Drawer and connect my Map into it. The thing is I need my Map to Zoom to the current location.

Here is the code I used in MapsActivity.java .

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    setUpMapIfNeeded();

    mMap.setMyLocationEnabled(true); // Identify the current location of the device
    mMap.setOnMyLocationChangeListener(this); // change the place when the device is moving

    Location currentLocation = getMyLocation(); // Calling the getMyLocation method
    if(currentLocation!=null){
        LatLng currentCoordinates = new LatLng(
                currentLocation.getLatitude(),
                currentLocation.getLongitude());
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentCoordinates, 13.0f));
    }

}

Here I implemented getMyLocation() method.

//Zoom to the current location
private Location getMyLocation() {
    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); // Get location from GPS if it's available
    Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    // Location wasn't found, check the next most accurate place for the current location
    if (myLocation == null) {
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        // Finds a provider that matches the criteria
        String provider = lm.getBestProvider(criteria, true);
        // Use the provider to get the last known location
        myLocation = lm.getLastKnownLocation(provider);
    }
    return myLocation;
}

Here is How I gave MapsFragment in to NavigatioDrawerActivity.

fragment = new MapFragment();

When I run this alone (Insert intent filter to MapsActivity in Manifest) it works perfect. But, when I'm running the Nvigation Drawer as MainActivity this function is not working. Only the default Map is loading.

What should I do?

-edit-

private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

My Maps.xml is like this.

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

My whole MapsActivity.java

public class MapsActivity extends FragmentActivity implements GoogleMap.OnMyLocationChangeListener {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.
    private MapView mapView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        setUpMapIfNeeded();

        mMap.setMyLocationEnabled(true); // Identify the current location of the device
        mMap.setOnMyLocationChangeListener(this); // change the place when the device is moving


        initializaMap(rootView, savedInstanceState);

    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    private void initializaMap(View rootView, Bundle savedInstanceState){
        MapsInitializer.initialize(MapsActivity.this);
        switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(MapsActivity.this)) {
            case ConnectionResult.SUCCESS:
                mapView = (MapView) rootView.findViewById(R.id.mapView);
                mapView.onCreate(savedInstanceState);

                if (mapView != null) {
                    mMap = mapView.getMap();
                    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                    UiSettings mUiSettings = mMap.getUiSettings();
                    mMap.setMyLocationEnabled(true);
                    mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));
                    mUiSettings.setCompassEnabled(true);
                    mUiSettings.setMyLocationButtonEnabled(false);

                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(6.9270786, 79.861243), 13));
                }
                break;
            case ConnectionResult.SERVICE_MISSING:
                break;
            case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
                break;
            default:
        }
    }


    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     * <p/>
     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    }

    @Override
    public void onMyLocationChange(Location location) {

    }


}

Here is my NavigationDrawer.java

public class NavigationDrawer extends ActionBarActivity {

    private GoogleMap mMap;

    String[] menutitles;
    TypedArray menuIcons;

    // nav drawer title
    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private List<RowItem> rowItems;
    private CustomAdapter adapter;
    private LinearLayout mLenear;
    static ImageView imageView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_NavigationDrawer);

        mTitle = mDrawerTitle = getTitle();
        menutitles = getResources().getStringArray(R.array.titles);
        menuIcons = getResources().obtainTypedArray(R.array.icons);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.slider_list);
        mLenear = (LinearLayout)findViewById(R.id.left_drawer);

        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFA500")));

        imageView=(ImageView)findViewById(R.id.profPic);
        Bitmap bitmap= BitmapFactory.decodeResource(getResources(), R.drawable.ic_prof);
        imageView.setImageBitmap(getCircleBitmap(bitmap));

        rowItems = new ArrayList<RowItem>();

        for (int i = 0; i < menutitles.length; i++) {
            RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(      i, -1));
            rowItems.add(items);
        }

        menuIcons.recycle();
        adapter = new CustomAdapter(getApplicationContext(), rowItems);
        mDrawerList.setAdapter(adapter);
        mDrawerList.setOnItemClickListener(new SlideitemListener());

        // enabling action bar app icon and behaving it as toggle button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_menu, R.string.app_name,R.string.app_name)
        {
            public void onDrawerClosed(View view) {
                getSupportActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }
            public void onDrawerOpened(View drawerView) {
                getSupportActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();          }
        };

        mDrawerLayout.setDrawerListener(mDrawerToggle);
        if (savedInstanceState == null) {
            // on first time display view for first nav item
            updateDisplay(0);
        }
        initializaMap(savedInstanceState);
    }

    private void initializaMap(Bundle savedInstanceState){
        MapsInitializer.initialize(Extract.this);
        switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(Extract.this)) {
            case ConnectionResult.SUCCESS:
                MapView mapView = (MapView) findViewById(R.id.mapView);
                mapView.onCreate(savedInstanceState);

                if (mapView != null) {
                    mMap = mapView.getMap();
                    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                    UiSettings mUiSettings = mMap.getUiSettings();
                    mMap.setMyLocationEnabled(true);
                    mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));
                    mUiSettings.setCompassEnabled(true);
                    mUiSettings.setMyLocationButtonEnabled(false);

                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(6.9192, 79.8950), 13));
                }
                break;
            case ConnectionResult.SERVICE_MISSING:
                break;
            case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
                break;
            default:
        }
    }

   //Circle Image
    public static Bitmap getCircleBitmap(Bitmap bitmap) {

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        int radius = Math.min(h / 2, w / 2);
        Bitmap output = Bitmap.createBitmap(w + 8, h + 8, Bitmap.Config.ARGB_8888);

        Paint p = new Paint();
        p.setAntiAlias(true);

        Canvas c = new Canvas(output);
        c.drawARGB(0, 0, 0, 0);
        p.setStyle(Paint.Style.FILL);

        c.drawCircle((w / 2) + 4, (h / 2) + 4, radius, p);

        p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

        c.drawBitmap(bitmap, 4, 4, p);
        p.setXfermode(null);
        p.setStyle(Paint.Style.STROKE);
        p.setColor(Color.WHITE);
        p.setStrokeWidth(3);
        c.drawCircle((w / 2) + 2, (h / 2) + 2, radius, p);

        return output;
    }

    class SlideitemListener implements ListView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            updateDisplay(position);
        }
    }
        private void updateDisplay(int position) {
            Fragment fragment = null;
            switch (position) {
                case 0:
                   // fragment = new MapFragment();
                    //break;

                default:
                    break;
            }
            if (fragment != null) {
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();

                // update selected item and title, then close the drawer
                setTitle(menutitles[position]);
                mDrawerLayout.closeDrawer(mLenear);
            }
            else {
                // error in creating fragment
                Log.e("Extract", "Error in creating fragment");
            }
        }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getSupportActionBar().setTitle(mTitle);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_extract, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
        case R.id.action_settings:
            return true;
            default :
                return super.onOptionsItemSelected(item);
        }
    }

    /***   * Called when invalidateOptionsMenu() is triggered   */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mLenear);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    /**   * When using the ActionBarDrawerToggle, you must call it during   * onPostCreate() and onConfigurationChanged()...   */
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggles
        mDrawerToggle.onConfigurationChanged(newConfig);
    }
}

try this ..

   map.animateCamera(CameraUpdateFactory.newLatLngZoom((sydney), 13.0f));

you have not given by in float. so its not working.. try this..

try this

map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentCoordinates, 13));

In XML

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

In JAVA Activity

private void initializaMap(Bundle savedInstanceState){
    MapsInitializer.initialize(MainActivity.this);
    switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity())) {
    case ConnectionResult.SUCCESS:
        mapView = (MapView) findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);

        if (mapView != null) {
            mMap = mapView.getMap();
            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            UiSettings mUiSettings = mMap.getUiSettings();
            mMap.setMyLocationEnabled(true);
            mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));
            mUiSettings.setCompassEnabled(true);    
            mUiSettings.setMyLocationButtonEnabled(false);

            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLatitude, mLongitude), 13));
        }
        break;
    case ConnectionResult.SERVICE_MISSING:
        break;
    case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
        break;
    default:
    }
}

call like this

initializaMap(savedInstanceState);

it will not work because the navigation drawer takes a fragment and you are initializing :

fragment = new MapFragment();  

so it takes the MapFragment default layout .

you must to change the updateDisplay to takes an activity not a fragment . In another words change the navigation drawer to activities instead of fragments

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM