Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I let google maps api v2 go directly to my location

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...

like image 839
Emver Avatar asked Jan 21 '13 15:01

Emver


1 Answers

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!"));
}
like image 121
user2307955 Avatar answered Nov 15 '22 10:11

user2307955