【问题标题】:How do I get my current location and get latitude and longitude as string?如何获取当前位置并将纬度和经度作为字符串?
【发布时间】:2020-08-14 04:28:20
【问题描述】:

我正在学习一个教程并尝试使用 Google 地图获取我的当前位置,但我在 LatLng 处遇到错误,它说“尝试调用虚拟方法和空对象引用”。我想获取我当前的位置,并以字符串形式获取纬度和经度。我想使用这些纬度和经度进行实时位置跟踪。

public class DriverCurrentLocationActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    LocationManager locationManager;
    LocationListener locationListener;

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

        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                    Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    updateMap(lastKnownLocation);

                }

            }
        }
    }

    public void updateMap(Location location) {
        try {

            LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
            mMap.clear();
            mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
            mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location"));
        }catch (Exception e){
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_driver_current_location);
        // 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;


        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                updateMap(location);
            }

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

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };

        if (Build.VERSION.SDK_INT < 23) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);



        }else {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
            } else {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
                Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                if (lastKnownLocation != null){
                    updateMap(lastKnownLocation);
                }
            }
        }
    }
}

【问题讨论】:

    标签: android-studio google-maps locationmanager android-gps locationlistener


    【解决方案1】:

    在 onCreate 中创建 someMethod()

            fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
            fetchLastLocation();
    
     private void someMethod() {
    
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
                return;
            }
        Task<Location> task = fusedLocationProviderClient.getLastLocation();
        task.addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
    
                if (location != null){
                    currentLocation = location;
                    Toast.makeText(this,currentLocation.getLatitude() +""+ currentLocation.getLongitude(),Toast.LENGTH_LONG).show();
                    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
                    mapFragment.getMapAsync(MapFragment.this);
                }
            }
        });
    }
    

    然后在您的 onMapReady() 方法中使用以下代码:

     LatLng center = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions().position(center).title(center.latitude + ":" + center.longitude);
        mMap.clear();
        googleMap.animateCamera(CameraUpdateFactory.newLatLng(center));
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(center, 18));
        googleMap.addMarker(markerOptions);
    

    将 LatLng 转换为字符串:

    String string_latlng = center.toString();
    

    希望对你有帮助:)

    【讨论】:

      【解决方案2】:

      检查您的 updateMap 函数是否为 null,因为 getLastKnownLocation 有时可能会返回 null,这样您就不会遇到崩溃或异常。也可以试试this

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-08-31
        • 2012-07-02
        • 2017-05-09
        • 2019-08-25
        • 1970-01-01
        • 1970-01-01
        • 2013-10-11
        相关资源
        最近更新 更多