Pages

Monday, December 31, 2012

Move map to my location - Google Maps Android API v2

On request, here's a very small tutorial on how to move the map to your location in the new API.
Have a look at this code:

private void moveMapToMyLocation() {

  LocationManager locMan = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);

  Criteria crit = new Criteria();

  Location loc = locMan.getLastKnownLocation(locMan.getBestProvider(crit, false));

  

  CameraPosition camPos = new CameraPosition.Builder()

   .target(new LatLng(loc.getLatitude(), loc.getLongitude()))

   .zoom(12.8f)

   .build();

  CameraUpdate camUpdate = CameraUpdateFactory.newCameraPosition(camPos);

  getMap().moveCamera(camUpdate);

  

 }

This is a method I made, you can place it somewhere in your custom MapFragment or in your Activity.

It's important to call this moment at the right time. We have to make sure that the map is loaded before we ask it to move to somewhere else:

  • in custom MapFragment: call the method somewhere in onActivityCreated(Bundle)
  • in Activity: call the method somewhere in onStart()
Moving the camera (your view of the map) around is possible by making a CameraPosition object, and using that to make the right CameraUpdate object.

Once we have our CameraUpdate object, we can choose to use moveCamera(CameraUpdate) or animateCamera(CameraUpdate). With moveCamera, the view will instantly change and with animateCamera you'll see the map moving on the screen towards the destination that we want. There are multiple arguments possible for these methods, please check the android API here for more information.

Good luck!

7 comments:

  1. Hi, I thing you can do it shorter and readable :).

    This should have the same effect:

    getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 12.8f));

    ReplyDelete
    Replies
    1. Indeed, I just showed it like this so people would get to know the CameraPosition class. There are more things you can add such as 'bearing' and 'tilt'. I didn't use this in this example.

      Delete
  2. Find all latest mobile phone, smartphone, android phone,tab,all mobile phone review, latest technology, feature phone etc.


    https://mobilebaazar24.blogspot.com

    https://mobilebaazar24.blogspot.com/2020/06/oppo-a9-mobile-price-in-bangladesh.html#more

    https://mobilebaazar24.blogspot.com/2020/05/vivo-v19-pro-mobile-price-in-bangladesh.html

    https://mobilebaazar24.blogspot.com/2020/06/oppo-f15-mobile-price-in-bangladesh.html#more

    ReplyDelete