ANDROID - 谷歌地图获取当前位置

Posted

技术标签:

【中文标题】ANDROID - 谷歌地图获取当前位置【英文标题】:ANDROID - Google maps get current location 【发布时间】:2021-09-11 19:04:29 【问题描述】:

我正在开发一个应用程序,我需要在地图上显示我的当前位置。不幸的是,我遇到了错误:

第 53 行:

E/androidRuntime: FATAL EXCEPTION: main
    Process: com.vojtechadam.mcdonaldscoupons, PID: 8329
    java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
        at com.example.mcdonaldscoupons.MapFragment.onMapReady(MapFragment.java:53)
        at com.google.android.gms.maps.zzat.zzb(com.google.android.gms:play-services-maps@@17.0.1:1)
        at com.google.android.gms.maps.internal.zzaq.zza(com.google.android.gms:play-services-maps@@17.0.1:6)
        at com.google.android.gms.internal.maps.zzb.onTransact(com.google.android.gms:play-services-maps@@17.0.1:3)
        at android.os.Binder.transact(Binder.java:1043)
        at dp.aZ(:com.google.android.gms.dynamite_mapsdynamite@212116097@21.21.16 (150400-0):2)
        at com.google.maps.api.android.lib6.impl.bk.run(:com.google.android.gms.dynamite_mapsdynamite@212116097@21.21.16 (150400-0):1)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:236)
        at android.app.ActivityThread.main(ActivityThread.java:7861)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:600)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
I/Process: Sending signal. PID: 8329 SIG: 9

我的 onRequestPermissionResult 也不起作用...我想在从 navigation_drawer 中单击我的地图片段时向位置发送请求,但它说这个

第 80 行:覆盖 'androidx.fragment.app.Fragment' 中已弃用的方法

第 81 行: 'onRequestPermissionsResult(int, java.lang.String[], int[])' 已弃用

MapFragment.java

public class MapFragment extends Fragment implements OnMapReadyCallback 
    Location currentLocation;
    FusedLocationProviderClient fusedLocationProviderClient;
    private static final int REQUEST_CODE = 101;

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) 
        return inflater.inflate(R.layout.fragment_map, container, false);
    

    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) 
        super.onViewCreated(view, savedInstanceState);
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
        fetchLastLocation();
        SupportMapFragment supportMapFragment = (SupportMapFragment)
                getChildFragmentManager().findFragmentById(R.id.google_map);
        supportMapFragment.getMapAsync(this);
    

    @Override
    public void onMapReady(GoogleMap googleMap) 
        LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions().position(latLng)
                .title("Here I am!");
        googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5));
        googleMap.addMarker(markerOptions);
    

    private void fetchLastLocation() 
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
            ActivityCompat.requestPermissions(getActivity(), new String[]
                    Manifest.permission.ACCESS_FINE_LOCATION, REQUEST_CODE);
            return;
        
        Task<Location> task = fusedLocationProviderClient.getLastLocation();
        task.addOnSuccessListener(location -> 
            if (location != null) 
                currentLocation = location;
                Toast.makeText(getContext(), currentLocation.getLatitude()
                        + "" + currentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
                SupportMapFragment supportMapFragment = (SupportMapFragment)
                        getChildFragmentManager().findFragmentById(R.id.google_map);
                supportMapFragment.getMapAsync(MapFragment.this);
            
        );
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults) 
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) 
            case REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) 
                    fetchLastLocation();
                
                break;
        
    

【问题讨论】:

【参考方案1】:

您正在设置您当前的位置标记 onReady。但是您应该在获取位置后执行此操作。检查下面的代码。

   private GoogleMap googleMap;


    @Override
    public void onMapReady(GoogleMap googleMap) 
      this.googleMap = googlemap;

    

private void fetchLastLocation() 
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
            ActivityCompat.requestPermissions(getActivity(), new String[]
                    Manifest.permission.ACCESS_FINE_LOCATION, REQUEST_CODE);
            return;
        
        Task<Location> task = fusedLocationProviderClient.getLastLocation();
        task.addOnSuccessListener(location -> 
            if (location != null) 
                currentLocation = location;
                UpdateCurrentLocation();
                Toast.makeText(getContext(), currentLocation.getLatitude()
                        + "" + currentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
                SupportMapFragment supportMapFragment = (SupportMapFragment)
                        getChildFragmentManager().findFragmentById(R.id.google_map);
                supportMapFragment.getMapAsync(MapFragment.this);
            
        );
    

private void UpdateCurrentLocation() 
    LatLng latLng = new LatLng(currentLocation.getLatitude(), 
    currentLocation.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions().position(latLng)
                .title("Here I am!");
        googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5));
        googleMap.addMarker(markerOptions);

【讨论】:

以上是关于ANDROID - 谷歌地图获取当前位置的主要内容,如果未能解决你的问题,请参考以下文章

打开android原生谷歌地图应用程序获取从当前位置开始的方向

Android:使用谷歌地图实时获取当前坐标

如何在谷歌地图android中显示当前位置的平滑移动

谷歌地图查找当前位置和附近的地方

Android 谷歌地图使用 GPS 定位而不是网络

当前位置的问题 android 谷歌地图