缩放到不使用导航抽屉的当前位置

时间:2015-11-23 05:14:25

标签: android google-maps

我正在开发一个Android应用程序,它由导航抽屉和谷歌地图组成。我已经成功开发了我的导航抽屉并将我的地图连接到它。问题是我需要将地图缩放到当前位置。

以下是我在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));
    }

}

这里我实现了getMyLocation()方法。

//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;
}

以下是我如何将MapsFragment提供给NavigatioDrawerActivity。

fragment = new MapFragment();

当我独自运行时(将意图过滤器插入Manifest中的MapsActivity),它可以完美运行。但是,当我将Nvigation Drawer作为MainActivity运行时,此功能无效。只加载默认地图。

我该怎么办?

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

我的Maps.xml是这样的。

<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" />

我的整个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) {

    }


}

这是我的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);
    }
}

3 个答案:

答案 0 :(得分:1)

试试这个..

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

你没有在浮动中给出。所以它不工作..试试这个..

答案 1 :(得分:0)

试试这个

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

在XML

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

在JAVA活动中

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:
    }
}

像这样打电话

initializaMap(savedInstanceState);

答案 2 :(得分:0)

它不起作用,因为导航抽屉采用片段并且您正在初始化:

fragment = new MapFragment();  

所以需要 MapFragment默认布局

您必须更改 updateDisplay 才能获取活动而不是片段。换句话说,将导航抽屉更改为活动而不是片段