[android] Google Maps v2 - set both my location and zoom in

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

This question is related to android api google-maps google-maps-api-2

The answer is


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!


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.


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

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

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

}

}


@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));

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) {
}

this is simple solution for your question

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

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

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


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to api

I am receiving warning in Facebook Application using PHP SDK Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file Failed to load resource: the server responded with a status of 404 (Not Found) css Call another rest api from my server in Spring-Boot How to send custom headers with requests in Swagger UI? This page didn't load Google Maps correctly. See the JavaScript console for technical details How can I send a Firebase Cloud Messaging notification without use the Firebase Console? Allow Access-Control-Allow-Origin header using HTML5 fetch API How to send an HTTP request with a header parameter? Laravel 5.1 API Enable Cors

Examples related to google-maps

GoogleMaps API KEY for testing Google Maps shows "For development purposes only" java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion How to import JSON File into a TypeScript file? Googlemaps API Key for Localhost Getting "Cannot call a class as a function" in my React Project ERROR: Google Maps API error: MissingKeyMapError This page didn't load Google Maps correctly. See the JavaScript console for technical details Google Maps API warning: NoApiKeys ApiNotActivatedMapError for simple html page using google-places-api

Examples related to google-maps-api-2

Android map v2 zoom to show all the markers Find distance between two points on map using Google Map API V2 Google Maps v2 - set both my location and zoom in Set Google Maps Container DIV width and height 100% Add Marker function with Google Maps API How can I change the color of a Google Maps marker?