Как сделать перетаскиваемый маркер с котлина в Android - PullRequest
0 голосов
/ 29 сентября 2019

Я хотел бы изменить этот код в Котлине, чтобы маркер можно было перемещать по карте и возвращать новые координаты выбранной точки. Может кто-нибудь сказать мне, как это сделать?

класс MapsActivity: AppCompatActivity (), OnMapReadyCallback, GoogleMap.OnMarkerClickListener {переопределить fun onMarkerClick (p0: Marker?) = False

private lateinit var map: GoogleMap
private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var lastLocation: Location

companion object {
    private const val LOCATION_PERMISSION_REQUEST_CODE = 1
    private const val PLACE_PICKER_REQUEST = 3
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_maps)

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    val mapFragment = supportFragmentManager
        .findFragmentById(R.id.map) as SupportMapFragment
    mapFragment.getMapAsync(this)
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
override fun onMapReady(googleMap: GoogleMap) {
    map = googleMap
    map.getUiSettings().setZoomControlsEnabled(true)
    map.setOnMarkerClickListener(this)
    setUpMap()
}

private fun setUpMap() {
    if (ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,
            arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_REQUEST_CODE)
        return
    }

    map.isMyLocationEnabled = true

    fusedLocationClient.lastLocation.addOnSuccessListener(this) { location ->

        if (location != null) {
            lastLocation = location
            val currentLatLng = LatLng(location.latitude, location.longitude)
            placeMarkerOnMap(currentLatLng)
            map.animateCamera(
                CameraUpdateFactory.newLatLngZoom(
                    LatLng(
                        location.latitude,
                        location.longitude
                    ), 12f
                )
            )
        }
    }
}
private fun getAddress(latLng: LatLng): String {
    val geocoder = Geocoder(this)
    val addresses: List<Address>?
    val address: Address?
    var addressText = ""
    try {
        addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1)
        if (null != addresses && !addresses.isEmpty()) {
            address = addresses[0]
            for (i in 0 until address.maxAddressLineIndex) {
                addressText += if (i == 0) address.getAddressLine(i) else "\n" + address.getAddressLine(i)
            }
        }
    } catch (e: IOException) {
        Log.e("MapsActivity", e.localizedMessage)
    }
    return addressText
}
private fun placeMarkerOnMap(location: LatLng) {
    val markerOptions = MarkerOptions().position(location)
    val titleStr = getAddress(location)
    markerOptions.title(titleStr)
    map.addMarker(markerOptions)
}
private fun loadPlacePicker() {
    val builder = PlacePicker.IntentBuilder()

    try {
        startActivityForResult(builder.build(this@MapsActivity), PLACE_PICKER_REQUEST)
    } catch (e: GooglePlayServicesRepairableException) {
        e.printStackTrace()
    } catch (e: GooglePlayServicesNotAvailableException) {
        e.printStackTrace()
    }
}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...