Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 地图碎片加载缓慢_Android_Google Maps - Fatal编程技术网

Android 地图碎片加载缓慢

Android 地图碎片加载缓慢,android,google-maps,Android,Google Maps,我在仪表板片段中放置了一个地图片段,如下图所示: 清晰地观看图像 每当我在主页片段上并单击仪表板片段时,需要3-4秒(第一次)和1-2秒 下面是仪表板片段的代码 class DashboardFragment : BaseFragment<DashboardViewModel, FragmentDashboardBinding, WeatherRepository>(), GoogleMap.OnMapClickListener, GoogleMap

我在仪表板片段中放置了一个地图片段,如下图所示:

清晰地观看图像

每当我在主页片段上并单击仪表板片段时,需要3-4秒(第一次)和1-2秒

下面是仪表板片段的代码

    class DashboardFragment :
    BaseFragment<DashboardViewModel, FragmentDashboardBinding, WeatherRepository>(),
    GoogleMap.OnMapClickListener,
    GoogleMap.OnMapLongClickListener,
    GoogleMap.OnCameraIdleListener,
    OnMapReadyCallback {

    private var map: GoogleMap? = null
    private var cameraPosition: CameraPosition? = null

    private lateinit var fusedLocationProviderClient: FusedLocationProviderClient

    private val defaultLocation = LatLng(-33.8523341, 151.2106085)
    private var locationPermissionGranted = false
    private var lastKnownLocation: Location? = null
    private var weatherData: WeatherData? = null

    private lateinit var bottomSheetBehavior: BottomSheetBehavior<NestedScrollView>

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        if (savedInstanceState != null) {
            lastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION)
            cameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION)
            weatherData = savedInstanceState.getParcelable(KEY_WEATHER_DATA)
        }
        Log.e("Weather Data", weatherData.toString())

            fusedLocationProviderClient =
                LocationServices.getFusedLocationProviderClient(requireActivity())
            val mapFragment =
                childFragmentManager.findFragmentById(R.id.myMap) as SupportMapFragment?
            mapFragment?.getMapAsync(this@DashboardFragment)


        bottomSheetBehavior = BottomSheetBehavior.from(binding.root.bottomSheet)
        bottomSheetBehavior.addBottomSheetCallback(object :
            BottomSheetBehavior.BottomSheetCallback() {
            override fun onSlide(bottomSheet: View, slideOffset: Float) { /*handle onSlide*/ }

            override fun onStateChanged(bottomSheet: View, newState: Int) {
                when (newState) {
                    BottomSheetBehavior.STATE_COLLAPSED -> {
                        binding.root.bottomSheet.background =
                            (ContextCompat.getDrawable(requireContext(), R.drawable.round))
                    }
                    BottomSheetBehavior.STATE_EXPANDED -> {
                        binding.root.bottomSheet.background =
                            (ContextCompat.getDrawable(requireContext(), R.drawable.edge))
                    }
                    BottomSheetBehavior.STATE_DRAGGING -> {
                    }
                    BottomSheetBehavior.STATE_SETTLING -> {
                    }
                    BottomSheetBehavior.STATE_HIDDEN -> {
                    }
                    else -> {
                    }
                }
            }
        })

        viewModel.weatherResponse.observe(viewLifecycleOwner, {
            when (it) {
                is Resource.Success -> {
                    updateUi(binding.root, it.value)
                    weatherData = it.value
                }
                is Resource.Failure -> {
                    Toast.makeText(
                        requireContext(),
                        "Damn, Failed To Load Data",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        })

    }

    override fun onSaveInstanceState(outState: Bundle) {
        map?.let { map ->
            outState.putParcelable(KEY_CAMERA_POSITION, map.cameraPosition)
            outState.putParcelable(KEY_LOCATION, lastKnownLocation)
        }
        super.onSaveInstanceState(outState)
    }

    override fun onMapReady(map: GoogleMap) {
        this.map = map
        map.setOnMapClickListener(this)
        map.setOnMapLongClickListener(this)
        map.setOnCameraIdleListener(this)
        getLocationPermission()
        updateLocationUI()
        getDeviceLocation()
    }

    var marker: Marker? = null
    override fun onMapClick(point: LatLng) {
        if (marker == null){
        marker = map?.addMarker(
            MarkerOptions()
                .position(point)
                .title("${point.latitude.toString()},${point.longitude.toString()} is the location")
        )
        } else {
            marker!!.position  = point
            marker!!.title = "${point.latitude.toString()},${point.longitude.toString()} is the location"
        }
        viewModel.getWeather(
            point.latitude.toString(),
            point.longitude.toString(),
            app_id
        )
        if (bottomSheetBehavior.state == BottomSheetBehavior.STATE_EXPANDED)
            bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
        else
            bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
        Toast.makeText(this.context, "click $point", Toast.LENGTH_SHORT).show()
    }

    override fun onMapLongClick(point: LatLng) {
        try {
            val manager: FragmentManager =
                (this.context as AppCompatActivity).supportFragmentManager
            CustomBottomSheetDialogFragment().show(manager, CustomBottomSheetDialogFragment.TAG)
        } catch (e: Exception) {
            Log.e("❤", e.printStackTrace().toString())
        }
        Toast.makeText(this.context, "long click", Toast.LENGTH_SHORT).show()
    }

    override fun onCameraIdle() {
        //if(!::map.isInitialized) return
        //cameraTextView.text = map.cameraPosition.toString()
        //Toast.makeText(this.context, "camera idle", Toast.LENGTH_SHORT).show()
    }

    private fun updateLocationUI() {
        if (map == null) {
            return
        }
        try {
            if (locationPermissionGranted) {
                map?.isMyLocationEnabled = true
                map?.uiSettings?.isMyLocationButtonEnabled = true
            } else {
                map?.isMyLocationEnabled = false
                map?.uiSettings?.isMyLocationButtonEnabled = false
                lastKnownLocation = null
                getLocationPermission()
            }
        } catch (e: SecurityException) {
            Log.e("Exception: %s", e.message, e)
        }
    }

    private fun getDeviceLocation() {
        try {
            if (locationPermissionGranted) {
                val locationResult = fusedLocationProviderClient.lastLocation
                locationResult.addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        lastKnownLocation = task.result
                        if (lastKnownLocation != null) {
                            map?.moveCamera(
                                CameraUpdateFactory.newLatLngZoom(
                                    LatLng(
                                        lastKnownLocation!!.latitude,
                                        lastKnownLocation!!.longitude
                                    ), DEFAULT_ZOOM.toFloat()
                                )
                            )
                            viewModel.getWeather(
                                lastKnownLocation!!.latitude.toString(),
                                lastKnownLocation!!.longitude.toString(),
                                app_id
                            )
                        }
                    } else {
                        Log.d(TAG, "Current location is null. Using defaults.")
                        Log.e(TAG, "Exception: %s", task.exception)
                        map?.moveCamera(
                            CameraUpdateFactory
                                .newLatLngZoom(defaultLocation, DEFAULT_ZOOM.toFloat())
                        )
                        map?.uiSettings?.isMyLocationButtonEnabled = false
                    }
                }
            }
        } catch (e: SecurityException) {
            Log.e("Exception: %s", e.message, e)
            Toast.makeText(this.context, "Some exception occurred", Toast.LENGTH_SHORT).show()
        }
    }

    private fun getLocationPermission() {
        if (ContextCompat.checkSelfPermission(
                requireContext(),
                Manifest.permission.ACCESS_FINE_LOCATION
            )
            == PackageManager.PERMISSION_GRANTED
        ) {
            locationPermissionGranted = true
        } else {
            requestPermissions(
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION
            )
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        locationPermissionGranted = false
        when (requestCode) {
            PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION -> {

                if (grantResults.isNotEmpty() &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED
                ) {
                    locationPermissionGranted = true
                }
            }
        }
        updateLocationUI()
    }

    override fun getViewModal() = DashboardViewModel::class.java

    override fun getFragmentBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ) = FragmentDashboardBinding.inflate(inflater, container, false)

    override fun getFragmentRepository() =
        WeatherRepository(remoteDataSource.buildApi(WeatherApi::class.java))


    companion object {
        private val TAG = DashboardFragment::class.java.simpleName
        private const val DEFAULT_ZOOM = 15
        private const val PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1
        private const val KEY_CAMERA_POSITION = "camera_position"
        private const val KEY_LOCATION = "location"
        private const val KEY_WEATHER_DATA = "weather_data"
        const val app_id = "*******api********"
    }
}
类仪表板片段:
BaseFragment(),
GoogleMap.OnMapClickListener,
GoogleMap.OnMapLongClickListener,
GoogleMap.onCameraideListener,
onmapredycallback{
私有变量映射:GoogleMap?=null
私有变量cameraPosition:cameraPosition?=null
私有lateinit变量fusedLocationProviderClient:fusedLocationProviderClient
私有val defaultLocation=LatLng(-33.8523341151.2106085)
private var locationpermissiongrated=false
私有变量lastKnownLocation:位置?=null
私有var weatherData:weatherData?=null
私有lateinit变量bottomSheetBehavior:bottomSheetBehavior
覆盖活动创建的乐趣(savedInstanceState:Bundle?){
super.onActivityCreated(savedInstanceState)
如果(savedInstanceState!=null){
lastKnownLocation=savedInstanceState.getParcelable(键位置)
cameraPosition=savedInstanceState.getParcelable(键\相机\位置)
weatherData=savedInstanceState.getParcelable(关键字天气数据)
}
Log.e(“天气数据”,weatherData.toString())
fusedLocationProviderClient=
LocationServices.getFusedLocationProviderClient(require())
val映射片段=
childFragmentManager.findFragmentById(R.id.myMap)是否作为SupportMapFragment?
mapFragment?.getMapAsync(this@DashboardFragment)
bottomSheetBehavior=bottomSheetBehavior.from(binding.root.bottomSheet)
bottomSheetBehavior.addBottomSheetCallback(对象:
BottomSheetBehavior.BottomSheetCallback(){
覆盖滑轨上的乐趣(底页:视图,滑轨偏移:Float){/*滑轨上的句柄*/}
覆盖状态更改(底部工作表:视图,新闻状态:Int){
何时(新闻状态){
BottomSheetBehavior.STATE_已折叠->{
binding.root.bottomSheet.background=
(ContextCompat.getDrawable(requireContext(),R.drawable.round))
}
BottomSheetBehavior.STATE_已展开->{
binding.root.bottomSheet.background=
(ContextCompat.getDrawable(requireContext(),R.drawable.edge))
}
BottomSheetBehavior.STATE_拖动->{
}
BottomSheetBehavior.STATE_沉降->{
}
BottomSheetBehavior.STATE_隐藏->{
}
其他->{
}
}
}
})
viewModel.weatherResponse.observe(viewLifecycleOwner{
什么时候{
是资源。成功->{
updateUi(binding.root,it.value)
weatherData=it.value
}
是资源。失败->{
Toast.makeText(
requireContext(),
“该死,加载数据失败”,
吐司长度
).show()
}
}
})
}
覆盖存储实例状态(超出状态:捆绑){
映射?让{map->
外站。可放置(键\摄像机\位置,地图。摄像机位置)
外州可输入(钥匙位置,最后知道的位置)
}
super.onSaveInstanceState(超出状态)
}
在mapready上覆盖乐趣(地图:谷歌地图){
this.map=map
map.setOnMapClickListener(此)
map.setOnMapLongClickListener(此)
map.setOnCameraideListener(此)
getLocationPermission()
updateLocationUI()
getDeviceLocation()
}
变量标记:标记?=null
覆盖乐趣onmaplick(点:LatLng){
如果(标记==null){
marker=map?.addMarker(
标记选项()
.位置(点)
.title(${point.latitude.toString()},${point.latitude.toString()}是位置)
)
}否则{
标记!!位置=点
marker!!.title=“${point.latitude.toString()},${point.latitude.toString()}是位置”
}
viewModel.getWeather(
point.latitude.toString(),
point.longitude.toString(),
应用程序id
)
if(bottomSheetBehavior.state==bottomSheetBehavior.state\u展开)
bottomSheetBehavior.state=bottomSheetBehavior.state\u已折叠
其他的
bottomSheetBehavior.state=bottomSheetBehavior.state\u已展开
Toast.makeText(this.context,“click$point”,Toast.LENGTH\u SHORT.show())
}
单击鼠标右键(点:LatLng){
试一试{
val管理器:碎片管理器=
(此.context作为AppCompatActivity)。supportFragmentManager
CustomBottomSheetDialogFragment().show(管理器,CustomBottomSheetDialogFragment.TAG)
}捕获(e:例外){
Log.e(”❤", e、 printStackTrace().toString())
}
Toast.makeText(this.context,“长点击”,Toast.LENGTH\u SHORT.show())
}
覆盖有趣的onCameraIdle(){
//如果(!::map.i初始化)返回
//cameraTextView.text=map.cameraPosition.toString()
//Toast.makeText(this.context,“照相机空闲”,Toast.LENGTH\u SHORT.show())
}
私人娱乐更新目录(){
if(map==null){
返回
}
试一试{
如果(已授予位置许可){
映射?.isMyLocationEnabled=true
映射?.uiSettings?.ISMyLocationButtonneEnabled=tr