GoogleMap.getMyLocation() 返回 null

Posted

技术标签:

【中文标题】GoogleMap.getMyLocation() 返回 null【英文标题】:GoogleMap.getMyLocation() returns null 【发布时间】:2016-03-02 04:05:38 【问题描述】:

我正在尝试放大用户在地图上的当前位置。该位置绝对可以访问,因为它在地图上显示为蓝点

但是,GoogleMap.getMyLocation() 返回 null。

为了启用位置数据,我遵循Google documentation 并在我的清单中添加了适当的权限,此外还添加了必要的 API 密钥。

如果对我的 MyActivity.java 有帮助的话:

package com.example.beckah.helloworld;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.Location;
import android.location.LocationListener;
import android.content.Context;
import android.location.LocationManager;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback 

    private GoogleMap mMap;
    private LatLng location;
    Location mLocation;
    LocationManager locationManager;

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


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) 
        mMap = googleMap;

        mMap.setMyLocationEnabled(true);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        mLocation = googleMap.getMyLocation();


        if(mLocation != null) location = new LatLng(mLocation.getLatitude(), mLocation.getLongitude());
        else location = new LatLng(31, 31);

        mMap.addMarker(new MarkerOptions().position(location).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(location));


    

我的清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.beckah.helloworld">

    <!--
         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.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_GPS" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <permission android:name="com.example.beckah.helloworld.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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/. 
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

如何确保 GoogleMap.getMyLocation() 不返回 null 并且能够获取位置数据?

【问题讨论】:

该方法已弃用:developers.google.com/android/reference/com/google/android/gms/… 看看这个答案中的代码:***.com/a/30255219/4409409 【参考方案1】:

以下代码应该适用于用户的最后一个已知位置

LocationManager service = (LocationManager) 

getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
Location location = service.getLastKnownLocation(provider);
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());

【讨论】:

我第一次得到位置空值,你能告诉我当我第一次启动我的应用程序时在创建时如何处理当前位置吗?【参考方案2】:

尝试将此方法添加到您的代码中以找到最后一个已知位置:

private Location getMyLocation() 
    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (myLocation == null) 
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        String provider = lm.getBestProvider(criteria, true);
        myLocation = lm.getLastKnownLocation(provider);
    
    return myLocation;

然后替换

mLocation = googleMap.getMyLocation();

mLocation = getMyLocation();

【讨论】:

以上是关于GoogleMap.getMyLocation() 返回 null的主要内容,如果未能解决你的问题,请参考以下文章