Google Maps Location button (Android Studio) not displayed

Asked

Viewed 915 times

1

I’m developing a native Android app, with the Android Studio IDE, which integrates with the Google Maps API.

I noticed in several videos that when activating the setMyLocation(True) property you should activate the location button (Top direct corner of Activity), but when enabled this property the button is not showing. I have tried several ways to fix the error, but I haven’t found the solution yet.

Details:

  • I am inheriting the Supportmapfragment class.
  • I use Google’s Location API to pick up location.
  • All part of the location is working properly, the only problem is this button that is not displayed.

Source Codes:

  • Map activity (The setMyLocation(true) property is called in the onMapReady event

    public class ActMap extends SupportMapFragment implements 
    OnMapReadyCallback, GoogleMap.OnMapLongClickListener, 
    GoogleApiClient.ConnectionCallbacks,
        LocationListener {
    
    private GoogleMap mMap;
    private GoogleApiClient googleApi;
    private LocationRequest locationRequest;
    private LatLng myLocation;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getMapAsync(this);
    }
    
    @Override
    public void onResume() {
        super.onResume();
    
        if (googleApi != null && googleApi.isConnected()) {
            startLocationUpdate();
        }
    }
    
    @Override
    public void onPause() {
        super.onPause();
    
        if (googleApi != null) {
            stopLocationUpdate();
        }
    }
    
    // Evento principal, após carregar o mapa
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
    
        mMap.setMyLocationEnabled(true);
        setSettingsMap();
        callConenection();
            }
    
    // quando conecta na API Location. O Bandle retorna um objeto location
    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Location location = 
     LocationServices.FusedLocationApi.getLastLocation(googleApi);
    
        if (location != null) {
            myLocation = new LatLng(location.getLatitude(), 
       location.getLongitude());
            moveCameraMyLocation(myLocation);
        }
    
        initLocationRequest();
        startLocationUpdate();
    }
    
    @Override
    public void onConnectionSuspended(int i) {
    
    }
    
    @Override
    public void onMapLongClick(LatLng latLng) {
        createMarker("Click no mapa", latLng);
    }
    
    
    //resultado do location request
    @Override
    public void onLocationChanged(Location location) {
        myLocation = new LatLng(location.getLatitude(), l 
     ocation.getLongitude());
        Toast.makeText(getContext(), "Latitude:" + myLocation.latitude + " 
     Longetude:" + myLocation.longitude, Toast.LENGTH_LONG).show();
     }
    
    //------------ FUNCOES PROPRIAS -----------//
    
    private void moveCameraMyLocation(LatLng latLng) {
        mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
    }
    
    //configurações da requisição da localização que é executada em um 
    intervalo de tempo.
    private void initLocationRequest() {
        locationRequest = new LocationRequest();
        locationRequest.setInterval(10000);//tempo que sera atualizado
        locationRequest.setFastestInterval(5000); // tempo minimo que sera 
    atualiza (caso uma outra APP tentar atualizar dentro esse intervao, o 
    metodo não executa}
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
     // HIGH_ACCURAY é alta precisão (GPS);
    }
    
    //dispara o locationRequest
    private void startLocationUpdate() {
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApi, 
     locationRequest, this);// pegar dados de localização
    }
    
    //Pausa o location request
    private void stopLocationUpdate() {
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApi, 
    this);
    }
    
    //setando configurações iniciais;
    private void setSettingsMap() {
        try {
            mMap.getUiSettings().setZoomControlsEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(true);
            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    
            //Eventos
            mMap.setOnMapLongClickListener(this);
    
    
        } catch (Exception e) {
            Toast.makeText(getContext(), "Erro ao realizar configuração do 
    mapa. Detalhes: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    
    // metodo para criar marcadores
    public void createMarker(String title, LatLng position) {
        MarkerOptions marker = new MarkerOptions();
        marker.title(title);
        marker.position(position);
    
        mMap.addMarker(marker);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(position));
    }
    
    //Conexão com api Location
    private synchronized void callConenection() {
        googleApi = new GoogleApiClient.Builder(getContext())
                .addConnectionCallbacks(this)
                .addApi(LocationServices.API)
                .build();
        googleApi.connect();
    }   
    

    - Layout ():

     <fragment xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:map="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:id="@+id/map"
     android:name="com.google.android.gms.maps.SupportMapFragment"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     tools:context="com.example.joao.deliall.ActMap"
     map:mapType="normal"
     map:uiCompass="true"/>
    
  • Androidmanifest.xml

       <?xml version="1.0" encoding="utf-8"?>
       <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="com.example.joao.deliall">
    
       <uses-permission android:name="android.permission.INTERNET" />
       <uses-permission 
        android:name="android.permission.ACCESS_COARSE_LOCATION" />
       <uses-permission 
       android:name="android.permission.ACCESS_FINE_LOCATION" />
    
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".ActSplashScreen"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ActMain"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ActLogin"
            android:label="@string/title_activity_act_login" />
        <!--
             The API key for Google Maps-based APIs is defined as a string 
          resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to 
          sign the APK.
             You need a different API key for each encryption key, including 
         the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in 
           src/debug/ and src/release/. 
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />
    
        <activity
            android:name=".ActMap"
            android:label="@string/title_activity_act_map"></activity>
          </application>
      </manifest>
    

1 answer

1

Fortunately I found the problem, it is ridiculous of so simple. The detail is that the navbar was covering the button, I put a vertical Linearlayout and solved the problem.

Browser other questions tagged

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