【问题标题】:how to get latlng from LocationSettingsResponse method?如何从 LocationSettingsResponse 方法中获取 latlng?
【发布时间】:2020-08-26 13:17:18
【问题描述】:

我正在尝试制作一个地图活动,我可以选择我当前的位置并在地图上的任何位置做一个标记,我尝试使用谷歌文档,但我不明白如何从这种方法中获得 latlng任何人都对此有想法!

LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(5000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest);
    // ...

    SettingsClient client = LocationServices.getSettingsClient(this);
    Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());

    task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
        @Override
        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
            // All location settings are satisfied. The client can initialize
            // location requests here.
            // ...
            

        }
    });

【问题讨论】:

  • “如何从 LocationSettingsResponse 方法中获取 latlng?” 你没有。它只处理位置设置。正如代码中的 cmets 所说 “客户端可以在此处初始化位置请求。” 因此,您仍然需要使用 requestLocationUpdates() 执行实际位置请求,然后等待 onLocationChanged() 回调。该操作可能需要一段时间,因此即使getLastKnownLocation() 也不一定会立即返回最新位置,应在了解该限制的情况下使用。但是你在下面得到了一个很好的答案。

标签: java android google-maps


【解决方案1】:

为您的问题创建如下函数:

 public void centreMapOnLocation(Location location, String title){

    if (location != null) {
        LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());

        mMap.addMarker(new MarkerOptions().position(userLocation).title(title));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
    }
}

在 onMapReady 函数中添加以下代码:

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

    mMap.setOnMapLongClickListener(this);
    mMap.clear();

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

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {

            }

            @Override
            public void onProviderDisabled(String s) {

            }
        };

        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);
            centreMapOnLocation(lastKnownLocation, "Your Location");

        }else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
    }
}

在 onMapLongClick 中:

Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());

String address = "";

try {

    List<Address> listAddresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);

            if(listAddresses != null && listAddresses.size() > 0){

                if (listAddresses.get(0).getThoroughfare() != null){
                    address += listAddresses.get(0).getThoroughfare() + " ";
                }
                address += listAddresses.get(0).getSubThoroughfare() + " ";


            }

        }catch (Exception e){
            e.printStackTrace();
        }

        if (address.equals("")){
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm dd-MM-yyyy");
            address += sdf.format(new Date());

        }
        mMap.addMarker(new MarkerOptions().position(latLng).title(address));
SharedPreferences sharedPreferences = this.getSharedPreferences("com.luv.memorableplaces", Context.MODE_PRIVATE);

        try {

            ArrayList<String> lat = new ArrayList<String>();
            ArrayList<String> lng = new ArrayList<String>();

            for (LatLng coord : MainActivity.locations){

                lat.add(Double.toString(coord.latitude));
                lng.add(Double.toString(coord.longitude));

                sharedPreferences.edit().putString("latitudes", ObjectSerializer.serialize(lat)).apply();
                sharedPreferences.edit().putString("longitudes", ObjectSerializer.serialize(lng)).apply();
            }

            sharedPreferences.edit().putString("places", ObjectSerializer.serialize(MainActivity.places)).apply();

        }catch (Exception e){
            e.printStackTrace();
        }

        Toast.makeText(this, "Location Saved", Toast.LENGTH_SHORT).show();

这也将帮助您保存以前的位置。试试看,应该可以的。

【讨论】:

  • 你写了这么多废话,没有回答他的问题。您如何从 LocationSettingsResponse 获取位置?如果您无法从中获取位置,LocationSettingsResponse 有什么用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-25
  • 2017-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-23
  • 1970-01-01
相关资源
最近更新 更多