I try display Google Maps inside my Fragment. The problem is when I run my project I do not see this maps. The additional information is this fragments belongs to Pager View.
This is my sample of code:
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
thisContext = inflater.getContext();
View view = inflater.inflate(R.layout.tab_fragment_2, container, false);
loadMap();
// initializeMap();
locationManager = (LocationManager) thisContext.getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(thisContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(thisContext, android.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 null;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, this);
return view;
}
private void initializeMap() {
if (map == null) {
SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
}
private void loadMap() {
SupportMapFragment mSupportMapFragment;
mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
if (mSupportMapFragment == null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
mSupportMapFragment = SupportMapFragment.newInstance();
fragmentTransaction.replace(R.id.map, mSupportMapFragment).commit();
}
if (mSupportMapFragment != null) {
mSupportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
if (googleMap != null) {
googleMap.getUiSettings().setAllGesturesEnabled(true);
// -> marker_latlng // MAKE THIS WHATEVER YOU WANT
//CameraPosition cameraPosition = new CameraPosition.Builder().target(marker_latlng).zoom(15.0f).build();
// CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
// googleMap.moveCamera(cameraUpdate);
}
}
});
}
}
The problem is when I run my project I do not see this maps.
You can use the default 'new Activity' wizard to create Google maps activity.
It includes all the information you need. See the 7th item in the following screenshot.
The best thing so far I know for Fragment is to use MapView instead of MapFragment. I am using MapView inside a Navigation Drawer Fragment and its working fine with all callbacks that I need and PlacesAutoComplete.
Related
I want to show mylocationbutton in my app. For that, I added setMyLocationEnabled(true) in my code. But it's not working. Please suggest me a solution for this. Here is my code.
My minimum and maximum sdk are 16 and 26 respectively
here is my mapFragment where I wrote my code to set myLocation button
MapFragment.java
public class MapFragment extends Fragment implements OnMapReadyCallback {
private static final int PLACE_AUTOCOMPLETE_REQUEST_CODE = 1;
private GoogleMap mMap;
private boolean isUp;
private View addressView,mapView;
private View searchLayout;
private TextView addressLine1, addressLine2;
private Button cancel, select;
private Geocoder geocoder;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
//ToDo : Replace with orginal view
View view = inflater.inflate(R.layout.fragment_map, null, false);
init(view);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mapView = mapFragment.getView();
setListeners();
return view;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), 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;
}
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.setMyLocationEnabled(true);
isUp = false;
addressView.setVisibility(View.INVISIBLE);
// Add a marker in Sydney and move the camera
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
setUpMarker(latLng);
geocoder = new Geocoder(getContext());
try {
List<Address> addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
search(addresses);
} catch (IOException e) {
e.printStackTrace();
}
}
});
if (mapView != null &&
mapView.findViewById(Integer.parseInt("1")) != null) {
// Get the button view
View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
// and next place it, on bottom right (as Google Maps app)
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
locationButton.getLayoutParams();
// position on right bottom
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 30, 30);
}
}
}
My xml file
fragment_map.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
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"
tools:context=".activities.HomeActivity" />
Permissions in manifest file
Manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
A long time i used this code, to 'reuse' a GoogleMap in Fragment - when switching to another Fragment and opening the MapFragment again, the Map and all its content was as before (no zooming-in again, no need to re-set Markers, it was 'just in background' and brought to front again):
public class MapFragmentGoogle extends Fragment implements SensorEventListener, OnMapLoadedCallback {
private static View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null)
parent.removeView(rootView);
}
try {
rootView = inflater.inflate(R.layout.fragment_map_google, container, false);
} catch (InflateException e) {
//
}
return rootView;
So now i switched from eclipse to AndroidStudio (i kow i'm late), which is implementing the latest PlayServices and i cannot use
map = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.gmap)).getMap();
anymore and the 'Reuse-Code" does not work anymore. I'am getting tiered about those things.
How can i have a GoogleMap, which stays exactly as it is, no new init, no zomming from space to place, not redrawing Polylines and Markersetc etc when switching to another fragment and then back to the mapfragment?
You can still use supportmapfragment, please find the code below:
XML:
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
android:id="#+id/search1"
>
code:
SupportMapFragment mapFragment;
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.maps);
mapFragment.getMapAsync(this);
ldb = new LocationDatabase(this);
intentlat = null;
intentlng = null;
public void onMapReady(GoogleMap googleMap) {
m_map = googleMap;
map_false = true;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
m_map.setMyLocationEnabled(true);
m_map.getUiSettings().setMapToolbarEnabled(true);
m_map.getUiSettings().setZoomControlsEnabled(true);
m_map.getUiSettings().setZoomGesturesEnabled(true);
m_map.getUiSettings().setMyLocationButtonEnabled(true);
geocoder = new Geocoder(this, Locale.getDefault());
addresses = null;
if (intentlat == null && intentlng == null) {
LatLng target3 = new LatLng(<latitude>, <81.488100>);
CameraPosition nnn = CameraPosition.builder().target(target3).zoom(14).build();
m_map.animateCamera(CameraUpdateFactory.newCameraPosition(nnn), 2000, null);
CameraPosition nnn = CameraPosition.builder().target(target3).zoom(14.0f).build();
m_map.animateCamera(CameraUpdateFactory.newCameraPosition(nnn), 2000, null);
}
I have been working in Navigation Drawer Activity, it has many fragments and one of the fragment contains MapFragment.
Now there is a problem in MapFragment i-e When for the first time i open the fragment that contains MapFragment inside it everything works fine, but once i navigate to some other fragment using getFragmentManager().beginTransaction().replace(...)
and then return to previous fragment using getFragmentManager().popBackStack();
My mapFragment.getView() does not works, you can review my code for MapFragment
private void initMap() {
if (mapFragment == null)
mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapView);
if (mapFragment == null)
mapFragment = (MapFragment) this.getChildFragmentManager().findFragmentById(R.id.mapView);
if (mapFragment == null) {
Toast.makeText(getActivity(), "mapFragment not initialized", Toast.LENGTH_SHORT).show();
}
if (mapFragment.getView() == null) {
Toast.makeText(getActivity(), "getView not initialized", Toast.LENGTH_SHORT).show();
}
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
Toast.makeText(getActivity(), "map intialized", Toast.LENGTH_SHORT).show();
// For showing a "move to my location" button
CheckPermissions cp = new CheckPermissions(getActivity());
if (cp.getPermission(Manifest.permission.ACCESS_COARSE_LOCATION) || cp.getPermission(Manifest.permission.ACCESS_FINE_LOCATION)) {
// enableMyLocation();
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION);
}
mUiSettings = mMap.getUiSettings();
mUiSettings.setZoomControlsEnabled(true);
mUiSettings.setCompassEnabled(true);
cameraListener();
markerListener();
mapListener();
}
});
}
above method is called if following method
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initMap();
if (mapFragment.getView() != null) {
mapFragment.getView().setVisibility(View.GONE);
}
}
i have searched a lot on every platform but not getting any help.
and i do not want to use SupportFragmentManager because i'm not creating this app for older android versions.
Any help would be appreciable.
Regards.
UPDATE
I have sorted my problem temporarily by putting MapFragment inside RelativeLayout and hiding this RelativeLayout
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initMap();
relativeLayout = (RelativeLayout) view.findViewById(R.id.rel_layout);
if (relativeLayout != null) {
relativeLayout.setVisibility(View.GONE);
}
}
I think your first line of code is what makes your fragment disappear.
Delete this:
if (mapFragment == null)
mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapView);
Whenever you are adding a fragment as child to existing fragment, you want to use getChildFragmentManager().
EDIT:
To show / hide / remove child fragment, you can use one of the following methods:
getChildFragmentManager().beginTransaction().hide(fragment).commit();
getChildFragmentManager().beginTransaction() has various methods for managing fragments, such as show / remove / replace / add, etc.
You can try these, though I'm not sure why you wish to hide MapFragment immediately after creating it.
I can access map when I call the fragment first time but when I call the fragment second time it gives me this caused by error:
12-26 09:36:41.306: E/AndroidRuntime(28156): Caused by: java.lang.IllegalArgumentException: Binary XML file line #164: Duplicate id 0x7f090012, tag null, or parent id 0x0 with another fragment for com.google.android.gms.maps.SupportMapFragment
I create the inner map fragment in my fragment class' onCreateView():
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Defines the xml file for the fragment
View view = inflater.inflate(R.layout.howtogo_fragment, container,
false);
if(map==null)
map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
}
here is the layout of my fragment:
<LinearLayout>
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</LinearLayout>
Try this .
private static GoogleMap mMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
view = (RelativeLayout) inflater.inflate(R.layout.howtogo_fragment, container, false);
MapLoad(); // For setting up the MapFragment
return view;
}
/***** Sets up the map if it is possible to do so *****/
public static void MapLoad() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) YOURACTIVITY.fragmentManager
.findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null)
setUpMap();
}
}
private static void setUpMap() {
// For showing a move to my loction button
mMap.setMyLocationEnabled(true);
// For dropping a marker at a point on the Map
// mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My Home").snippet("Home Address"));
// For zooming automatically to the Dropped PIN Location
// mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,
// longitude), 12.0f));
}
You can try my code:
xml code:
<RelativeLayout 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"
android:background="#android:color/white"
tools:context="com.example.catalyst_home.GeolocationActivity$PlaceholderFragment" >
<RelativeLayout
android:id="#+id/map_root"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</RelativeLayout>
Fragment java:
private GoogleMap mMap;
private SupportMapFragment mMapFragment;
private void setUpMapIfNeeded() {
if (mMap == null) {
mMapFragment = SupportMapFragment.newInstance();
FragmentTransaction fragmentTransaction = getChildFragmentManager()
.beginTransaction();
fragmentTransaction.add(R.id.map_root, mMapFragment);
fragmentTransaction.commit();
}
}
in onResum of fragment:
#Override
public void onResume() {
super.onResume();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mMap = mMapFragment.getMap();
if (mMap != null) {
mMap.setMyLocationEnabled(true);
}
}
}, 2000);
}
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);
}
}
}