我是科特林的初学者,我正在尝试构建附近的场所应用程序。
我的应用程序应该像这样工作:
[首页是不同地点类型的列表(例如'餐厅','博物馆','酒吧','标记'...)。如果用户单击这些类型之一,则会将其发送到新页面,地图。在此地图上,他们可以看到他们附近所选择地点的类型。为此,我关注了一个YouTube频道,该频道的功能与我相似,但设计不同。
这里是链接:https://www.youtube.com/watch?v=tI4dV9n6-yE&t=2937s
(我在第3部分)
我的问题如下:我创建了带有列表视图的第一页,当我单击某个元素时,我得到了一张具有我所在位置的地图,但是我没有到附近的地方。
当应用程序运行时,我可以在控制台上看到以下内容:
URL_DEBUG:maps.googleapis.com/maps/api/place/nearbysearch/json?location=0.0,0.0&radius=10000&type=museum&key=MY_API_KEY
所以我知道问题出在位置不佳,但我不知道为什么。
这里是文件关注的代码:
class MapRestaurant : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mMap: GoogleMap
private var latitude:Double=0.toDouble()
private var longitude:Double=0.toDouble()
private lateinit var mLastLocation: Location
private var mMarker: Marker?=null
companion object { private const val MY_PERMISSION_CODE: Int = 1000 }
//Location
lateinit var fusedLocationProviderClient: FusedLocationProviderClient
lateinit var locationRequest: LocationRequest
lateinit var locationCallback: LocationCallback
lateinit var mService:IGoogleAPIService
internal lateinit var currentPlace:MyPlaces
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map_restaurant)
// 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)
//Init Service
mService = Common.googleApiService
//Request runtime permission
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if(checkLocationPermission())
{
buildLocationRequest()
buildLocationCallBack()
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper())
}
}
else
{
buildLocationRequest()
buildLocationCallBack()
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper())
}
val placeChoix = intent.getStringExtra("CHOIX")
when(placeChoix)
{
"Restaurants" -> nearByPlace("restaurant")
"Bars" -> nearByPlace("bar")
"Musées" -> nearByPlace("museum")
"SuperMarché" -> nearByPlace("supermarket")
"Hopital" -> nearByPlace("hospital")
"Magasins" -> nearByPlace("shopping_mall")
}
}
private fun nearByPlace(typePlace: String) {
var url = getUrl(latitude, longitude, typePlace)
mService.getNearbyPlaces(url)
.enqueue(object:Callback<MyPlaces>{
override fun onFailure(call: Call<MyPlaces>, t: Throwable) {
Toast.makeText(baseContext, ""+t.message, Toast.LENGTH_SHORT).show()
}
override fun onResponse(call: Call<MyPlaces>, response: Response<MyPlaces>) {
currentPlace = response.body()!!
if(response.isSuccessful)
{
for(i in 0 until response.body()!!.results!!.size)
{
val markerOptions=MarkerOptions()
val googlePlace = response.body()!!.results!![i]
val lat = googlePlace.geometry!!.location!!.lat
val lng = googlePlace.geometry!!.location!!.lng
val placeName = googlePlace.name
val latLng = LatLng(lat, lng)
markerOptions.position(latLng)
markerOptions.title(placeName)
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
markerOptions.snippet(i.toString()) //Assign index for marker
mMap.addMarker(markerOptions) //Add marker to map
//Move camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng))
mMap.animateCamera(CameraUpdateFactory.zoomTo(20f))
}
}
}
})
}
private fun getUrl(latitude: Double, longitude: Double, typePlace: String): String {
//Toast.makeText(applicationContext, "latitude: $latitude \n longitude : $longitude", Toast.LENGTH_LONG).show()
val googlePlaceUrl = StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json")
googlePlaceUrl.append("?location=$latitude,$longitude")
googlePlaceUrl.append("&radius=10000") //10 km
googlePlaceUrl.append("&type=$typePlace")
googlePlaceUrl.append("&key=MY_API_KEY")
Log.d("URL_DEBUG", googlePlaceUrl.toString())
return googlePlaceUrl.toString()
}
private fun buildLocationCallBack() {
locationCallback = object : LocationCallback() {
override fun onLocationResult(p0: LocationResult?) {
mLastLocation = p0!!.locations.get(p0.locations.size-1) //get last location
if(mMarker != null)
{
mMarker!!.remove()
}
latitude = mLastLocation.latitude
longitude = mLastLocation.longitude
//Toast.makeText(applicationContext, "latitude: $latitude \n longitude : $longitude", Toast.LENGTH_LONG).show()
val latLng = LatLng(latitude,longitude)
val markerOptions = MarkerOptions()
.position(latLng)
.title("Votre position")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
mMarker = mMap.addMarker(markerOptions)
//move camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng))
mMap.animateCamera(CameraUpdateFactory.zoomTo(11f))
}
}
}
private fun buildLocationRequest() {
locationRequest = LocationRequest()
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
locationRequest.interval = 5000
locationRequest.fastestInterval = 3000
locationRequest.smallestDisplacement = 10f
}
private fun checkLocationPermission(): Boolean {
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION))
ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), MY_PERMISSION_CODE)
else
ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), MY_PERMISSION_CODE)
return false
}
else
return true
}
//override onRequestPermissionResult
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
when(requestCode)
{
MY_PERMISSION_CODE->{
if(grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
if(checkLocationPermission())
{
buildLocationRequest()
buildLocationCallBack()
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper())
mMap.isMyLocationEnabled=true
}
}
else
{
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()
}
}
}
}
override fun onStop() {
fusedLocationProviderClient.removeLocationUpdates(locationCallback)
super.onStop()
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
//Init google play services
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(
this,
android.Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
) {
mMap.isMyLocationEnabled = true
}
}
else
mMap.isMyLocationEnabled = true
//enabled zoom control
mMap.uiSettings.isZoomControlsEnabled=true
}
}
当调用getUrl()
函数时,我不明白为什么纬度和经度为0。有人可以帮我吗?
似乎在执行位置回调之前,对nearByPlace
的调用已运行。尝试放置以下代码:
val placeChoix = intent.getStringExtra("CHOIX")
when(placeChoix)
{
"Restaurants" -> nearByPlace("restaurant")
"Bars" -> nearByPlace("bar")
"Musées" -> nearByPlace("museum")
"SuperMarché" -> nearByPlace("supermarket")
"Hopital" -> nearByPlace("hospital")
"Magasins" -> nearByPlace("shopping_mall")
}
在回调内部:
private fun buildLocationCallBack() {
locationCallback = object : LocationCallback() {
override fun onLocationResult(p0: LocationResult?) {
mLastLocation = p0!!.locations.get(p0.locations.size-1) //get last location
if(mMarker != null)
{
mMarker!!.remove()
}
latitude = mLastLocation.latitude
longitude = mLastLocation.longitude
//Toast.makeText(applicationContext, "latitude: $latitude \n longitude : $longitude", Toast.LENGTH_LONG).show()
val latLng = LatLng(latitude,longitude)
val markerOptions = MarkerOptions()
.position(latLng)
.title("Votre position")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
mMarker = mMap.addMarker(markerOptions)
//move camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng))
mMap.animateCamera(CameraUpdateFactory.zoomTo(11f))
val placeChoix = intent.getStringExtra("CHOIX")
when(placeChoix)
{
"Restaurants" -> nearByPlace("restaurant")
"Bars" -> nearByPlace("bar")
"Musées" -> nearByPlace("museum")
"SuperMarché" -> nearByPlace("supermarket")
"Hopital" -> nearByPlace("hospital")
"Magasins" -> nearByPlace("shopping_mall")
}
}
}
}
希望这会有所帮助!
谢谢!这是工作 !我现在遇到另一个问题,“您已经超出了此API的每日请求配额。如果您没有设置自定义的每日请求配额,请验证您的项目是否具有有效的结算帐户:http://g.co/dev/maps-no-account”。我必须付费才能使我的API正常工作吗?