在 android 中识别用户位置

Identify user location in android

我是 android 的初学者,我正在尽最大努力学习 android。我正在尝试创建一个 android 应用程序来使用 google 地图识别用户位置。但是我能够识别用户的位置,但不是我预期的那样。

如下图所示,它显示了一个默认位置。单击左上角的按钮后,地图会显示我的位置。

我想立即知道我的位置,而无需单击按钮。另外我想知道用户位置并将其存储在字符串中,而不是经度和纬度值。有帮助吗?

代码:

package com.example.lalinda.googlemap1;

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;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @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;
        mMap.setMyLocationEnabled(true);
    }
}

Google 地图使用用户的 lastKnownLocation 作为位置,如果 lastknownLocation 未知,则需要时间通过不同的提供商获取位置,例如 GPSNetwork.我建议使用 lastKnownLocation 作为基本位置并使用 LocationListener 更新它。

       @Override
       public void onMapReady(GoogleMap googleMap) { 
       if (ActivityCompat.checkSelfPermission
                (this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                &&
                ActivityCompat.checkSelfPermission
                        (this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            requestPermissions(new String[]{
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
            }, 1);

        }
        else {

            // enable location buttons
            googleMap.setMyLocationEnabled(true);
            googleMap.getUiSettings().setMyLocationButtonEnabled(true);

            // fetch last location if any from provider - GPS.
            final LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            final Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            //if last known location is not available
            if (loc == null) {

                final LocationListener locationListener = new LocationListener() {
                    @Override
                    public void onLocationChanged(final Location location) {
                        clearMap(googleMap); // clear map for every new location to update your marker unless `n` number of markers will form.
                        // getting location of user
                        final double latitude = location.getLatitude();
                        final double longitude = location.getLongitude();
                        final LatLng userCurrentLocation = new LatLng(latitude, longitude);
                        //focus added here **edited**
    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userCurrentLocation, 14));

                        googleMap.addMarker(new MarkerOptions()
                       .position(userCurrentLocation)
                       .draggable(true)
       .icon(BitmapDescriptorFactory.fromResource(R.drawable.your_marker_icon_from_deawable)));
                        //do something with Lat and Lng, Parse to String if u want or set marker.

                    }

                    @Override
                    public void onStatusChanged(String provider, int status, Bundle extras) {
                    }

                    @Override
                    public void onProviderEnabled(String provider) {
                        //when user enables the GPS setting, this method is triggered.
                    }

                    @Override
                    public void onProviderDisabled(String provider) {
                        //when no provider is available in this case GPS provider, trigger your gpsDialog here.
                    }
                };

                //update location every 10sec in 500m radius with both provider GPS and Network.

            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10*1000, 500, locationListener);
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 500, locationListener);
            }
            else {
                //do something with last known location.
                // getting location of user
                final double latitude = loc.getLatitude();
                final double longitude = loc.getLongitude();
                final LatLng userCurrentLocation = new LatLng(latitude, longitude);

                //focus added here **edited**
    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userCurrentLocation, 14));

                googleMap.addMarker(new MarkerOptions()
                .position(userCurrentLocation)
                .draggable(true)
       .icon(BitmapDescriptorFactory.fromResource(R.drawable.your_marker_icon_from_deawable)));
            }
           }
        }

权限处理:

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

        case 1:
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED){
                //do something
            }
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

这个例子只是为了演示(示例目的),我没有使用方法优化我的代码。请日后编辑。