Cannot cast from Fragment to SupportMapFragment - android

public class OutdoorFragment extends Fragment {
private GoogleMap googleMap;
double latitude = 1.31039;
double longitude = 103.7784;
public OutdoorFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_outdoor, container,
false);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.setMyLocationEnabled(true);
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Koh Chi Hao ");
// adding marker
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET));
googleMap.addMarker(marker);
return rootView;
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getActivity().getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
public void onResume() {
super.onResume();
initilizeMap();
}
}
Hi there, inside my initializeMap() , googleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); keeps on saying that Cannot cast from Fragment to SupportMapFragment . I am not sure what is happening .
Thanks in advance

Change;
googleMap = ((SupportMapFragment) getFragmentManager().
findFragmentById(R.id.map)).getMap();
with this;
googleMap = ((SupportMapFragment) getSupportFragmentManager().
findFragmentById(R.id.map)).getMap();
Note that getSupportFragmentManager is from android.support.v4.app.FragmentActivity.
Good luck.

You need to use android.support.v7.app.Fragment;
And need to use getSupportFragmentManager
Basically you need v7 library

Check your activity layout. The fragment with map must have the following attribute name="com.google.android.gms.maps.SupportMapFragment" to indicate which fragment class you use.

Related

How to use getMapAsync() instead of getMap()

I am aware that in Play Services, getMap() is depreciated, and is replaced by getMapAsync().
But I am not sure how to use getMapAsync(). I found other questions similar to this -- however, in my code, I am not sure what to implement in my getMapAsync(). I think it is supposed to be a callback method, but I am not sure.
Could someone please put the correct code in, and tell me what I am doing wrong?
public class FindParty extends AppCompatActivity {
static final LatLng Durban = new LatLng(-29.858680, 31.021840);
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_party);
try{
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMapAsync();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
final Marker marker_Durban = googleMap.addMarker(new MarkerOptions()
.position(Durban)
.snippet("Durban, KwaZulu-Natal, South Africa")
.title("Durban"));
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
if (marker.getTitle().equals("Durban")) {
Intent intent = new Intent(FindParty.this, Party.class);
intent.putExtra("message", "Durban");
startActivity(intent);
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
your class need to implements OnMapReadyCallback
public class FindParty extends AppCompatActivity implements OnMapReadyCallback {
static final LatLng Durban = new LatLng(-29.858680, 31.021840);
private GoogleMap googleMap;
MapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_party);
try {
if (googleMap == null) {
mapFragment = ((MapFragment) getFragmentManager().findFragmentById(R.id.map));
mapFragment.getMapAsync(this);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onMapReady(GoogleMap map) {
googleMap = map;
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
final Marker marker_Durban = googleMap.addMarker(new MarkerOptions()
.position(Durban)
.snippet("Durban, KwaZulu-Natal, South Africa")
.title("Durban"));
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
if (marker.getTitle().equals("Durban")) {
Intent intent = new Intent(FindParty.this, Party.class);
intent.putExtra("message", "Durban");
startActivity(intent);
}
}
});
}
}
You are right, getMapAsync() is based on callback, please see belowe example and move your map options settings to callback method:
Example
getMapAsync() { it.isTrafficEnabled = false }
The better way I found to understand the use of getMapAsync was to create a new project in Android Studio and use the template of google maps activity instead of an empty activity.
Hope help others with the same difficulty.

google map is not showing marker on it

this is my activity
public class FindPeopleFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap googleMap;
MapFragment fragment;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_find_people, container, false);
initilizeMap();
return rootView;
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void initilizeMap() {
MapFragment fragment = (MapFragment) getChildFragmentManager().findFragmentById(R.id.map1);
if (fragment != null) {
fragment.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng marker = new LatLng(44.797283, 20.460663);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(44.797283, 20.460663), 12));
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(44.797283, 20.460663))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
googleMap.setMyLocationEnabled(true);
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public void onPause() {
final FragmentManager fragManager = this.getFragmentManager();
final Fragment fragment = fragManager.findFragmentById(R.id.map1);
if (fragment != null) {
fragManager.beginTransaction().remove(fragment).commit();
super.onPause();
}
}
#Override
public void onDestroy() {
super.onDestroy();
final FragmentManager fragManager = this.getFragmentManager();
final Fragment fragment = fragManager.findFragmentById(R.id.map1);
if (fragment != null) {
fragManager.beginTransaction().remove(fragment).commit();
}
}
}
I am using navigation drawer to show the map. my map is working but the marker on it does not show. I have used all permission and created the xml file well. I don't know what is the problem, I can't find a solution for this anywhere. I think I am having problem as I am using fragment, but I need it as I am using navigation drawer. please anybody? give me a solution, I'm stuck at this
You should implement onMapReadyCallback, you should set marker when map is ready. Once an instance of this interface is set on a MapFragment or MapView object, the onMapReady(GoogleMap) method is triggered when the map is ready to be used and provides a non null instance of GoogleMap.
The onMapReady() and method might not being called. Try to implement SupportMapFragment object that you retrieved from the XML layout. Then, call getMapAsync().
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final GoogleMap googleMap) {
// ...
}
});

getmap error on Google Maps in a fragment

I try some Code with a Map in a fragemt.
It works but the Map ID didnt found.
I get the warning that getMap is deprecated.
public class MapsActivity 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.activity_maps, container,
false);
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
googleMap = mMapView.getMap();
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
The getMap() method in MapView and MapFragment is now deprecated in
favor of the new getMapAsync() method.
Google provided sample code for this:
public class MainActivity extends FragmentActivity
implements OnMapReadyCallback {
...
}
and when initializing fragment:
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
when map is ready, you callback will be called
#Override
public void onMapReady(GoogleMap map) {
map.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Marker"));
}
Please one try to change the app:gradle because the getMap() helps some versions like
compile 'com.google.android.gms:play-services-maps:7.8.0'
compile 'com.google.android.gms:play-services-location:7.8.0'
then try to sync the code again!

App crashes when I close the app [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 8 years ago.
I have integrated Google Maps in ViewPager and afterward, when I close my app by pressing back button, I get "Unfortunately app has closed" message. If anyone have gone through issue and get solved, please let me know how to solve it.
Code
public class NearestBathroomMapView extends Fragment {
//Declare all necessary objects
public static View view;
public static GoogleMap gMap;
public static Double latitude,longitude;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(container==null){
return null;
}
//Inflate the view
view= inflater.inflate(R.layout.bathroomsmapview,
container, false);
latitude=27.706750;//declare latitude and logitude
longitude=85.314513;
setUpIfMapNeeded();
//call this function to obtain SupportMapFragment
return view;
}
//Get the map from SupportMapFragment
public void setUpIfMapNeeded(){
// Try to obtain the SupportMapFragment if map does not equal null.
if (gMap == null) {
gMap = ((SupportMapFragment) BathroomInformation.fragmentManager
.findFragmentById(R.id.location_map)).getMap();
//call this function to display map
if (gMap != null){
setUpMap();
}
}
}
private void setUpMap() {
gMap.setMyLocationEnabled(true);
//add marker in map
gMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My Home").snippet("Home Address"))
//setup map position and animate it
gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,
longitude), 12.0f));
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//view created to display map
if (gMap != null)
setUpMap();
//get SupportMapFragment if map is equal to null
if (gMap == null) {
gMap = ((SupportMapFragment) BathroomInformation.fragmentManager
.findFragmentById(R.id.location_map)).getMap();
//set up map if map is not null
if (gMap != null)
setUpMap();
}
}
//should I need to call this below function onBackPressed method ??
public void onDestroyView() {
super.onDestroyView();
//map fragment get remove from FragmentManager
if (gMap != null) {
BathroomInformation.fragmentManager.beginTransaction()
.remove(BathroomInformation.fragmentManager
.findFragmentById(R.id.location_map)).commit();
gMap = null;
}
}
}
I think you should eliminate your
public void onDestroyView()
function. I don't see correct to remove a fragment that is destroyed.
Hope it helps.

How to get Google Maps object inside a Fragment

I am using fragments in my application and I am new for this. There is a fragment in which I want to display Google Map and want to get its object, for this I have a fragment in my XML and I want to inflate it in the Fragment itself. When I am trying to inflate the map view its showing me error for getSupportFragmentManager().
How do I get the map object then that is the main issue. My XML is like this :-
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="250dp"
class="com.google.android.gms.maps.SupportMapFragment" />
And my Fragment in which I want to get the Google Map object is like that :-
public class FindMyCar extends Fragment {
private TextView mTvFind;
private TextView mTvPark;
private EditText mEtParkHint;
private GoogleMap map;
#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.findmycar, null);
initViews(view);
Typeface type = Typeface.createFromAsset(getActivity().getResources().getAssets(),"Multicolore.otf");
mTvFind.setTypeface(type);
mTvPark.setTypeface(type);
mEtParkHint.setTypeface(type);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
return view;
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void initViews(View view){
mTvPark = (TextView) view.findViewById(R.id.tvFindCarPark);
mTvFind = (TextView) view.findViewById(R.id.tvFindCar);
mEtParkHint = (EditText) view.findViewById(R.id.etParkHint);
}
Can someone help me to get the object for my map so that I can show current location and draw the marker there.
Any help would be appreciable.
Thanks in advance.
getMap() method is deprecated
getMap() method is deprecated but after the play-services 9.2it is removed, so better use getMapAsync(). You can still use getMap() only if you are not willing to update the play-services 9.2 for your app.
To use getMapAsync(), implement the OnMapReadyCallback interface on your activity or fragment:
For fragment:
public class MapFragment extends android.support.v4.app.Fragment
implements OnMapReadyCallback { /* ... */ }
Then, while initializing the map, use getMapAsync() instead of getMap():
//call this method in your onCreateMethod
private void initializeMap() {
if (mMap == null) {
SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.fragment_map);
mapFrag.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap();// do your map stuff here
}
For Activity:
public class MapActivity extends FragmentActivity
implements OnMapReadyCallback { }
Then, while initializing the map, use getMapAsync() instead of getMap():
//call this method in your onCreateMethod
private void initializeMap() {
if (mMap == null) {
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_map);
mapFrag.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap();// do your map stuff here
}
Fragment in XML:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Try this
GoogleMap map = ((SupportMapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
and in your xml
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
Try this it works for me
How to put Google Maps V2 on a Fragment Using ViewPager
<Fragment
android:id="#+id/map"
android:layout_width="wrap_content"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
GoogleMap mGoogleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMap();
Try this i have made this as a sample according to your need
public class LocationMapActivity extends FragmentActivity {
private GoogleMap mMap;
static boolean Iscamera = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.locatio_map);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
if (mMap != null) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getMaxZoomLevel();
mMap.getMinZoomLevel();
mMap.getUiSettings();
mMap.animateCamera(CameraUpdateFactory.zoomIn());
mMap.animateCamera(CameraUpdateFactory.zoomOut());
mMap.animateCamera(CameraUpdateFactory.zoomTo(20));
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
mMap.clear();
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(arg0.getLatitude(), arg0
.getLongitude()))
.title("I am Here!!")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.map_icon)));
if (!Iscamera) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(arg0.getLatitude(), arg0
.getLongitude()), 14));
Iscamera = true;
}
try {
if (Constant.FORTNAME.equals("Arad Fort")) {
mMap.addMarker(new MarkerOptions()
.position(new LatLng(26.2525, 50.6269))
.title(Constant.FORTNAME)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.greenicon)));
} else if (Constant.FORTNAME.equals("Bahrain Fort")) {
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(26.2333598,
50.52035139))
.title(Constant.FORTNAME)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.greenicon)));
} else if (Constant.FORTNAME
.equals("International Circuit")) {
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(26.0303251,
50.51121409))
.title(Constant.FORTNAME)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.greenicon)));
} else if (Constant.FORTNAME
.equals("Khamis Mousque")) {
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(26.158719, 50.516426))
.title(Constant.FORTNAME)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.greenicon)));
} else if (Constant.FORTNAME
.equals("king fahad causeway")) {
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(26.1723987,
50.4579942))
.title(Constant.FORTNAME)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.greenicon)));
} else if (Constant.FORTNAME.equals("Riffa Fort")) {
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(26.11771965026855,
50.56298065185547))
.title(Constant.FORTNAME)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.greenicon)));
} else if (Constant.FORTNAME
.equals("Royal Golf Club")) {
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(26.13000, 50.55500))
.title(Constant.FORTNAME)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.greenicon)));
} else if (Constant.FORTNAME.equals("Tree of life")) {
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(25.9940396,
50.583135500000026))
.title(Constant.FORTNAME)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.greenicon)));
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
e.getMessage(), Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
});
}
}
}
// ********************************************************************************************
#SuppressWarnings("unused")
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title(
"Marker"));
}
}
public class MapActivity extends FragmentActivity
implements OnMapReadyCallback { }
Then, while initializing the map, use getMapAsync() instead of getMap():
//call this method in your onCreateMethod
private void initializeMap() {
if (mMap == null) {
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_map);
mapFrag.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
You can use this to making map but it will return map object is null because you don't find solution with getMapAsync to create a new object mMap. It only background task with return null
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/location_map"
android:layout_above="#id/atmLocation_recyclerView"
/>
View root= inflater.inflate(R.layout.fragment_a_t_m_locations, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.location_map);
mapFragment.getMapAsync(googleMap -> {
mMap=googleMap;
if(mMap!=null){
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
});
Revised code:
Your xml file-
<fragment
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Your java file (only relevant code)-
View view = null, mapView = null;
private GoogleMap mMap;
view = inflater.inflate(R.layout.findmycar, container,false);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager
.findFragmentById(R.id.map);
mMap = supportMapFragment.getMap();
mapView = (View) view.findViewById(R.id.map);

Categories

Resources