6

I am a real Google Maps API noob, so any help is appreciated. What I want to see here is that when I open my app, the camera needs to move directly to my current location and place the blue dot. How do I manage to do that?

I have made an example code so that everyone can understand it and implement to their code when needed:

GoogleMap map = ((SupportMapFragment)  getSupportFragmentManager().findFragmentById(R.id.general_map)).getMap();
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);

if( helper.isGPSEnabled() ){
    map.move... // move directly to my current position
}

Help please...

Emver
  • 61
  • 1
  • 1
  • 3

2 Answers2

28

Here's what I was able to get working. It displays your current location and puts a marker there. This is for Google Maps API v2

private void setUpMap() {
    // Enable MyLocation Layer of Google Map
    googleMap.setMyLocationEnabled(true);

    // Get LocationManager object from System Service LOCATION_SERVICE
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    // Create a criteria object to retrieve provider
    Criteria criteria = new Criteria();

    // Get the name of the best provider
    String provider = locationManager.getBestProvider(criteria, true);

    // Get Current Location
    Location myLocation = locationManager.getLastKnownLocation(provider);

    //set map type
    googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    // Get latitude of the current location
    double latitude = myLocation.getLatitude();

    // Get longitude of the current location
    double longitude = myLocation.getLongitude();

    // Create a LatLng object for the current location
    LatLng latLng = new LatLng(latitude, longitude);      

    // Show the current location in Google Map        
    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    // Zoom in the Google Map
    googleMap.animateCamera(CameraUpdateFactory.zoomTo(20));
    googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!"));
}
user2307955
  • 281
  • 3
  • 3
  • 4
    on Location myLocation = locationManager.getLastKnownLocation(provider); myLocation is null, any idea? – ALi Jul 24 '13 at 08:59
  • it is not working!! all i get is this : The Google Play services resources were not found. Check your project configuration to ensure that the resources are included. – Cyph3rCod3r Sep 24 '13 at 07:24
0

You need to first determine the user his location. After that you set your latitude and longitude on the map. Also don't forget to set the zoom level to zoom in on your map.

To determine if the gps is enabled:

How do I find out if the GPS of an Android device is enabled

Android - Is there a way to listen if GPS was enabled or disabled

More information about location strategies:

http://developer.android.com/guide/topics/location/strategies.html

Community
  • 1
  • 1
Vince V.
  • 3,115
  • 3
  • 30
  • 45