简体   繁体   中英

Change zoom level Google Maps Api v2 on app start

Is it possible to change the zoom level as soon as the map is ready? When I open the app it shows the map and the blue dot for my location. However, the zoom level is the default 3. How can I change this? I know how to do it when the 'MyLocationButton'is clicked but not when the app starts.

This is my class

public class MainPhoneActivity extends FragmentActivity implements ConnectionCallbacks, OnConnectionFailedListener, LocationSource, LocationListener, OnMyLocationButtonClickListener, OnMapReadyCallback{

    private GoogleApiClient mGoogleApiClient;
    private OnLocationChangedListener mMapLocationListener = null;

    // location accuracy settings
    private static final LocationRequest REQUEST = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);


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

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.mapView);
        mapFragment.getMapAsync(this);

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

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

    @Override
    public void onPause() {
        super.onPause();
        mGoogleApiClient.disconnect();
    }

    @Override
    public void onMapReady(GoogleMap map) {
        map.setLocationSource(this);
        map.setMyLocationEnabled(true);
        map.setOnMyLocationButtonClickListener(this);
    }

    public void showMyLocation(View view) {
        if (mGoogleApiClient.isConnected()) {
            String msg = "Location = "
                    + LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        if (mMapLocationListener != null) {
            mMapLocationListener.onLocationChanged(location);
        }
    }

    @Override
    public void onConnected(Bundle connectionHint) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, REQUEST,this);
    }

    @Override
    public void onConnectionSuspended(int cause) {
        // Do nothing
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // Do nothing
    }

    @Override
    public boolean onMyLocationButtonClick() {
        return false;
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mMapLocationListener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {
        mMapLocationListener = null;
    }
}

You can set zoom level like following:

map.animateCamera(CameraUpdateFactory.newLatLngZoom(point,15));

Where point is your LatLng position. In this way you can center the map in that point with given zoom level.

Complete method:

@Override
    public void onMapReady(GoogleMap map) {
        map.setLocationSource(this);
        map.setMyLocationEnabled(true);
        map.setOnMyLocationButtonClickListener(this);
        //newLatLngZoom(LatLng , ZoomLevel) -> choose your zoom level
        // and change my 'point' with yours
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(point,15));
    }

EDIT:

If you want to get the dot coords, you can try this:

Location loc = map.getMyLocation();
LatLng point = new LatLng(loc.getlatitude() , loc.getLongitude());

and use that point as center.

Complete method:

@Override
        public void onMapReady(GoogleMap map) {
            map.setLocationSource(this);
            map.setMyLocationEnabled(true);
            map.setOnMyLocationButtonClickListener(this);
            Location loc = map.getMyLocation();
            if(loc != null){
                LatLng point = new LatLng(loc.getLatitude() , loc.getLongitude());
                map.animateCamera(CameraUpdateFactory.newLatLngZoom(point,15));
            }
        }

This could cause a NullPointerException beacuse loc could be null.

OTHER SOLUTION

If you want to get only first time the coordinates, you should work in onLocationChanged , using a boolean variable to set first call.

Declare it CRDS_CALL = false;

  @Override
        public void onLocationChanged(Location location) {
            if (mMapLocationListener != null) {
                mMapLocationListener.onLocationChanged(location);
                if(!CRDS_CALL){
                    LatLng point = new LatLng(location.getLatitude(), location.getLognitude());
                    map.animateCamera(CameraUpdateFactory.newLatLngZoom(point,15));
                    CRDS_CALL = true;
                }
        }
    }

In this answer i use map , but you have to use your mapFragment , but if you want to use it in other methods over onCreate , you have to declare outside of it.

Add this just before the onCreate

SupportMapFragment mapFragment;

And inside it, use it like follwing:

mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.mapView);
        mapFragment.getMapAsync(this);

In that way, you can use mapFragment in other methods

Solution

The solution was to do everything @MikeKeepsOnShine said but remove the

   Location loc = map.getMyLocation();
        LatLng point = new LatLng(loc.getLatitude() , loc.getLongitude());
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(point,15));

part from onMapReady. Works absolutely perfectly now!

You should use this . And you should put this request in onMapReady() callback. Something like this:

@Override
public void onMapReady(GoogleMap map) {
    map.setLocationSource(this);
    map.setMyLocationEnabled(true);
    map.setOnMyLocationButtonClickListener(this);
    map.animateCamera(CameraUpdateFactory.zoomTo(14), 2000, null);
}

you have already done the new "MapAsync" way so you are one step forward to the result. In order to zoom, you can use the animateCamera method for googleMap object to zoom to a specific location: https://developers.google.com/android/reference/com/google/android/gms/maps/GoogleMap.html#animateCamera(com.google.android.gms.maps.CameraUpdate) for example, a zoomin:

map.animateCamera(CameraUpdateFactory.zoomIn());

or if you already know "where":

map.animateCamera(CameraUpdateFactory.newLatLngZoom(knownlocation,17));

and you will be very close to the location. If you need to do at the first "locationUpdate" you should keep a flag to false and set to true the first time you receive a location, at that time you perform the zoom to location.

EDIT: If you want to zoom only the first time, where you receive location updates (which is not really clear from your code), you can do, assuming you have a class variable like:

private boolean FIRST_TIME = true;

the following code:

if(FIRST_TIME){
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(location,17));
FIRST_TIME = false;
}

The best option is to remove the listener but it seems you use location updates as "blue dot" updates.

What worked for me was:

 mMap.setMinZoomPreference(6.0f);
 mMap.setMaxZoomPreference(20.0f);

You can modify the zoom preference values to your taste.

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