我正在开发使用Android地图扩展库的Android应用程序。当尝试从mapFragment获取地图时,我将地图显示为null。我验证了我的mapFragment不为null。 以下是我的片段。
public class ClusterMarkersFragment extends Fragment {
private static final String LOG_AREA = "ClusterMarkersFragment";
public static final String KEY_PREFIX = "KeyPrefix";
private SupportMapFragment mapFragment;
public GoogleMap map;
public static ClusterMarkersFragment newInstance (String prefix) {
ClusterMarkersFragment clusterMarkersFragment = new
ClusterMarkersFragment();
Bundle bundle = new Bundle();
bundle.putString(KEY_PREFIX, prefix);
clusterMarkersFragment.setArguments(bundle);
return clusterMarkersFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_cluster_marker,
container, false);
FragmentManager fm = getChildFragmentManager();
mapFragment = (SupportMapFragment) fm.findFragmentById(R.id.map_container);
if (mapFragment == null) {
mapFragment = SupportMapFragment.newInstance();
FragmentTransaction tx = fm.beginTransaction();
tx.add(R.id.map_container, mapFragment);
tx.commit();
}
map = mapFragment.getExtendedMap();
String prefix = getArguments().getString(KEY_PREFIX);
getLatLngFromDatabase(prefix);
map.setClustering(new ClusteringSettings().clusterOptionsProvider(new ClusterOptionsProvider() {
@Override
public ClusterOptions getClusterOptions(List<Marker> markers) {
float hue = BitmapDescriptorFactory.HUE_ROSE;
BitmapDescriptor blueIcon = BitmapDescriptorFactory.defaultMarker(hue);
return new ClusterOptions().icon(blueIcon);
}
}));
return view;
}
public void getLatLngFromDatabase (final String prefix) {
final List<LatLngPair> latLngPairs ;
//return LatLngPairs from database
addMarkersOnMap(latLngPairs);
}
private void addMarkersOnMap(final List<LatLngPair> latLngPairs) {
int diameter = (int) latLngPairs.get(0).rad * 2;
Bitmap bm = Bitmap.createBitmap(diameter, diameter, Bitmap.Config.ALPHA_8);
Canvas canvas = new Canvas(bm);
Paint p = new Paint();
p.setColor(getResources().getColor(R.color.green));
canvas.drawCircle(diameter / 2, diameter / 2, diameter / 2, p);
Bitmap bmIcon = BitmapFactory.decodeResource(getResources(), R.drawable.map_marker);
canvas.drawBitmap(bmIcon, diameter / 2, diameter / 2, p);
for (LatLngPair latLngPair : latLngPairs) {
map.addMarker(new MarkerOptions().position(new LatLng(
latLngPair.lat, latLngPair.lng)).icon(BitmapDescriptorFactory.
fromBitmap(bm)));
}
}
}
以下是我的布局文件
<RelativeLayout
android:id="@+id/map_container"
android:layout_width="match_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android" >
答案 0 :(得分:2)
只需使用异步方法
mapFragment.getExtendedMapAsync(new OnMapReadyCallback() {
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap; setUpMap();
}
});