Как получить координату от фиксированного маркера в центре карт Google в Android

В моем приложении я пытаюсь получить координату от фиксированного маркера в центре карт Google. Когда я прокручиваю карту, я хочу получить координаты и установить их в текстовом представлении.

Вот мой код Котлина:

class ActivityMapsDSPBng : AppCompatActivity(), OnMapReadyCallback, GoogleMap.OnMarkerClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
        com.google.android.gms.location.LocationListener {

    ...

    private val TAG = "ActivityMapsDSPBng"
    private lateinit var mGoogleApiClient: GoogleApiClient
    private var mLocationManager: LocationManager? = null
    lateinit var mLocation: Location
    private var mLocationRequest: LocationRequest? = null
    private val listener: com.google.android.gms.location.LocationListener? = null
    private val UPDATE_INTERVAL = (2 * 1000).toLong()
    private val FASTEST_INTERVAL: Long = 2000

    lateinit var locationManager: LocationManager

    override fun onStart() {
        ...
    }

    override fun onStop() {
        ...
    }

    override fun onConnectionSuspended(p0: Int) {
        ...
    }

    override fun onConnectionFailed(connectionResult: ConnectionResult) {
        Log.i(TAG, "Connection failed. Error: " + connectionResult.errorCode)
    }

    override fun onLocationChanged(location: Location) {
        var msg = "Update Location: Latitude " + location.latitude.toString() + " Longitude " + location.longitude.toString()
        tv_dspbg_lat.setText("" + location.latitude)
        tv_dspbg_long.setText("" + location.longitude)
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }

    override fun onConnected(p0: Bundle?) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return
        }

        startLocationUpdates()

        var fusedLocationProviderClient: FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
        fusedLocationProviderClient.lastLocation
                .addOnSuccessListener(this, OnSuccessListener<Location> { location ->
                    if (location != null){
                        mLocation = location
                        tv_dspbg_lat.setText("" + mLocation.latitude)
                        tv_dspbg_long.setText("" + mLocation.longitude)
                    }
                })
    }

    protected fun startLocationUpdates(){
        // Create location request
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(UPDATE_INTERVAL)
                .setFastestInterval(FASTEST_INTERVAL)

        // Request location updates
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            return
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        ...

        val mapsDSPBNGfragment = supportFragmentManager
                .findFragmentById(R.id.maps_dspbg) as SupportMapFragment
        mapsDSPBNGfragment.getMapAsync(this)

        fusedLPCBg = LocationServices.getFusedLocationProviderClient(this)

        mGoogleApiClient = GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build()
        mLocationManager = this.getSystemService(Context.LOCATION_SERVICE) as LocationManager

        checkLocation()
    }

    private fun checkLocation(): Boolean{
        ...
    }

    private fun isLocationEnabled(): Boolean{
        ...
    }

    private fun showAlert(){
        val dialog = AlertDialog.Builder(this)
        dialog.setTitle("Enable Location")
                .setMessage("Your location setting is set to 'Off'. \nPlease enable location to " + "use this app")
                .setPositiveButton("Location Settings", DialogInterface.OnClickListener { paramDialogInterface, paramInt ->
                    val myIntent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                    startActivity(myIntent)
                })
                .setNegativeButton("Cancel", DialogInterface.OnClickListener { paramDialogInterface, paramInt ->  })
        dialog.show()
    }

}

Собираю код из https://androidteachers.com/kotlin-for-android/get-location-in-android-with-kotlin/

Когда я прокручиваю карты, координаты не меняются в зависимости от фиксированного производителя.

У вас есть код, в котором вы инициализируете карту? Я не могу найти "фиксированный маркер", который вы упомянули в приведенном выше коде.

Tam Huynh 11.07.2018 09:04

Я создаю «фиксированный маркер» в коде activity.xml.

Bara19 11.07.2018 09:54
0
2
1 895
2

Ответы 2

Проверьте мой код Java. Фиксированный маркер, о котором вы говорите, похож на наложение View из вашего кода макета. Но если он находится прямо в центре карты, вы можете использовать центр камеры:

mGoogleMap.setOnCameraIdleListener(new OnCameraIdleListener() {
    @Override
    public void onCameraIdle() {
            // Get the center coordinate of the map, if the overlay view is center too
            CameraPosition cameraPosition = mGoogleMap.getCameraPosition();
            LatLng currentCenter = cameraPosition.target;

            // Or get any coordinate if overlay view is not at the centered
            // int[] location = new int[2];
            // mOverlayView.getLocationInWindow(location);

            // Point viewPosition = new Point(location[0], location[1]);
            // LatLng currentCenter = mGoogleMap.getProjection().fromScreenLocation(viewPosition);
    }
}

Да, фиксированный маркер похож на центр наложения карты. Могу ли я с помощью вашего кода получить координаты и установить их в текстовом представлении?

Bara19 11.07.2018 10:40

Проверьте мой отредактированный ответ для фиксированного маркера по центру и не по центру

Tam Huynh 11.07.2018 10:45
currentCenter - это координаты, которые вам нужны, просто покажите широту и долготу на вашем TextView.
Tam Huynh 11.07.2018 11:44

Я пробовал ваш Java-код, но получаю ошибку в коде "LatLng currentCenter"

Bara19 11.07.2018 12:44

Используйте только одно из двух решений, проверьте отредактированный ответ

Tam Huynh 11.07.2018 14:56

Я пробую ваш java-код переопределять удовольствие onLocationChanged (newLocation: Location?) {Val latLng = LatLng (newLocation !!. Latitude, newLocation.longitude) ... mMaps.setOnCameraIdleListener (GoogleMap.OnCameraIdleListener () {val centerPosMaps: LatLng = m .cameraPosition.target tv_nplotbng_lat.setText ("" + centerPos.latitude) tv_nplotbng_long.setText ("" + centerPos.longitude)})} но в текстовом представлении координаты не отображаются

Bara19 16.07.2018 05:32

Чтобы получить центральное расположение карты Google

LatLng centerLatLang = mMap.getProjection().getVisibleRegion().latLngBounds.getCenter();

Другие вопросы по теме