Google 地图在用户没有最近位置时无法获取用户位置。

huangapple go评论89阅读模式
英文:

Google maps does not get the user location if the user does not have a recent location

问题

我遇到了一个问题,当获取用户当前位置时,如果用户没有最近的位置信息,地图无法找到当前位置。但是,如果我允许其他应用程序访问位置信息,然后回到我的应用程序,地图就能够看到当前位置了。

我尝试编写了另一个用于获取当前位置的代码,因为我目前正在使用的代码已经不建议使用了。当我运行应用程序时,它无法获取用户的当前位置,但如果我在其他应用程序中有最近的位置信息,我的应用程序就能够获取用户的位置。以下是我的代码:

public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    public static int LOCATION_REQUEST_CODE = 100;

    FusedLocationProviderClient fusedLocationProviderClient;

    private final LatLng MarisolTerminal = new LatLng(15.1519204,120.4476555);
    private final LatLng VillaTerminal = new LatLng(15.1268318,120.5974806);
    private final LatLng CheckpointTerminal = new LatLng(15.169206,120.5872296);

    private Marker markerMarisolTerm;
    private Marker markerVillaTerminal;
    private Marker markerCheckpointTerminal;

    private LocationCallback locationCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        if (mapFragment != null) {
            mapFragment.getMapAsync(this);
        }

        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        checkLocationPermission();
    }

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

        mMap.getUiSettings().setMyLocationButtonEnabled(true);

        mMap.setMapStyle(
                MapStyleOptions.loadRawResourceStyle(this,R.raw.custom_map_style)
        );

        // 添加一些地图标记,并为每个标记添加数据对象。
        markerMarisolTerm = mMap.addMarker(new MarkerOptions()
                .position(MarisolTerminal)
                .title("Marisol Terminal")
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.marisol)));
        markerMarisolTerm.setTag(0);

        markerVillaTerminal = mMap.addMarker(new MarkerOptions()
                .position(VillaTerminal)
                .title("Villa Terminal")
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.villa)));
        markerVillaTerminal.setTag(0);

        markerCheckpointTerminal = mMap.addMarker(new MarkerOptions()
                .position(CheckpointTerminal)
                .title("Checkpoint Terminal")
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.checkpoint)));
        markerCheckpointTerminal.setTag(0);
    }

    private void checkLocationPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            getUserLocation();
        } else {
            requestForPermission();
        }
    }

    private void getUserLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Task<Location> task = fusedLocationProviderClient.getLastLocation();
        task.addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if (location != null) {
                    double lat = location.getLatitude();
                    double longitude = location.getLongitude();
                    LatLng userLocation = new LatLng(lat, longitude);
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
                    mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
                    mMap.addMarker(new MarkerOptions().position(userLocation).title("I am here"));
                }
            }
        });
    }

    private void requestForPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Permission Accepted", Toast.LENGTH_SHORT).show();
                getUserLocation();
            } else {
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

如果您有任何关于这段代码的问题,请随时提出。

英文:

I have encountered a problem when getting the users current location if the user does not have any recent location the map cannot find the current location but if I allow other apps on location then going back to my application the map can now see the current location.

I tried doing another code for the current location because the one that I am currently using is deprecated, when I run the application it does not get the users current location but if I have a recent location using other application my app can now get the user location, . Here is my code.

public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    public static int LOCATION_REQUEST_CODE = 100;

    FusedLocationProviderClient fusedLocationProviderClient;

    private final LatLng MarisolTerminal = new LatLng(15.1519204,120.4476555);
    private final LatLng VillaTerminal = new LatLng(15.1268318,120.5974806);
    private final LatLng CheckpointTerminal = new LatLng(15.169206,120.5872296);

    private Marker markerMarisolTerm;
    private Marker markerVillaTerminal;
    private Marker markerCheckpointTerminal;

    private LocationCallback locationCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);



        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        if (mapFragment != null) {
            mapFragment.getMapAsync(this);
        }

        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        checkLocationPermission();

    }



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

        mMap.getUiSettings().setMyLocationButtonEnabled(true);

        mMap.setMapStyle(
                MapStyleOptions.loadRawResourceStyle(this,R.raw.custom_map_style)
        );





        // Add some markers to the map, and add a data object to each marker.
        markerMarisolTerm = mMap.addMarker(new MarkerOptions()
                .position(MarisolTerminal)
                .title(&quot;Marisol Terminal&quot;)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.marisol)));
        markerMarisolTerm.setTag(0);

        markerVillaTerminal = mMap.addMarker(new MarkerOptions()
                .position(VillaTerminal)
                .title(&quot;Villa Terminal&quot;)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.villa)));
        markerVillaTerminal.setTag(0);

        markerCheckpointTerminal = mMap.addMarker(new MarkerOptions()
                .position(CheckpointTerminal)
                .title(&quot;Checkpoint Terminal&quot;)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.checkpoint)));
        markerCheckpointTerminal.setTag(0);


    }


    private void checkLocationPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                &amp;&amp; ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            getUserLocation();


        } else {
            requestForPermission();
        }


    }

    private void getUserLocation() {

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &amp;&amp; ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        Task&lt;Location&gt; task = fusedLocationProviderClient.getLastLocation();

        task.addOnSuccessListener(new OnSuccessListener&lt;Location&gt;() {
            @Override
            public void onSuccess(Location location) {

                if (location !=null){

                    double lat = location.getLatitude();
                    double longitude = location.getLongitude();

                    LatLng userLocation = new LatLng(lat, longitude);


                    mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
                    mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
                    mMap.addMarker(new MarkerOptions().position(userLocation).title(&quot;I am here&quot;));
                }

            }
        });
    }

    private void requestForPermission(){
        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},LOCATION_REQUEST_CODE);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == LOCATION_REQUEST_CODE){
            if (grantResults [0] == PackageManager.PERMISSION_GRANTED){
                Toast.makeText(this, &quot;Permission Accepted&quot;, Toast.LENGTH_SHORT).show();
                getUserLocation();
            }else {
                Toast.makeText(this,&quot;Permission Denied&quot; , Toast.LENGTH_SHORT).show();
            }
        }

    }

答案1

得分: 1

getLastLocation 只有在位置子系统已经有数据时才会返回结果。它不会启动位置子系统。几乎不应该使用它。请使用 getCurrentLocation 或 requestLocationUpdates,它们都会启动位置子系统。

英文:

getLastLocation only returns a result if the Location subsystem already has data. It does not start the location subsystem. It should almost never be used. Use getCurrentLocation or requestLocationUpdates, both of which will start the location subsystem instead.

huangapple
  • 本文由 发表于 2023年8月4日 20:47:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76836062.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定