Implementing a google map fragment to an activity - android

I am having a hard time implementing my google map fragment into an activity and from everything else I'me reading I'm getting more confused.
#Override
public void onStart() {
super.onStart();
try {
mListener = (OnFragmentInteractionListener) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(getActivity().toString()
+ " must implement OnFragmentInteractionListener");
}
}
This section crashes my app gives me the error must implement OnFragmentInteractionListener. Which I find confusing since I thought that since it was part of the throw it would prevent the app from crashing regardless of if the error was there.
In my main method I have
private void addMapFragment(){
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = manager.beginTransaction();
MapFragment fragment = new MapFragment();
transaction.add(R.id.mapView, fragment);
transaction.commit();
}
Which is called in the onCreate method. Honestly I just don't exactly where to look. I feel like I have something somewhere else causing the crash but I cant figure out what it is. So I don't know if this is relevant but here is the code that also exists in the same file as the onStart method
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.map_fragment, container, false);
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
googleMap = mMapView.getMap();
//Latitude and longitude ????
double latitude = 17.385044;
double longitude = 78.486671;
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello Maps");
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
return v;
}

Related

Mapview in separate fragment android

I want to have a mapview like this suppose my main activity is like this
Here my main activity holds the instance of mapview in main activity and then when I click on it ,then a new activity should be opened with the map activity in android
You need to have the supportMapFragment in your xml file and get the reference of mapFragment into your MainFragment. The below code explains, How I accomplished the MapView inside Fragment. Write the below XML code in the mapView.xml and then Use the Fragment OnCreateView to get references.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainMap"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="200dp"
/>
public class MapInFragment extends Fragment implements OnMapReadyCallback {
private View rootView;
private GoogleMap mMap;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.mapView, container, false);
try{
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mainMap);
mapFragment.getMapAsync(MapInFragment.this);
}catch (Exception e){
e.printStackTrace();
}
return rootView;
}
#Override
public void onMapReady(GoogleMap googleMap) {
try {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng croplatlng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
mMap.addMarker(new MarkerOptions().position(croplatlng).title(crop + "Field"));
//mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(croplatlng,16));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(croplatlng , 16);
//mMap.addMarker(new MarkerOptions().position(location).title(""));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation ));
mMap.animateCamera(cameraUpdate,2000,null);
}catch (Exception e){
e.printStackTrace();
}
}
public void onDestroyView()
{
try {
Fragment fragment = (getChildFragmentManager().findFragmentById(R.id.mainMap));
if (fragment != null) {
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
}catch (Exception e){
e.printStackTrace();
}
super.onDestroyView();
}
}
Step 1:
Add Mapview on your main activity.
Step 2:
Add OnClickListener on MapView
mMapView.getMap().setOnMapClickListener(new OnMapClickListener()
{
#Override
public void onMapClick(LatLng arg0)
{
//Open New Activity
}
});
Step 3:
Open New Activiy to show your map.
Hope you will find this answer usefull.
Happy Coading

Marker's not showing: Google Map Android

In my project I'm loading my maps programmatically on a fragment. However, adding markers on this map is not working. No error is shown but the marker is not on the map as well.
I'm following the specification so i have no idea why it is not working.
(Lat and Lng of the marker and the camera are the same)
My Fragment Code
public class MainMapFragment extends Fragment implements OnMapReadyCallback {
SupportMapFragment mMapFragment;
static final LatLng LIBRARY = new LatLng(Lat, Lng);
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
return inflater.inflate(R.layout.main_map_layout,container,false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
//Set the initial stage of the map
//It is set on code (not on the xml) because the map is created programmatically
GoogleMapOptions options = new GoogleMapOptions();
CameraPosition ufv_position = new CameraPosition.Builder()
.target(new LatLng(Lat,Lng))
.zoom(15)
.tilt(0)
.bearing(40)
.build();
options.mapType(GoogleMap.MAP_TYPE_NORMAL)
.compassEnabled(false)
.rotateGesturesEnabled(false)
.tiltGesturesEnabled(false)
.camera(ufv_position);
//Load the map with the given options
mMapFragment = SupportMapFragment.newInstance(options);
FragmentTransaction fragmentTransaction =
getChildFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.map, mMapFragment);
fragmentTransaction.commit();
}
#Override
public void onMapReady(GoogleMap googleMap) {
googleMap.addMarker(new MarkerOptions()
.position(LIBRARY)
.title("Library")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.book)));
}
}
add mMapFragment.getMapAsync(this); so your onMapReady method gets called

Map does not detect touches/swipes in android

I followed this tutorial to add a map to one of my tabs. It works, but when I open the map tab I cannot swipe up/down, zoom in/out (except when I double click). Swiping left/right works, but the map moves very little. I made a customViewPager, and it disables swiping the tabs, but does nothing for he map.
At first I used tabActivity and my map fragment worked as it should, and looked like this:
mapActivity extends FragmentActivity...
Since tabActivity is deprecated I added sliding tabs, following the tutorial above. Map could not be added with FragmentActivity, only with Fragment so I changed map fragment to:
mapActivity extends Fragment...
Now I have the following problem - I cannot navigate the map. Swipe and touch inputs are not detected. I cannot move up or down, zoom in or out, and the only thing I can do is move from left to right, but it is very slow.
Try this. its sample . 100% working
public class Map extends Fragment {
final int RQS_GooglePlayServices = 1;
Location myLocation;
TextView tvLocInfo;
boolean markerClicked;
PolygonOptions polygonOptions;
Polygon polygon;
// GPSTracker class
GPSTracker gps;
double latitude;
double longitude;
MapView mapView;
GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_map_fragment, container, false);
// TODO Auto-generated method stub
MapsInitializer.initialize(getActivity());
switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity())) {
case ConnectionResult.SUCCESS:
Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT).show();
mapView = (MapView) rootView.findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
if (mapView != null) {
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 13);
map.animateCamera(cameraUpdate);
}
break;
case ConnectionResult.SERVICE_MISSING:
Toast.makeText(getActivity(), "SERVICE MISSING", Toast.LENGTH_SHORT).show();
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
Toast.makeText(getActivity(), "UPDATE REQUIRED", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(getActivity(), GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()), Toast.LENGTH_SHORT).show();
}
gps = new GPSTracker(getActivity());
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
// \n is for new line
// Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
// tvLocInfo = (TextView) findViewById(R.id.locinfo);
/* FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment
= (MapFragment) myFragmentManager.findFragmentById(R.id.map);
map = myMapFragment.getMap();*/
map.setMyLocationEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
markerClicked = false;
map.setMyLocationEnabled(true);
map.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(latitude, longitude));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(11);
map.moveCamera(center);
map.animateCamera(zoom);
}
});
/* LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}*/
// Updates the location and zoom of the MapView
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
/* TextView tv = (TextView) getActivity().findViewById(R.id.textset);
tv.setText("Audio");*/
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
At first I added tabLayout and viewPager to appBarLayout in app_bar_main (I made an app with navigation drawer), and later I moved the appBarLayout to content_main and it worked.

replace, remove fragment and removing view doesn´t work in second run

My app selects one object of the listview and show the map. Works on first time running but in the second didn´t work. On third it works!
This is because of the inflate exception on the second time. It can´t return a view, or inflate it.
I need that every time it is selected something from the navigation drawer brings the map, im using replace and the method mentioned in many questions onDestroy, and obviusly removing the view when it is different from null.
Help would be appreciated!! Thanks!!
Code of the map:
public class mapfragmentplaces extends Fragment implements LocationListener {
protected LocationManager locationManager;
// GoogleMap googleMap;
LatLng myPosition;
private SupportMapFragment map;
private GoogleMap mMapView;
int fragVal2;
static Context ontext;
private static View view;
//lo que se ocupa para construir los sitios
String[] mPlaceType=null;
String[] mPlaceTypeName=null;
double mLatitude=0;
double mLongitude=0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null) {
parent.removeView(view);
}
}
try {
view = inflater.inflate(R.layout.fragment_layout, container, false);
android.support.v4.app.FragmentManager fm = getFragmentManager();
/*
GoogleMapOptions gmo = (new GoogleMapOptions()).zoomControlsEnabled(false).rotateGesturesEnabled(false);
SupportMapFragment mapFragment = SupportMapFragment.newInstance(gmo);
android.support.v4.app.FragmentTransaction fragmentTransaction = getFragmentManager() .beginTransaction();
fragmentTransaction.add(R.id.mapFragmentHole, mapFragment);
fragmentTransaction.commit();
GoogleMap map = mapFragment.getMap(); */
map = (SupportMapFragment) fm.findFragmentById(R.id.map);
/* if (map == null) {
map = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map, map).commit();
} */
// mMapView = fm.getMap();
mMapView = map.getMap();
// Enabling MyLocation Layer of Google Map
mMapView.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
mMapView.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Intent intent = new Intent(getActivity(), Stores.class);
startActivity(intent);
}
});
// Clears all the existing markers
mMapView.clear();
String Lugar = "Plaza fiesta";
String Desc = "Lugar bonito";
Double Lat3 = 25.751188242782035;
Double Lng3 = -100.3097140789032;
// notificacion(Results.toString());
mMapView.addMarker(new MarkerOptions()
.position(new LatLng(Lat3,Lng3))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker1))
.title(Lugar)
.snippet(Desc));
List<HashMap<String, String>> list = setPlaceTag.getList();
if (list!=null){
//((Menu) map).clear();
for(int i=0;i<list.size();i++){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
mMapView.addMarker(markerOptions);
}
}
} catch (InflateException e) {
/* map is already there, just return view as it is */
}
return view;
}
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mMapView.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMapView.animateCamera(CameraUpdateFactory.zoomTo(12));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onDestroyView() {
super.onDestroyView();
Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));
if (fragment != null)
getFragmentManager().beginTransaction().remove(fragment).commit();
}
}
In my main activity Im calling the mapfragmentplaces with this:
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//if (dataList.get(position).getTitle() == null) {
//SelectItem(position);
// } //Toast.makeText(getApplicationContext(), "diste click a sitios", Toast.LENGTH_SHORT).show();
//Currently selected item in spinner first is airport!!!
mTitle = setPlaceTag.getTag() ;
// Creating a fragment object
mapfragmentplaces rFragment = new mapfragmentplaces();
// Creating a Bundle object
Bundle data = new Bundle();
// Setting the index of the currently selected item of mDrawerList
data.putString("position", setPlaceTag.getTag());
// Setting the position to the fragment it is the value of the spinner
rFragment.setArguments(data);
// Getting reference to the FragmentManager
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
// Creating a fragment transaction
android.support.v4.app.FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, rFragment);
// Committing the transaction
ft.commit();
// Closing the drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
}
My xml for maps:
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
Check your onCreateView method. I dont think its the correct way to inflate a xml file in oncreateview method. Please try this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout.,container,false);
//start inflating the view and return the view
map = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
}
A good place to utilize and use view methods is onStart of the fragment.
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
mMapView = map.getMap();
}
Also I see that you are mixing the support package from the fragment. See this line:
android.support.v4.app.FragmentManager fm = getFragmentManager();
Make sure that all your import's and code for fragment are either from support package or from default package(api 11 or greater). This is a common source of bugs like classcastexception.

How to use google map V2 inside fragment?

I have a fragment which is a part of Viewpager, and I want to use Google Map V2 inside that fragment. This is what I have tried so far,
In my fragment,
private SupportMapFragment map;
private GoogleMap mMapView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getChildFragmentManager();
map = (SupportMapFragment) fm.findFragmentById(R.id.map);
if (map == null) {
map = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map, map).commit();
}
}
#Override
public void onResume() {
super.onResume();
if (mMapView == null) {
mMapView = map.getMap();
Marker hamburg = mMapView.addMarker(new MarkerOptions().position(HAMBURG)
.title("Hamburg"));
Marker kiel = mMapView.addMarker(new MarkerOptions()
.position(KIEL)
.title("Kiel")
.snippet("Kiel is cool")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
mMapView.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));
// Zoom in, animating the camera.
mMapView.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
}
and in my layout subfragment_info.xml , I have,
<fragment
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/tableLayout1" />
I can see the map now. But the markers are not showing. I think my Google map mMapView is null. Please help me to get this problem solved. Thanks in advance.
Create a frame for map in which it will be added in your xml layout
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map_container">
<!-- The map fragments will go here -->
</RelativeLayout>
Don't include class="com.google.android.gms.maps.SupportMapFragment" in xml
either in your fragment class do get it manually inside onActivityCreated
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getChildFragmentManager();
fragment = (SupportMapFragment) fm.findFragmentById(R.id.map_container);
if (fragment == null) {
fragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map_container, fragment).commit();
}
/***at this time google play services are not initialize so get map and add what ever you want to it in onResume() or onStart() **/
}
#Override
public void onResume() {
super.onResume();
if (map == null) {
map = fragment.getMap();
map.addMarker(new MarkerOptions().position(new LatLng(0, 0)));
}
}
if you guys face any problem Illegal State Exception Occur just write below code
/*
* This issue Is tracked in (Google Bugs)
* http://code.google.com/p/gmaps-api-issues/issues/detail?id=5064 Added
* Code Due to Illegal State Exception Occur when reclicking on tab
*
* A short-term workaround that fixed it for me is to add the following to
* onDetach() of every Fragment which you call
*/
#Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class
.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
//If you want to show map in activity just extend your Activity by //FragmentActivity write code mention below
In onCreate
FragmentManager fm = getSupportFragmentManager();
fragment = (SupportMapFragment) fm.findFragmentById(R.id.map_container);
if (fragment == null) {
fragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map_container, fragment)
.commit();
}
In onResume
#Override
protected void onResume() {
super.onResume();
if (googleMap == null) {
initilizeMap();
}
}
private void initilizeMap() {
if (googleMap != null) {
googleMap = fragment.getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(10).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(
latitude, longitude));
// ROSE color icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
Additional help can get from these links
https://code.google.com/p/gmaps-api-issues/issues/detail?id=5064#c1
https://developers.google.com/maps/documentation/android/map
You have to decide if you create your fragment in code new SupportMapFragment() or inflate from xml class="com.google.android.gms.maps.SupportMapFragment".
Actually you cannot have a Fragment in xml for another Fragment. Read about nested Fragments.
You may follow this comment on how to add nested SupportMapFragment.
I had more or less the same problem. I had a Navigation Drawer and I wanted to put the map in a fragment.
I followed this thread (but it is in Spanish):
https://groups.google.com/forum/#!msg/desarrolladores-android/1cvqPm0EZZU/Q801Yvb2ntYJ
The clue was (in my opinion) to change the layout.xml file:
Instead of a "fragment" inside your "layout subfragment_info.xml" you would need to change to this:
<com.google.android.gms.maps.MapView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />`
Here it is the code inside the thread (you could use it and adapt):
https://groups.google.com/d/msg/desarrolladores-android/1cvqPm0EZZU/9srw_9feamUJ
my approach is:
Bundle bundle = new Bundle();
bundle.putInt(MY_ID, id);
FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.customer_details_fragment);
fragment = new SalesFragment();
fm.beginTransaction()
.add(R.id.customer_details_fragment, fragment)
.commit();
fragment.setArguments(bundle);
For MapFragment
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
In your Fragment Class
map = ((MapFragment) getActivity().getFragmentManager()
.findFragmentById(R.id.map)).getMap();
map.addMarker(new MarkerOptions().position(
new LatLng(13.031902, 80.278823)).title("Marker Title"));
For SupportMapFragment
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
In your Fragment Class
map = ((SupportMapFragment) getActivity().getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
map.addMarker(new MarkerOptions().position(
new LatLng(13.031902, 80.278823)).title("Marker Title"));
Note - SupportMapFragment map render once user touchs the map
In link , answer for you:
"The problem is that what you are trying to do shouldn't be done. You shouldn't be inflating fragments inside other fragments. From Android's documentation:
Note: You cannot inflate a layout into a fragment when that layout includes a . Nested fragments are only supported when added to a fragment dynamically.
While you may be able to accomplish the task with the hacks presented here, I highly suggest you don't do it. Its impossible to be sure that these hacks will handle what each new Android OS does when you try to inflate a layout for a fragment containing another fragment.
The only Android-supported way to add a fragment to another fragment is via a transaction from the child fragment manager."
For this problem:
Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment
For me, the best solution are of #DeepakPanwar
For Load map into fragment:
<fragment
android:id="#+id/fragmentMap1"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
For .java:
public class PathFragment extends Fragment {
View view;
GoogleMap mMap;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_path,null);
setupMap();
return view;
}
private void setupMap()
{
if (mMap == null)
{
mMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.fragment_map1)).getMap();
mMap.getUiSettings().setZoomControlsEnabled(true);
}
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
getlocation();
}
});
}
public void getlocation()
{
try
{
/*Collect Source and destination latitude and longitude
* To draw Polyline
* */
LatLng src = new LatLng(Double.parseDouble(AppGlobal.WorkerHistory.getOrder_lat()),Double.parseDouble(AppGlobal.WorkerHistory.getOrder_lng()));
LatLng dest =new LatLng(Double.parseDouble(AppGlobal.WorkerHistory.getWorker_lat()),Double.parseDouble(AppGlobal.WorkerHistory.getWorker_lng()));
//Add Marker
mMap.addMarker(new MarkerOptions()
.position(src)
.title("Source")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.srcicon)));
mMap.addMarker(new MarkerOptions()
.position(dest)
.title("Destination")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.desticon)));
Polyline line = mMap.addPolyline(
new PolylineOptions().add(
new LatLng(src.latitude, src.longitude),
new LatLng(dest.latitude, dest.longitude)
).width(5).color(Color.RED).geodesic(true)
);
//set zoom level
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(src);
builder.include(dest);
LatLngBounds bounds = builder.build();
int padding = 0; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
mMap.animateCamera(cu);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
This is how I did it
in layout:
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight=".90"
class="com.google.android.gms.maps.SupportMapFragment"
/>
in code:
public class GPS extends FragmentActivity {
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (supportMap == null) {
// Try to obtain the map from the SupportMapFragment.
supportMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (supportMap != null) {
MarkerOptions mo = new MarkerOptions().position( new LatLng( latitude, longitude ) );
supportMap.addMarker( mo );
}
}
}
}
Took me a lot of fiddling, you need just the right combination of things, make sure your class extends FragmentActivity
If I replace the fragment, where the map fragment is in (in this code example MyFragment) with a different fragment and then come back, I get an IllegalStateException
public class Home_Map extends Fragment {
GoogleMap googleMap;
FragmentManager myFragmentManager;
SupportMapFragment mySupportMapFragment;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.fragment_home__map, container, false);
//googleMap.setMyLocationEnabled(true);
try {
// Loading map
initilizeMap();
googleMap.setMyLocationEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
return rootView;
}
private void initilizeMap() {
try
{
if (googleMap == null) {
myFragmentManager = getFragmentManager();
mySupportMapFragment = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map2);
googleMap = mySupportMapFragment.getMap();
if (googleMap == null) {
Toast.makeText(getActivity().getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
} catch (Exception e) { Toast.makeText(getActivity().getApplicationContext(), ""+e, 1).show();
// TODO: handle exception
}
}
#Override
public void onResume() {
super.onResume();
initilizeMap();
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
try {
Field childFragmentManager = Fragment.class
.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}

Categories

Resources