Google Maps v2 - set both my location and zoom in

AndroidApiGoogle MapsGoogle Maps-Api-2

Android Problem Overview


My question is, does anyone know how to set google maps up, to open up both my location and in a zoomed-in view?

Currently, the main view opens up to Africa, all the way zoomed out.

And so I have been searching for days now, and all I can find are:

  1. You cannot animate two things (like zoom in and go to my location) in one google map? So if I can figure out how to set the zoom before I set the animate, then this problem would be solved. That tends to be the issue, you can change one, but not both.

  2. I have found other classes that might be useful, but there is no help on how to set up the code so the class can manipulate the google map.

This is the code I have been holding on to so far, some works, some do not. Some I thought might be useful later on.

package com.MYWEBSITE.www;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;

public class MainActivity extends FragmentActivity {
private GoogleMap map;	

@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main_layout);
	
    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
    map.setMyLocationEnabled(true);
    
	//LocationSource a = (LocationSource) getSystemService(Context.LOCATION_SERVICE);
	//LocationManager b = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    //map.setLocationSource(a);
    
    Criteria criteria = new Criteria();
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    String provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);
    double lat =  location.getLatitude();
    double lng = location.getLongitude();
    LatLng coordinate = new LatLng(lat, lng);
    
    //CameraPosition.Builder x = CameraPosition.builder();
    //x.target(coordinate);
    //x.zoom(13);
    
    //Projection proj = map.getProjection();
    //Point focus = proj.toScreenLocation(coordinate);
    
    //map.animateCamera(CameraUpdateFactory.newLatLng(coordinate));
    map.animateCamera(CameraUpdateFactory.zoomBy(13));
    //map.moveCamera(CameraUpdateFactory.newLatLng(coordinate));
    
    
    ////LatLngBounds bounds = mMap.getProjection().getVisibleRegion().latLngBounds;
}
}

Android Solutions


Solution 1 - Android

> You cannot animate two things (like zoom in and go to my location) in one google map?

From a coding standpoint, you would do them sequentially:

    CameraUpdate center=
        CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044,
                                                 -73.98180484771729));
    CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);

    map.moveCamera(center);
    map.animateCamera(zoom);

Here, I move the camera first, then animate the camera, though both could be animateCamera() calls. Whether GoogleMap consolidates these into a single event, I can't say, as it goes by too fast. :-)

Here is the sample project from which I pulled the above code.


Sorry, this answer is flawed. See Rob's answer for a way to truly do this in one shot, by creating a CameraPosition and then creating a CameraUpdate from that CameraPosition.

Solution 2 - Android

It's possible to change location, zoom, bearing and tilt all in one go. It's also possible to set the duration on the animateCamera() call.

CameraPosition cameraPosition = new CameraPosition.Builder()
    .target(MOUNTAIN_VIEW)      // Sets the center of the map to Mountain View
    .zoom(17)                   // Sets the zoom
    .bearing(90)                // Sets the orientation of the camera to east
    .tilt(30)                   // Sets the tilt of the camera to 30 degrees
    .build();                   // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

Have a look at the docs here:

https://developers.google.com/maps/documentation/android/views?hl=en-US#moving_the_camera

Solution 3 - Android

this is simple solution for your question

LatLng coordinate = new LatLng(lat, lng);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 5);
map.animateCamera(yourLocation);

Solution 4 - Android

Try in this way -

public class SummaryMapActivity extends FragmentActivity implements LocationListener{

 private GoogleMap mMap;
 private LocationManager locationManager;
 private static final long MIN_TIME = 400;
 private static final float MIN_DISTANCE = 1000;

@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.summary_mapview);
	
    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) {
        	mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
        }
    }
    mMap.setMyLocationEnabled(true);
    
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); 
    
    
}

@Override
public void onLocationChanged(Location location) {
	LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15);
    mMap.animateCamera(cameraUpdate);
    locationManager.removeUpdates(this);
	
}

@Override
public void onProviderDisabled(String provider) {
	// TODO Auto-generated method stub
	
}

@Override
public void onProviderEnabled(String provider) {
	// TODO Auto-generated method stub
	
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
	// TODO Auto-generated method stub
	
}

}

Solution 5 - Android

You also could set both parameters like,

mMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(21.000000, -101.400000) ,4) );

This locates your map on a specific position and zoom. I use this on the setting up my map.

Solution 6 - Android

Its a late answer but I think it will help. Use this method:

protected void zoomMapInitial(LatLng finalPlace, LatLng currenLoc) {
    try {
        int padding = 200; // Space (in px) between bounding box edges and view edges (applied to all four sides of the bounding box)
	    LatLngBounds.Builder bc = new LatLngBounds.Builder();
	    
	    bc.include(finalPlace);
	    bc.include(currenLoc);
	    googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bc.build(), padding));
    } catch (Exception e) {
	    e.printStackTrace();
    }
}

Use this method after loading the map. Cheers!

Solution 7 - Android

The simpliest way to do it is to use CancelableCallback. You should check the first action is complete and then call the second:

mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, size.x, height, 0), new CancelableCallback() {
				
				@Override
				public void onFinish() {
					CameraUpdate cu_scroll = CameraUpdateFactory.scrollBy(0, 500);
					mMap.animateCamera(cu_scroll);
				}
				
				@Override
				public void onCancel() {
				}
			});

Solution 8 - Android

@CommonsWare's answer doesn't not actually work. I found that this is working properly :

map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-33.88,151.21), 15));

Solution 9 - Android

1.Add xml code in your layout for displaying maps.

2.Enable google maps api then get api key place that below.

<fragment
                   android:id="@+id/map"
               android:name="com.google.android.gms.maps.MapFragment"
                    android:layout_width="match_parent"
                    android:value="ADD-API-KEY"
                    android:layout_height="250dp"
                    tools:layout="@layout/newmaplayout" />
        <ImageView
            android:id="@+id/transparent_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@color/transparent" />

3.Add this code in oncreate.

 MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(UpadateProfile.this);

4.Add this code after oncreate. then access current location with marker placed in that

@Override
public void onMapReady(GoogleMap rmap) {
    DO WHATEVER YOU WANT WITH GOOGLEMAP
    map = rmap;
    setUpMap();
}
public void setUpMap() {
    map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
  map.setMyLocationEnabled(true);
    map.setTrafficEnabled(true);
    map.setIndoorEnabled(true);
    map.getCameraPosition();
    map.setBuildingsEnabled(true);
    map.getUiSettings().setZoomControlsEnabled(true);
    markerOptions = new MarkerOptions();
    markerOptions.title("Outlet Location");
    map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng point) {
            map.clear();
            markerOptions.position(point);
            map.animateCamera(CameraUpdateFactory.newLatLng(point));
            map.addMarker(markerOptions);
            String all_vals = String.valueOf(point);
            String[] separated = all_vals.split(":");
            String latlng[] = separated[1].split(",");
            MyLat = Double.parseDouble(latlng[0].trim().substring(1));
            MyLong = Double.parseDouble(latlng[1].substring(0,latlng[1].length()-1));
            markerOptions.title("Outlet Location");
            getLocation(MyLat,MyLong);
        }
    });
}
public void getLocation(double lat, double lng) {
    Geocoder geocoder = new Geocoder(UpadateProfile.this, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
   } catch (IOException e) {
         TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(this,e.getMessage(),Toast.LENGTH_SHORT).show();
    }
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}

Solution 10 - Android

You cannot animate two things (like zoom in and go to my location) in one google map.
So use move and animate Camera to zoom

googleMapVar.moveCamera(CameraUpdateFactory.newLatLng(LocLtdLgdVar));
googleMapVar.animateCamera(CameraUpdateFactory.zoomTo(10));

Solution 11 - Android

gmap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(9.491327, 76.571404), 10, 30, 0)));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDustinView Question on Stackoverflow
Solution 1 - AndroidCommonsWareView Answer on Stackoverflow
Solution 2 - AndroidRobView Answer on Stackoverflow
Solution 3 - AndroidHusnain AliView Answer on Stackoverflow
Solution 4 - AndroidKhobaibView Answer on Stackoverflow
Solution 5 - AndroidorganilleroView Answer on Stackoverflow
Solution 6 - AndroidAbxView Answer on Stackoverflow
Solution 7 - AndroidYuliya TarasenkoView Answer on Stackoverflow
Solution 8 - AndroidiMahdiView Answer on Stackoverflow
Solution 9 - AndroidVenkateshView Answer on Stackoverflow
Solution 10 - AndroidSujay U NView Answer on Stackoverflow
Solution 11 - AndroidzachariaView Answer on Stackoverflow