I'm trying to mess around with the Maps API V2 to get more familiar with it, and I'm trying to start the map centered at the user's current location. Using the map.setMyLocationEnabled(true);
statement, I am able to show my current location on the map. This also adds the button to the UI that centers the map on my current location.
I want to simulate that button press in my code. I am familiar with the LocationManager
and LocationListener
classes and realize that using those is a viable alternative, but the functionality to center and zoom in on the user's location seems to already be built in through the button.
If the API has a method to show the user's current location, there surely must be an easier way to center on the location than to use the LocationManager
/LocationListener
classes, right?
Users can zoom the map by clicking the zoom controls. They can also zoom and pan by using two-finger movements on the map for touchscreen devices.
Maps API getZoom() Method The getZoom() method returns the current zoom level of the map.
Try this coding:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false)); if (location != null) { map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13)); CameraPosition cameraPosition = new CameraPosition.Builder() .target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user .zoom(17) // Sets the zoom .bearing(90) // Sets the orientation of the camera to east .tilt(40) // Sets the tilt of the camera to 30 degrees .build(); // Creates a CameraPosition from the builder map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); }
After you instansiated the map object (from the fragment) add this -
private void centerMapOnMyLocation() { map.setMyLocationEnabled(true); location = map.getMyLocation(); if (location != null) { myLocation = new LatLng(location.getLatitude(), location.getLongitude()); } map.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation, Constants.MAP_ZOOM)); }
if you need any guidance just ask but it should be self explantory - just instansiate the myLocation object for a default one...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With