Google maps android already open looking current position [closed]

0

I would like help to get google maps from my android application already look for the current position of the user as soon as the map is opened, in the same way as traditional gps, such as waze, to have to click on any button for this .

And along with that, if it is possible to make the map already open with some zoom. Because if the user is not connected with gps or wifi, the map at least already showing the state of São Paulo instead of being without zoom as is the default. Thank you.

    
asked by anonymous 31.08.2016 / 08:18

2 answers

1

To open your map in a specific place you can use:

 CameraPosition cameraPosition = new CameraPosition.Builder()
        .target(new LatLng(-23.572847, -46.629716))      // Define o centro do mapa para localização do usuário em São Paulo
        .zoom(17)                   // Define zoom
        .bearing(90)                // Define a orientação da câmera para leste
        .tilt(30)                   // Define a inclinação da câmara para 30 graus
        .build();                   // define uma posição da câmera do construtor
    map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));  

In order for your location to be captured, you can follow this my answer in another question. After the implementation, for you to open the map without having to click any button, you will insert this code below into your onCreate :

        if (GetLocalization(this)) {
            if (ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(Main.this,
                            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                return;
            }
            Location location = LocationServices.FusedLocationApi.getLastLocation(mapGoogleApiClient);
            if (location != null) {
                edtLat.setText(String.valueOf(location.getLatitude()));
                edtLog.setText(String.valueOf(location.getLongitude()));
            } else {
                showSettingsAlert();
            }
        }

Redirection to settings if GPS is disabled:

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS");

        // Setting Dialog Message
        alertDialog.setMessage("GPS não está habilitado. Você deseja configura-lo?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

Details

31.08.2016 / 14:31
0

See if the example helps, I just do not know how to make the emulator work.

** In AndroidManifest.XML add

   <uses-permission android:name="android.permission.INTERNET"/>
   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

** Gradle script (Module app) dependences add

   compile 'com.google.android.gms:play-services-maps:9.4.0'
   compile 'com.google.android.gms:play-services-location:9.4.0'

**

//-------------------------------------

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback
{

  protected GoogleMap m_map;

  //-----------------------------------

  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

    mapFragment.getMapAsync(this);
  }

  //-----------------------------------

  @Override
  public void onMapReady(GoogleMap googleMap)
  {
    m_map = googleMap;

    m_map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    UiSettings ui = m_map.getUiSettings();

    ui.setZoomControlsEnabled(true);

    try {
      checkCnn();
      checkGps();

      new MyLocation().execute();
    }
    catch (Exception e) {
      // Tratar error

      Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show();

      e.printStackTrace();
    }
  }

  //-----------------------------------

  public void checkCnn() throws Exception
  {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

    if (activeNetwork == null) {
      throw new Exception("wi-fi off");
    }
  }

  //-----------------------------------

  public void checkGps() throws Exception
  {
    LocationManager manager;

    manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
      throw new Exception("gps off");
    }
  }

  //-----------------------------------

  protected class MyLocation implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
  {
    private GoogleApiClient m_api;

    //---------------------------------

    public MyLocation()
    {
      super();
    }

    //---------------------------------

    protected void execute()
    {
      m_api = new GoogleApiClient.Builder(MainActivity.this)
                      .addConnectionCallbacks(this)
                      .addOnConnectionFailedListener(this)
                      .addApi(LocationServices.API)
                      .build();

      m_api.connect();
    }

    //-----------------------------------

    @Override
    public void onConnected(Bundle bundle)
    {
      LatLng latLng = location();

      m_map.addMarker(new MarkerOptions().position(latLng));
      m_map.animateCamera(cameraPosition(latLng,15,0,0));
      //m_map.moveCamera(cameraPosition(latLng,15,0,0));

      m_api.disconnect();
    }

    //---------------------------------

    @Override
    public void onConnectionSuspended(int i)
    {
    }

    //---------------------------------

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult)
    {
    }

    //---------------------------------

    public CameraUpdate cameraPosition(LatLng latLng, float zoom, float tilt, float bearing)
    {
      CameraPosition.Builder builder = new CameraPosition.Builder();

      CameraPosition position = builder.target(latLng)
                                        .zoom(zoom)
                                        .tilt(tilt)
                                        .bearing(bearing)
                                        .build();

      return CameraUpdateFactory.newCameraPosition(position);
    }

    //---------------------------------

    public LatLng location()
    {
      Location loc = LocationServices.FusedLocationApi.getLastLocation(m_api);

      return new LatLng(loc.getLatitude(),loc.getLongitude());
    }

    //-----------------------------------

  } // end MyLocation

  //-----------------------------------

} // end class

//-------------------------------------
    
31.08.2016 / 15:47