I am trying to implement PlaceAutoCompleteFragment inside a fragment. I have end up with this (based on the accepted answer of this question):
public class SecondFragment extends Fragment
implements OnMapReadyCallback {
PlaceAutocompleteFragment placeAutoComplete;
.....
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.fragment_second, null, false);
// Create Map
if (savedInstanceState != null) {
mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
latlang.Lat = mLastKnownLocation.getLatitude();
latlang.Lang = mLastKnownLocation.getLongitude();
}
// Construct a FusedLocationProviderClient.
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
getLocationPermission();
getDeviceLocation();
placeAutoComplete = (PlaceAutocompleteFragment) getActivity().getFragmentManager().findFragmentById(R.id.place_autocomplete);
placeAutoComplete.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
Log.d("Maps", "Place selected: " + place.getName());
}
#Override
public void onError(Status status) {
Log.d("Maps", "An error occurred: " + status);
}
});
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//Search Place
return view;
}
and the corresponding layout is:
<LinearLayout 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"
tools:context=".SecondFragment"
android:orientation="vertical"
android:weightSum="1">
<fragment
android:id="#+id/place_autocomplete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
/>
<fragment
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
So, I got a searchbar which, on click opens up and keyboard flashes for a second and then crashes, before I start typing, and returns to "before click" view.
Whats going wrong here?
Related
My application shows blank google map on a fragment. I just call that fragment from MainActivity. I have searched/read on google, but none did help me at. I am not getting any error and I have used proper APIs Keys.
The following are my classes/mxls:
public class MainActivity extends AppCompatActivity {
private Button map_me;
private Button bCordinates;
public static Location mLastKnownLocation;
private FusedLocationProviderClient mFusedLocationProviderClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try {
if (true) {
Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful()) {
//Get the Location of the current device
mLastKnownLocation = task.getResult();
}
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
bCordinates = (Button)findViewById(R.id.bcordinates);
bCordinates.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Toast.makeText(getApplicationContext(),""+mLastKnownLocation.getLatitude()+" , " +
" "+mLastKnownLocation.getLongitude(),Toast.LENGTH_LONG).show();
}
});
map_me = (Button)findViewById(R.id.bmap);
map_me.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyMapFragment myMapFragment = new MyMapFragment();
fragmentTransaction.add(R.id.fragment_container, myMapFragment);
fragmentTransaction.commit();
}
});
}
}
public class MyMapFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap googleMap;
private MapView mapView;
private View view;
private FusedLocationProviderClient mFusedLocationProviderClient;
public MyMapFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.map_layout, container, false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapView = (MapView) getView().findViewById(R.id.map);
if(mapView!=null)
{
mapView.onCreate(null);
mapView.onResume();
mapView.getMapAsync(this);
}
}
#Override
public void onMapReady(final GoogleMap mGoogleMap) {
{
googleMap = mGoogleMap;
LatLng mLatLng = new LatLng(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude());
googleMap.addMarker(new MarkerOptions().position(mLatLng).title("You're here"));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mLatLng,15));
mapView.onResume();
}
}
}
map fragment layout
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MyMapFragment">
<com.google.android.gms.maps.MapView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
/>
</FrameLayout>
main activity layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.bdushimi.android2.MainActivity"
>
<Button
android:id="#+id/bmap"
android:layout_width="88dp"
android:layout_height="wrap_content"
android:text="MAP Me!"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginStart="8dp"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintHorizontal_bias="0.067"
tools:layout_editor_absoluteY="32dp" />
<Button
android:id="#+id/btext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEXT ME!"
tools:layout_editor_absoluteY="32dp"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintHorizontal_bias="0.464" />
<Button
android:id="#+id/bcordinates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cordinates"
android:layout_marginEnd="8dp"
tools:layout_editor_absoluteY="32dp"
android:layout_marginRight="28dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintHorizontal_bias="0.949"
app:layout_constraintLeft_toLeftOf="parent" />
<LinearLayout
android:id="#+id/fragment_container"
android:layout_width="333dp"
android:layout_height="370dp"
android:orientation="vertical"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="125dp"
app:layout_constraintHorizontal_bias="0.514"></LinearLayout>
</android.support.constraint.ConstraintLayout>
Please, help me to find out what I am doing wrong.
I think you should use MapFragment or SupportMapFragment in your map layout xml file according to your usability.
For now :
Replace :
with :
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/headerLayout"
tools:context="com.dxs.rnf.winwin.main.ui.fragments.DashboardMapFragment"
android:name="com.google.android.gms.maps.MapFragment"/>
Note : Also check your GOOGLE_API_KEY
I am adding SupportMapFragment programmatically to my main activity.
I am able to add it but i need a edit text and a button also to be displayed at the top of the map.
I have created a separate layout for my map fragment which i add programmatically inside my main activity. But i get a NPE saying "Unable to resume activity"
Please help me.
Here is my code . MainActivity.java
public class MainActivity extends FragmentActivity{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
GoogleMap googleMap;
String lat;
String provider;
protected double latitude,longitude;
protected boolean gps_enabled,network_enabled;
private ImageView mImage;
List<Marker> markerslist = new ArrayList<Marker>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get an instance of FragmentTransaction from your Activity
final FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//add a fragment
MapFragmentActivity mapFragment = new MapFragmentActivity();
fragmentTransaction.replace(R.id.appfragment, mapFragment);
fragmentTransaction.commit();
mImage = (ImageView)findViewById(R.id.eemaView);
mImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("inside on click eema");
EnterpriseFragment entFragment = new EnterpriseFragment();
FragmentTransaction fragmentTrans = fragmentManager.beginTransaction();
fragmentTrans.replace(R.id.appfragment, entFragment);
fragmentTrans.commit();
}
});
mImage = (ImageView)findViewById(R.id.deviationView);
mImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("inside on click deviation");
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//add a fragment
MapFragmentActivity mapFragment = new MapFragmentActivity();
fragmentTransaction.replace(R.id.appfragment, mapFragment);
fragmentTransaction.commit();
}
});
}
Here is my fragment class
public class MapFragmentActivity extends SupportMapFragment implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
GoogleMap googleMap;
String lat;
String provider;
protected double latitude,longitude;
protected boolean gps_enabled,network_enabled;
List<Marker> markerslist = new ArrayList<Marker>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.mapfragmentlayout, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
googleMap = this.getMap();
if (googleMap != null) {
//Your initialization code goes here
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
// Getting reference to btn_find of the layout activity_main
//Button btn_find = (Button) getActivity().findViewById(R.id.btn_find);
// Defining button click event listener for the find button
View.OnClickListener findClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Getting reference to EditText to get the user input location
EditText etLocation = (EditText) getActivity().findViewById(R.id.et_location);
// Getting user input location
String location = etLocation.getText().toString();
if(location!=null && !location.equals("")){
for(Marker m : markerslist) {
System.out.println("Marker size is "+markerslist.size());
System.out.println("Title is "+m.getSnippet());
System.out.println("Position is "+((LatLng)(m.getPosition())).latitude);
if(location.equals(m.getSnippet())) {
// do something with the marker
LatLng latLng = m.getPosition();
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
break; // stop the loop
}
}
}
}
};
// Setting button click event listener for the find button
//btn_find.setOnClickListener(findClickListener);
googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Getting view from the layout file info_window_layout
View v = getActivity().getLayoutInflater().inflate(R.layout.site_info_window, null);
List<String> qfList = JSONReader.readQuickFixData(getActivity());
ListView devLst = (ListView)v.findViewById(R.id.deviationList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),R.layout.simple_list_item_deviation,android.R.id.text1,qfList);
devLst.setAdapter(adapter);
return v;
}
});
}
}
This is my fragment layout xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_find"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Find"
android:layout_alignParentRight="true" />
<EditText
android:id="#+id/et_location"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="Enter Site ID"
android:layout_toLeftOf="#id/btn_find" />
</RelativeLayout>
<fragment 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:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
</LinearLayout>
My main layout xml
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="WEM App"
android:id="#+id/textView"
android:textStyle="bold"
android:textSize="16sp"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:layout_margin="3dp"
android:textColor="#color/abc_input_method_navigation_guard"
android:background="#android:color/holo_green_light"/>
<LinearLayout
android:id="#+id/appfragment"
android:layout_width="match_parent"
android:layout_weight="4"
android:layout_height="0dip"
android:orientation="horizontal">
</LinearLayout>
<HorizontalScrollView
android:id="#+id/hsview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginBottom="3dp"
android:background="#android:color/holo_green_light">
<LinearLayout android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/deviationView"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/sema_icon" />
<ImageView
android:id="#+id/eemaView"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/eema_icon" />
<ImageView
android:id="#+id/siteView"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/sema_icon" />
<ImageView
android:id="#+id/alertsView"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/eema_icon" />
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
Make sure u r using import android.support.v4.app.Fragment; and import android.support.v4.app.FragmentTransaction;
Make changes as below -
change public class MapFragmentActivity extends SupportMapFragment
to public class MapFragmentActivity extends Fragment keep rest as it is.
I am having a problem initializing my map. The map fragment is inflated into the FrameLayout of the main activity. I keep getting a null pointer exception within the setUpMapIfNeeded() method.
activity_main.xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
`
<include layout="#layout/toolbar"/>
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"></FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/drawer"
/>
</android.support.v4.widget.DrawerLayout>
map_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
tools:context=".MapFragment"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
</LinearLayout>
MainActivity.java
switch (menuItem.getItemId()) {
case R.id.shop:
MapFragment mapFragment = new MapFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frameLayout,mapFragment);
fragmentTransaction.commit();
break;
case R.id.list:
ListFragment listFragment = new ListFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction1 = getSupportFragmentManager().beginTransaction();
fragmentTransaction1.replace(R.id.frameLayout,listFragment);
fragmentTransaction1.commit();
break;
case R.id.points:
Toast.makeText(getApplicationContext(),"Global card selected",Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
MapFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.map_fragment,container,false);
//Check if GPS is enabled
locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(getContext(),"GPS enabled",Toast.LENGTH_SHORT).show();
}else {
showGPSDisabledAlertToUser();
}
setUpMapIfNeeded();
return view;
}
private void setUpMapIfNeeded() {
// 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.
//I get a null pointer exception at this point, no map it gotten
mMap = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
Take look at my repo for mapTab here. It shows how to initial the google map for in the fragment.
Sample code:
public class MapTabFragment extends Fragment {
private SupportMapFragment mMapView;
public static MapTabFragment newInstance(String param1, String param2) {
MapTabFragment fragment = new MapTabFragment();
return fragment;
}
MapView mapView;
GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_map, container, false);
// Gets the MapView from the XML layout and creates it
MapsInitializer.initialize(getActivity());
switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity())) {
case ConnectionResult.SUCCESS:
Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT).show();
mapView = (MapView) v.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(43.1, -87.9), 10);
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();
}
// Updates the location and zoom of the MapView
LatLng sydney = new LatLng(-33.867, 151.206);
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));
map.addMarker(new MarkerOptions()
.title("Sydney")
.snippet("The most populous city in Australia.")
.position(sydney));
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();
}
}
XML for this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.bojie.materialtest.fragments.UpcomingFragment"/>
</RelativeLayout>
I am trying to switch fragments after login, I have MainActivity that for the first time add the LogIn Fragment to his content, after the user login, I want to switch to a Google map Fragment.
How can I create a Google Map class extending Fragment and not FragmentActivity or Activity?
Can I add FragmentActivity to the layout of the MainActivity?
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public class YS_MapFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public YS_MapFragment() {
// Empty constructor required for fragment subclasses
}
MarkerOptions markerOptions;
LatLng latLng;
String locationString;
MapView mapView;
GoogleMap googleMap;
private String tag = "TAG";
private String msg = "= ";
// GPSTrackerN class
GPSTracker gps;
double latitude = 0.0, longitude = 0.0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mainLayout = inflater.inflate(R.layout.fragment_map, container,false);
locationString = getArguments().getString("location");
latitude = getArguments().getDouble("Lat");
longitude = getArguments().getDouble("Long");
// Gets the MapView from the XML layout and creates it
mapView = (MapView) mainLayout.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
googleMap = mapView.getMap();
googleMap.getUiSettings().setMyLocationButtonEnabled(false);
googleMap.setMyLocationEnabled(true);
// Needs to call MapsInitializer before doing any CameraUpdateFactory
// calls
MapsInitializer.initialize(this.getActivity());
if (locationString != null && !locationString.equals(""))
{
getLocation(latitude, longitude);
} else {
getCurrentLocation();
}
return mainLayout;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
<RelativeLayout
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.google.android.gms.maps.MapView
android:id="#+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="40dip" >
</com.google.android.gms.maps.MapView>
I tried instantiating the map directly in the xml but it got me a lot of problems when trying to do more complex things with the fragments and the navigation.
The solution that gave me the best results is something like this:
1- Have an empty FrameLayout in my view's xml:
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/color_separator" >
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:id="#+id/mapframe" />
</RelativeLayout>
2- Instantiate the SupportMapFragment in my Fragment class and add it to the FrameLayout:
if(mMapFragment==null) {
mMapFragment = SupportMapFragment.newInstance();
FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.mapframe, mMapFragment);
fragmentTransaction.commit();
}
3- Get the map asynchronically:
mMapFragment.getMapAsync(this);
(...)
#Override
public void onMapReady(GoogleMap googleMap) {
//THIS IS JUST EXAMPLE CODE; PUT WHATEVER STUFF YOU NEED HERE
mMap=googleMap;
googleMap.addMarker(new MarkerOptions().position(endLatLng).title(getString(R.string.title)));
mMapFragment.getView().setVisibility(View.GONE);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
new LatLng(endLatLng.latitude, endLatLng.longitude), 15);
googleMap.animateCamera(cameraUpdate);
}
This has worked perfectly for me.
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);
}