【问题标题】:Location on google map in android studio not updatingandroid studio中谷歌地图上的位置未更新
【发布时间】:2021-05-07 21:37:44
【问题描述】:

这是我在 android studio 中的 java 代码:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    FusedLocationProviderClient fusedLocationProviderClient;
    private GoogleMap mMap;
    double lat, lon;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MapsActivity.this);

        if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            getCurrentLocation();
        }else{
            ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
        }}

        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            if (requestCode == 100 && grantResults.length > 0 && (grantResults[0] + grantResults[1] == PackageManager.PERMISSION_GRANTED)){
                getCurrentLocation();
            }
        }

        private void getCurrentLocation() {
            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {


                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
                    @Override
                    public void onComplete(@NonNull Task<Location> task) {
                        Location location = task.getResult();
                        if (location != null) {
                            lat = location.getLatitude();
                            lon = location.getLongitude();
                            Toast.makeText(MapsActivity.this, String.valueOf(lat), Toast.LENGTH_SHORT).show();
                            onMapReady(mMap);
                        } else {
                            LocationRequest locationRequest = new LocationRequest().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                                    .setInterval(3000).setFastestInterval(5000);
                            LocationCallback locationCallback = new LocationCallback() {
                                @Override
                                public void onLocationResult(@NonNull LocationResult locationResult) {
                                    Location location1 = locationResult.getLastLocation();
                                    lat = location1.getLatitude();
                                    lon = location1.getLongitude();
                                    Toast.makeText(MapsActivity.this, String.valueOf(lat), Toast.LENGTH_SHORT).show();
                                    onMapReady(mMap);

                                }
                            };
                            if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                // TODO: Consider calling
                                //    ActivityCompat#requestPermissions
                                // here to request the missing permissions, and then overriding
                                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                //                                          int[] grantResults)
                                // to handle the case where the user grants the permission. See the documentation
                                // for ActivityCompat#requestPermissions for more details.
                                return;
                            }
                            fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
                        }
                    }
                });
            }
        }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        try {
            if(lat != 0.0) {
                LatLng location = new LatLng(lat, lon);
                mMap.addMarker(new MarkerOptions().position(location).title("My location"));
                googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 16));
            }
        }catch (Exception ignored){

        }

    }
}

由于某种原因,这条线:

fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());

不运行。这条线的重点是使查找用户位置的方法每隔几秒钟刷新/更新一次,并在地图上输出位置。但是我只在启动应用程序时才获得位置,并且位置永远不会刷新。我假设这是因为 fusedLocationProviderClient.requestLocationUpdate 行没有运行。

【问题讨论】:

    标签: java android google-maps


    【解决方案1】:

    首先,初始化LocationManager。

    LocationManager locationManager;
    

    其次,通过在 onCreate() 中添加以下行来获取位置服务。

      //get location service
        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    

    最后,通过在 onCreate() 中添加位置和提供者的条件,将 requestLocationUpdates 设置为 locationManager。

    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            // execute when network_provider is enable
            if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                // set requestLocationUpdates with adding time to refresh your location status and distance
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, new LocationListener() {
                    @Override
                    public void onLocationChanged(@NonNull Location location) {
                        if (location.getLatitude() != latitude & location.getLongitude() != longitude) {
                         //put your location code here same as a in getCurrentLocation().
                        }
                    }
                });
            }
            // execute when Gps_provider is enable
            else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                // set requestLocationUpdates with adding time to refresh your location status and distance
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, new LocationListener() {
                    @Override
                    public void onLocationChanged(@NonNull Location location) {
    
                        if (location.getLatitude() != latitude & location.getLongitude() != longitude) {
                            //put your location code here same as a in getCurrentLocation().
                        }
                    }
                });
            } else {
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-09
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 2015-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多