I'm developing an app by using mapbox api. At the map when the user clicks map item on menu a fragment is opening.Later user may want to change mapview style such as satellite,dark,emerald or just a street view. User is able to choose map style on action bar. I implemented my action bar on main activity. When the user on map fragment choose map style and a variable comes to fragment which handled in main activity. This variable is the string of map style. Now I want to change map view style without recreating map fragment. What can you advise about this problem ?
public class GeoMapFragment extends Fragment implements OnMapReadyCallback {
public MapView mapView = null;
private MapboxMap mapboxMap;
public String mapViewSelectedItem ;
private static final int PERMISSIONS_LOCATION = 0;
public GeoMapFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_geomap, container, false);
mapView = (MapView)view.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
// Inflate the layout for this fragment
return view;
}
#Override
public void onStart() {
super.onStart();
mapView.onStart();
}
#Override
public void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
/**
* Dispatch onPause() to fragments.
*/
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onMapReady(MapboxMap map) {
mapboxMap = map;
mapboxMap.setStyle(Style.DARK);
mapboxMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(0, 0)));
// Show user location (purposely not in follow mode)
if ((ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_LOCATION);
} else {
mapboxMap.setMyLocationEnabled(true);
}
// TODO - mv.loadFromGeoJSONURL("https://gist.githubusercontent.com/tmcw/10307131/raw/21c0a20312a2833afeee3b46028c3ed0e9756d4c/map.geojson");
mapboxMap.addMarker(new MarkerOptions().title("Edinburgh").snippet("Scotland").position(new LatLng(55.94629, -3.20777)));
mapboxMap.addMarker(new MarkerOptions().title("Stockholm").snippet("Sweden").position(new LatLng(59.32995, 18.06461)));
mapboxMap.addMarker(new MarkerOptions().title("Prague").snippet("Czech Republic").position(new LatLng(50.08734, 14.42112)));
mapboxMap.addMarker(new MarkerOptions().title("Athens").snippet("Greece").position(new LatLng(37.97885, 23.71399)));
mapboxMap.addMarker(new MarkerOptions().title("Tokyo").snippet("Japan").position(new LatLng(35.70247, 139.71588)));
mapboxMap.addMarker(new MarkerOptions().title("Ayacucho").snippet("Peru").position(new LatLng(-13.16658, -74.21608)));
mapboxMap.addMarker(new MarkerOptions().title("Nairobi").snippet("Kenya").position(new LatLng(-1.26676, 36.83372)));
mapboxMap.addMarker(new MarkerOptions().title("Canberra").snippet("Australia").position(new LatLng(-35.30952, 149.12430)));
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_LOCATION: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mapboxMap.setMyLocationEnabled(true);
}
}
}
}
Your map fragment should have a getMapAsync() call which you can change the style of. Heres a rough example of how you can accomplish this:
private MapboxMap map;
...
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final MapboxMap mapboxMap) {
map = mapboxMap;
}
});
...
// Wherever you implemented receiving the style string from MainActivity you can include this:
map.setStyleUrl(<style url>);
If this doesn't work for you, please let me know how exactly you are creating the map fragment. Currently the SDK includes a fragment already which you can setup like so:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment mapFragment;
if (savedInstanceState == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
LatLng patagonia = new LatLng(-52.6885, -70.1395);
MapboxMapOptions options = new MapboxMapOptions();
options.accessToken("<your access token here>");
options.styleUrl(Style.SATELLITE);
options.camera(new CameraPosition.Builder()
.target(patagonia)
.zoom(9)
.build());
mapFragment = SupportMapFragment.newInstance(options);
transaction.add(R.id.container, mapFragment, "mapFragment");
transaction.commit();
} else {
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentByTag("mapFragment");
}
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final MapboxMap mapboxMap) {
map = mapboxMap;
}
});
}
If you did it this way you can easily change the style of the map like I said above.
Hope this helps out!
Related
I would like guidance on how to properly implement a google map in a view pager. I have done so in an activity and have no problems producing a map in a activity but when trying to do the same with a view pager I am not having much success.
I have found this question that asks something similar but trying it out leads me to an error that I can't resolve: How to put Google Maps V2 on a Fragment using ViewPager
I updated get map to get map Async following this guide: Replace getMap with getMapAsync.
However I am still no close to getting a google map to display in my view pager. I am uncertain as where else to go to for tutorials. I have found plenty of tutorials on how to get a map to show in an activity but none on how to get it to show with a view pager. Unable to find any guides on the subject relating to view pagers inside of maps.
I am currently unable to display a map in my fragment google map resources fragment.
If there are any resources or tutorials I can be provided that are up to date feel free to share them, I am currently unable to find a solution on my own.
Any ideas would be appreciated.
public Class MainActivity extends AppCompatActivity implements OnMapReadyCallback{
private GoogleMap googleMap;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
//The adapter adds the fragments created to the view so it can be seen by the user
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new SucessfullFosterYouthFragment(), "Sucessfull Foster Youth");
adapter.addFragment(new ContactusFragment(), "Contact US");
adapter.addFragment(new GoogleMapResourcesFragment(), "resources");
viewPager.setAdapter(adapter);
}
#Override
public void onMapReady(GoogleMap googleMap) {
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.googlemap);
mapFragment.getMapAsync(this);
}
public void setUpMap() {
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
}
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public class GoogleMapResourcesFragment extends Fragment{
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_googlemapresources, container,
false);
mMapView = (MapView) v.findViewById(R.id.googlemap);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Perform any camera updates here
return v;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
You should use MapView here as well instead of MapFragment:
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.googlemap);
mapFragment.getMapAsync(this);
Try this example below:
public class SomeFragment extends Fragment {
MapView mapView;
GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.some_layout, container, false);
// Gets the MapView from the XML layout and creates it
mapView = (MapView) v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
// Updates the location and zoom of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
map.animateCamera(cameraUpdate);
return v;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
Layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.google.android.gms.maps.MapView android:id="#+id/mapview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
I am using google map in my project. it was working but i did something( dont know what)now getMap() gives error. i think i update something. how can i fix it?
my code is like that;
GoogleMap googleMap;
..
if (locationManagerCheck.isLocationServiceAvailable()) {
if (googleMap == null) {
try {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();//ERROR
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(), Toast.LENGTH_SHORT)
.show();
}...
i tried make it:
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMapAsync(this);
but 'this' gives another error
can you help me?
edit:
public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager_check locationManagerCheck = new LocationManager_check(
this);
if (locationManagerCheck.isLocationServiceAvailable()) {
if (googleMap == null) {
try {
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(), Toast.LENGTH_SHORT)
.show();
}
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(final Marker marker) {....}
}
#Override
public void onMapReady(GoogleMap Map) {
googleMap=Map;
}
}
You should give a look to documentation
To add a map to an activity, add map fragment to your layout :
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.google.android.gms.maps.MapFragment"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
And then use it in your activity :
public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
map.setMyLocationEnabled(true);
map.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(final Marker marker) {....}
}
The map will be created in async way, and the onMapReady function will be called when map is ready,in this function you will be able to add markers, change position, title, zoom or whatever.
At the point you're retrieving the map it is null. You need to do it when you now the views have been initialised.
For example, in a Fragment you could do it in onViewCreated or in an Activity in onCreate after calling setContentView(R.layout.your_layout);
For example:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
MapView mapView = ((MapFragment) getFragmentManager().findFragmentById(R.id.map));
mapView.getMapAsync(this);
}
I have main activity with fragments and one of the fragments is Map Fragment. Now, when i tap there, every time it opens slow. I am using singleton instance of fragment, but it still doesnt work as expected. Here is a good of that class:
public MapsFragment() {
gson = new Gson();
}
public static MapsFragment getInstance() {
if (mInstance == null)
mInstance = new MapsFragment();
return mInstance;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable final Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_maps, container, false);
mOnSavedinstance = savedInstanceState;
mMapView = (MapView) v.findViewById(R.id.map);
mMapWrapperLayout = (MapWrapperLayout) v.findViewById(R.id.map_relative_layout);
mMapView.getMapAsync(MapsFragment.this);
mMapView.onCreate(savedInstanceState);
mMapView.requestFocus();
MapsInitializer.initialize(getActivity());
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
// MapWrapperLayout initialization
// 39 - default marker height
// 20 - offset between the default InfoWindow bottom edge and it's content bottom edge
mMapWrapperLayout.init(mGoogleMap, Constants.MARKER_HEIGHT);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mGoogleMap.setMyLocationEnabled(false);
}
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
setUpMap();
}
private void setUpMap() {
new Thread(new Runnable() {
#Override
public void run() {
final ArrayList<MarkerOptions> markerOptionses = new ArrayList<MarkerOptions>();
int counter = 0;
for (final Places places : Model.getInstance().getPlaces()) {
LatLng location = new LatLng(Double.parseDouble(places.getLat()), Double.parseDouble(places.getLon()));
final MarkerOptions options = new MarkerOptions();
options.snippet(gson.toJson(places));
options.position(location);
options.title(String.valueOf(counter));
markerOptionses.add(options);
counter++;
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
for (MarkerOptions markerOptionse : markerOptionses) {
mGoogleMap.addMarker(markerOptionse).setIcon(BitmapDescriptorFactory.fromResource(Model.getInstance().getPlaces()
.get(Integer.parseInt(markerOptionse.getTitle())).getMapsRes(getActivity())));
}
}
});
final CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(45.4654, 9.1859)) // Sets the center of the map to location user
.zoom(Constants.CAMERA_ZOOM_LOCATION) // Sets the zoom
.build(); // Creates a CameraPosition from the builder
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mGoogleMap.setOnMapClickListener(MapsFragment.this);
// mGoogleMap.setOnInfoWindowClickListener(mInfoListener);
}
});
}
}).start();
}
#Override
public void onResume() {
mMapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mGoogleMap.clear();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
You can try to add markers only if it would be visible? I mean: first move camera to start position and set zoomLevel and just after that add Markers but only if it's in visible sector. And update markers on camera move.
I have a very simple SupportMapFragment to display a small Google map which I use in this view
The idea is that the user can click it to view a full screen map.
How can I get rid of the +/- button from the map?
If it's not possible, is there an alternative method to get a map?
Here is my MapFragment code:
public class CustomMapFragment extends SupportMapFragment {
private static LatLng mPosFija;
public CustomMapFragment() {
super();
}
public static CustomMapFragment newInstance(LatLng position) {
CustomMapFragment fragment = new CustomMapFragment();
mPosFija = position;
return fragment;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getMap() != null) {
initMap();
Log.d(getClass().getSimpleName(), "Map ready for use!");
}
}
#Override
public void onResume() {
super.onResume();
initMap();
}
private void initMap() {
Log.v("CustomMapFragment", "initMap");
if (getMap() != null) {
UiSettings settings = getMap().getUiSettings();
settings.setAllGesturesEnabled(true);
settings.setMyLocationButtonEnabled(false);
getMap().clear();
getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(mPosFija, 5));
getMap().addMarker(new MarkerOptions().position(mPosFija).draggable(false));
}
}
}
This is the code for my DialogFragment that adds the mapFragment to the view:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()) == ConnectionResult.SERVICE_INVALID
|| GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()) == ConnectionResult.SERVICE_MISSING) {
Log.e("HERE", "Google play not active");
TextViewFragment tvf = new TextViewFragment();
getChildFragmentManager().beginTransaction().replace(R.id.mapview, tvf).commit();
} else {
CustomMapFragment mMapFragment = CustomMapFragment.newInstance(new LatLng(offer.latitude, offer.longitude));
getChildFragmentManager().beginTransaction().replace(R.id.mapview, mMapFragment).commit();
}
}
Ok, so this was staring me in the face and was as simple as
UiSettings settings = getMap().getUiSettings();
settings.setAllGesturesEnabled(false);
settings.setMyLocationButtonEnabled(false);
settings.setZoomControlsEnabled(false);
I have a GoogleMap which displays fine (within a SupportMapFragment) and uses the GoogleMapOptions for the target camera location. However, I am unable to add markers/polylines to the GoogleMap. Here is the method for creating the map:
private void createMap(List<LatLng> latLngs) {
if(map == null) {
GoogleMapOptions options = new GoogleMapOptions();
mapFragment = SupportMapFragment.newInstance(options);
map = mapFragment.getMap();
float zoom = 13;
CameraPosition cameraP = new CameraPosition(latLngs.get(0), zoom, 0, 0);
options.camera(cameraP);
//TODO MAP IS NULL - SORT OUT!
// check it has been instantiated
if (map != null) {
Log.d(TAG, "map is not null");
map.clear();
//Calculate target zoom, based on trip size
map.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraP));
// Add LatLngs to polyline
PolylineOptions poly = new PolylineOptions().color(Color.RED);
MarkerOptions startMarker = new MarkerOptions()
.position(latLngs.get(0)).title("Start");
MarkerOptions endMarker = null;
if(latLngs.size() > 1) {
endMarker = new MarkerOptions().position(
latLngs.get(latLngs.size() - 1)).title("End");
}
for (LatLng latLng : latLngs) {
poly.add(latLng);
}
map.addPolyline(poly);
map.addMarker(startMarker);
map.addMarker(endMarker);
}
ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.trip_summary_map_container, mapFragment);
ft.commit();
}
}
As you can see from the inline comments, the map is still null (although it is displaying and using the options). Just can't add things to it. I assume I am not instantiating it properly?
The Activity extends FragmentActivity, and I have set up all the necessary stuff for using the Maps API.
Thank you for any help.
EDIT: I have posted a new answer with the solution I prefer to use now.
I had the same problem some days ago and I solved it extending SupportMapFragment class so that it executes a callback method once the map is finally ready.
public class ExtendedSupportMapFragment extends SupportMapFragment {
public static interface MapReadyListener {
public void mapIsReady(GoogleMap map);
}
#Deprecated
public static SupportMapFragment newInstance() {
return null;
}
#Deprecated
public static SupportMapFragment newInstance(GoogleMapOptions options) {
return null;
}
public static ExtendedSupportMapFragment newInstance(MapReadyListener mapReadyListener) {
ExtendedSupportMapFragment fragment = new ExtendedSupportMapFragment();
fragment.mapReadyListener = mapReadyListener;
return fragment;
}
private MapReadyListener mapReadyListener;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (mapReadyListener != null)
mapReadyListener.mapIsReady(getMap());
}
}
Then you just need to do something like this:
public class RutaMapaFragment extends SherlockFragment implements ExtendedSupportMapFragment.MapReadyListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragmentMapa = ExtendedSupportMapFragment.newInstance(RutaMapaFragment.this);
}
...
#Override
public void mapIsReady(GoogleMap map) {
//Do whatever you want with your map.
}
}
So, time has passed and all. The fact is that I don't use the solution in my previous answer anymore, but prefer to use a ViewTreeObserver instead. The following code shows a rather simple fragment with a SupportMapFragment being added to it.
The method createMap() adds the SupportMapFragment and then executes setupMap(), but only via a OnGlobalLayoutListener that will basically be executed once the map is actually ready. Of course, this listener is removed immediately—there's no need to keep it there any longer.
public class MyMapFragment extends Fragment {
private View mMapContainer;
private SupportMapFragment mMapFragment;
private GoogleMap mMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(/* ... */);
// ...
mMapContainer = view.findViewById(R.id.map_fragment_container);
createMap();
return view;
}
private void createMap() {
mMapFragment = new SupportMapFragment();
getFragmentManager().beginTransaction()
.replace(R.id.map_fragment_container, mMapFragment)
.commit();
mMapContainer.getViewTreeObserver()
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
mMapContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
mMapContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
mMap = mMapFragment.getMap();
setupMap();
}
});
}
private void setupMap() {
mMap.setMyLocationEnabled(true);
// ...
}
}
Try to add the Marker & PolyLines in the map using below code:
GoogleMap mMap;
static final CameraPosition BONDI =
new CameraPosition.Builder().target(new LatLng(-33.891614, 151.276417))
.zoom(15.5f)
.bearing(300)
.tilt(50)
.build();
changeCamera(CameraUpdateFactory.newCameraPosition(BONDI));
mMap.addMarker(new MarkerOptions().position(new LatLng(-33.891614, 151.276417)).title("Bondi"));
private void changeCamera(CameraUpdate update) {
changeCamera(update, null);
}
/**
* Change the camera position by moving or animating the camera depending on the state of the
* animate toggle button.
*/
private void changeCamera(CameraUpdate update, CancelableCallback callback) {
boolean animated = ((CompoundButton) findViewById(R.id.animate)).isChecked();
if (animated) {
mMap.animateCamera(update, callback);
} else {
mMap.moveCamera(update);
}
}
Add the PolyLines as below:
// A simple polyline with the default options from Melbourne-Adelaide-Perth.
mMap.addPolyline((new PolylineOptions())
.add(BONDI));