首页 > 解决方案 > Android - 像谷歌地图一样准确获取坐标

问题描述

我怎样才能像谷歌地图一样准确地获取我的当前坐标?

到目前为止,我已经使用getLastLocation了——它有效,但我在 20 米的同一区域得到了相同的坐标——它并不那么准确。在谷歌地图中,​​您可以看到大约 3 米的精度。我怎样才能做到这一点?

我只对坐标感兴趣

标签: javaandroidgoogle-mapslocationcoordinates

解决方案


用户授予位置权限后,您可以执行以下操作。1- 要求用户启用 GPS 以获得高精度位置 2- 使用 fusedLocationProviderClient.getCurrentLocation() 方法获取用户当前位置

private fun askToEnableGPS() {
        LocationServices.getSettingsClient(requireActivity())
            .checkLocationSettings(
                LocationSettingsRequest.Builder()
                    .addLocationRequest(LocationRequest.create().apply {
                        priority = LocationRequest.PRIORITY_HIGH_ACCURACY
                    }).build()
            )
            .addOnSuccessListener {
                //  GPS is already enable, callback GPS status through listener
                getCurrentUserLocation()
            }
            .addOnFailureListener { e ->
                when ((e as ApiException).statusCode) {
                    LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> try {
                        // system open location
                        val rae = e as ResolvableApiException
                        launchGPS.launch(IntentSenderRequest.Builder(rae.resolution).build())

                    } catch (sie: IntentSender.SendIntentException) {
                        Log.i(
                            TAG,
                            "PendingIntent unable to execute request."
                        )
                        viewModel.handleNoGPS()
                    }
                    LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> {
                        Log.i(
                            TAG,
                            "SETTINGS CHANGE UNAVAILABLE"
                        )
                        viewModel.handleNoGPS()
                    }
                }

            }
    }

    private val launchGPS =
        registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
            if (result.resultCode == AppCompatActivity.RESULT_OK) {
                getCurrentUserLocation()
            } else {
                MaterialAlertDialogBuilder(requireContext())
                    .setMessage(getString(R.string.gps_in_need_message))
                    .setPositiveButton(getString(R.string.confirm)) { dialog, _ ->
                        dialog.dismiss()
                        // retry here asking for GPS permission
                    }
                    .setNegativeButton(getString(R.string.get_default)) { dialog, _ ->
                        dialog.dismiss()
                        viewModel.handleNoGPS()
                    }
                    .setCancelable(false)
                    .show()
            }
        }

    fun getCurrentUserLocation() {
        fusedLocationProviderClient.getCurrentLocation(
            LocationRequest.PRIORITY_HIGH_ACCURACY,
            object : CancellationToken() {
                override fun isCancellationRequested(): Boolean = false

                override fun onCanceledRequested(p0: OnTokenCanceledListener): CancellationToken =
                    this

            }
        )
            .addOnSuccessListener {
                // here is user current location
                viewModel.setSelectedByLocation(it.longitude, it.latitude)

            }
            .addOnFailureListener {
                MaterialAlertDialogBuilder(requireContext())
                    .setMessage(getString(R.string.failed_to_get_current_location))
                    .setPositiveButton(getString(R.string.retry)) { dialog, _ ->
                        dialog.dismiss()
                        // retry getCurrentUserLocation or askToEnableGPS
                    }
                    .setNegativeButton(getString(R.string.get_default)) { dialog, _ ->
                        dialog.dismiss()
                        // handle failure in getting current location
                    }
                    .setCancelable(false)
                    .show()
            }
    }

推荐阅读