Google地图未显示用户当前位置

我正在尝试在我的android应用程序上显示用户的当前位置。我尝试在Android 6.0手机上测试该应用程序。但是,单击Google Maps活动右上角的按钮后,屏幕上没有任何反应。下面是我的Mapsactivity Java代码。

package com.example.nibebe;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.activityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragmentactivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnmapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;

import static com.google.android.gms.common.api.GoogleApiClient.*;

public class Mapsactivity extends Fragmentactivity implements
        OnmapReadyCallback,GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,com.google.android.gms.location.LocationListener {

    private GoogleMap mMap;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    LocationRequest mLocationRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

    }

    @Override
    public void onmapReady(GoogleMap googleMap) {
        mMap = googleMap;


        // Add a marker in Sydney and move the camera
        // LatLng sydney = new LatLng(-34,151);
        //mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        // mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }

    protected synchronized void buildGoogleApiClient()
    {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        mGoogleApiClient.connect();

    }
    @Override
    public void onLocationChanged(Location location) {

        mLastLocation = location;

        LatLng latLng= new LatLng(location.getLatitude(),location.getLongitude());

        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

    }



    @Override
    public void onConnected(@Nullable Bundle bundle) {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setfastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
        // LocationSettingsRequest.Builder builder= new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);

        // LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    protected void onStop() {
        super.onStop();

    }
}

下面是我的AndroidManifest.xml文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.nibebe">
    <uses-permission android:name="android.permission.accESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET" />

    <!--
         The accESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2,but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->
    <uses-permission android:name="android.permission.accESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.accESS_COARSE_LOCATION"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_car"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsrtl="true"
        android:theme="@style/Apptheme">

        <!--
             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/.
        -->
        <activity
            android:name=".Mapsactivity"
            android:label="@string/title_activity_maps"></activity>

        <activity android:name=".Mainactivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />
    </application>


</manifest>

我希望在点击该按钮时,地图会移动并显示一个标记。

提前谢谢!

cersga1215 回答:Google地图未显示用户当前位置

您可以使用以下示例代码添加标记

此处Google developer Documentation - Adding a Map with a marker

解释了此代码

-编辑-

使用此文档Get the last known location

,以获取当前位置AKA的最后一个已知位置。
fusedLocationClient.getLastLocation()
  .addOnSuccessListener(this,new OnSuccessListener<Location>() {
      @Override
      public void onSuccess(Location location) {
          // Got last known location. In some rare situations this can be null.
          if (location != null) {
              //pass the two parameter
              LatLng sydney = new LatLng(location.getLatitude(),location.getLongitude());
              googleMap.addMarker(new MarkerOptions().position(sydney)
              .title("Marker in My current location"));
              googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
          }
      }
  });
,

最好使用FusedLocationProviderApi

Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

本文链接:https://www.f2er.com/3169004.html

大家都在问