如何从AutoCompleteFragment中获取PlaceSelectionListener数据到MapFragment?
我想从AutoCompleteFragment信息中添加Marker到Google Map上,例如,如果用户选择了NewYork这个地方,Google Map就会在NewYork上添加新的标记,我现在把它分为AutoCompleteFragment和MapFragment。
这是AutoCompleteFragment类,这是MapFragment类。
class AutoCompleteFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_autocomplete, container, false)
return root
}
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?
) {
super.onViewCreated(view, savedInstanceState)
if (!Places.isInitialized()) {
Places.initialize(requireActivity(), google_key, Locale.US);
}
val autoCompleteFragment =
childFragmentManager.findFragmentById(R.id.autocomplete_fragment) as AutocompleteSupportFragment
autoCompleteFragment.setPlaceFields(
mutableListOf(
Place.Field.ID,
Place.Field.NAME,
Place.Field.LAT_LNG
)
)
}
}
这是MapFragment类。
class MapFragment : Fragment(), OnMapReadyCallback {
private lateinit var mapViewModel: MapViewModel
private lateinit var mMap: GoogleMap
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
mapViewModel =
ViewModelProviders.of(this).get(MapViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_map, container, false)
return root
}
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?
) {
val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
// Add a marker in Sydney and move the camera
val home = LatLng(35.535840, 138.713890)
mMap.addMarker(MarkerOptions().position(home).title("Marker in Home"))
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(home, 14.5f))
}
}