第一,守则:
class MapFragment: BaseFragment<MapFragmentBinding>(R.layout.map_fragment) {
var mapView: MapView? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mapView = binding.mapView
MapsInitializer.initialize(requireContext(),
MapsInitializer.Renderer.LATEST
) {}
// seems a bit out of place, but due to the binding variable, from out baseFragment class, it has to be done here
mapView?.onCreate(savedInstanceState)
mapView?.getMapAsync { gMap ->
gMap.setOnMapLoadedCallback {
val randomLocation = LatLng(
Random.nextDouble(-170.0, 170.0),
Random.nextDouble(-170.0, 170.0)
)
gMap.addMarker(MarkerOptions().position(randomLocation).title(randomLocation.toString()))
gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(randomLocation, 10.0f))
}
}
}
override fun onStart() {
super.onStart()
mapView?.onStart()
}
override fun onPause() {
super.onPause()
mapView?.onPause()
}
override fun onResume() {
super.onResume()
mapView?.onResume()
}
override fun onStop() {
super.onStop()
mapView?.onStop()
}
override fun onLowMemory() {
super.onLowMemory()
mapView?.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
mapView?.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView?.onSaveInstanceState(outState)
}
}这是一个包含在另一个片段中的mapFragment。它经常被重新加载(准确地说,该应用程序有一个装满物品的回收视图,只要按下这个片段就可以看到)。
我不知道为什么,但有时(每当它打开和关闭3-7次),它动画相机的随机位置,并没有显示标记。我注意到,当“随机地点”出现在北冰洋或南极洲时,这种情况大多会发生(相信我,我不知道这是否相关,我和你一样困惑)。
有什么暗示/想法,为什么会发生这种情况?
发布于 2022-10-14 13:41:50
随机纬度的范围是无效的-170.0, 170.0。地图相机的实现可能会将超出范围的值固定在-90或90,并且地图将拒绝放置标记。
随机位置的最大范围可以使用:
val randomLocation = LatLng(
Random.nextDouble(-90.0, 90.0), // kotlin Random produces [-90,90)
Random.nextDouble(-180.0, 180.0)纬度地图api允许:
[-90, 90] // inclusive at both ends对于经度许可:
[-180, 180) // inclusive on the negative and exclusive on the positivehttps://stackoverflow.com/questions/74068845
复制相似问题