Google maps android already open looking for current position

Asked

Viewed 1,108 times

0

I would like help to get google maps of my android application already look for the current position of the user once the map is opened, in the same way as traditional gps, like Waze, be have q click some button for this.

And in conjunction 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 was already showing the state of São Paulo instead of being without any zoom as is the default. Thank you.

  • Use this answer I put in another question! It will help you soon!

  • You are running the application on the emulator or on a device via USB?

  • On the same cell phone

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));  

To capture your location, you can follow this my answer on another question. After the implementation, for you to already 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();
            }
        }

Redirect 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

  • Hello friend. First thank you. I’m trying to implement the explanation you gave in the other post, using Locationmanager ...but on line " if (Activitycompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION)...." This part of "ACESS_FINE_LOCATION" and COURSE LOCATION appears as an error. Do you know what I can do to fix it? Permissions are already released in my Manifest file. Thank you.

  • @Omnislade What the mistake?

  • It is in red, as if I had not released the permissions in my Manifest file, but they are already released.

  • @Omnislade turns red in class or XML?

  • Buddy, it worked. I had to give him a clear on the project to make him normal. However, I still have a single problem with the "showSettingsAlert();" command. It appears as "Cannot resolve method", some suggestion?

  • It is possible instead of me having to click the button that was created there in main, the "btLocation" I can click the button that is created by the ". setMyLocationEnabled(true)" to do the same thing?

  • @Omnislade that showSettingsAlert() is just down there in the project. It serves to when your GPS is off, redirect you to the settings for you enable. As for setMyLocalizationEnabled(true), I believe so.

  • So .. plus this "shoSettingAlert()" is giving error when I write it. And I’ll see if I can put in setMyLocalizationEnable this button function, because I don’t have boot or editext in my project, only open the map directly with the location.

  • @Omnislade you will achieve using mMap.setOnMyLocationButtonClickListener.

  • I’m working here to get everything OK, but I still could not arrange the part of showSettingsAlert(). I need to implement something for this code to work?

  • @Omnislade edited the answer and added the showSettingsAlert().. Hugs

  • Thank you very much. I’m going to test here more is just what I need.

Show 7 more comments

0

See if the example helps, just do not know how to run emulator.

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

//-------------------------------------
  • I’ll try here and make you a friend.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.