I am working on Android application which makes use of Android maps extensions library.When Try to get map from mapFragment I get map as null. I verified my mapFragment is not null. Following is my Fragment.
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)));
}
}
}
Following is my layout file
<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" >
Just use async method
mapFragment.getExtendedMapAsync(new OnMapReadyCallback() {
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap; setUpMap();
}
});