Title can be a bit complicated but the problem is literally as described. I'm trying to use google map fragment within a fragment stack. When the application starts the user will see a button and when the user pushes the button, current view will be replaced with map fragment. Currently, I'm able to replace the fragments but when the map fragment is shown, the view still has the button of previous fragment.Also I'm trying to replace fragments in one of the tabs of my app. Here is my code;
Map Fragment;
public class MapFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_maps, container, false);
mMapView = (MapView) rootView.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();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
try {
googleMap.setMyLocationEnabled(true);
} catch (SecurityException e) {
e.printStackTrace();
}
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(-34, 151);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return rootView;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
Home Fragment;
public class HomeFragment extends RootFragment {
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Obtain the shared Tracker instance.
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.home_tab, container, false);
Button go = (Button)v.findViewById(R.id.btn_go);
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent intent = new Intent(getActivity(), MapFragment.class);
//startActivity(intent);
enterNextFragment();
}
});
return v;
}
#Override
public void onResume() {
super.onResume();
}
private void enterNextFragment() {
// Pushing MapView Fragment
Fragment fragment = Fragment.instantiate(this.getContext(), MapFragment.class.getName());
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_mainLayout, fragment);
ft.commit();
}
}
Map Layout;
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Home Fragment;
<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=".HomeFragment"
android:background="#android:color/white"
android:id="#+id/fragment_mainLayout">
<!-- TODO: Update blank fragment layout -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/btn_go"
android:layout_width="fill_parent"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_height="wrap_content"
android:layout_marginTop="170dp"
android:text="GO"/>
</FrameLayout>
Often you will want one Fragment to communicate with another, for
example to change the content based on a user event. All
Fragment-to-Fragment communication is done through the associated
Activity. Two Fragments should never communicate directly.
Your fragments shouldn't communicate directly according to the documentation.
If you've managed to communicate with your fragments considering the documentation. Then you can use this simple method to be able to change and reuse any fragment.
In your host activity :
private void changeFragment(Fragment frag, boolean saveInBackstack) {
String backStateName = ((Object) frag).getClass().getName();
try {
FragmentManager manager = getSupportFragmentManager();
if (manager.findFragmentByTag(backStateName) == null) {
//fragment not in back stack, create it.
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container, frag, backStateName);
if (saveInBackstack) {
Log.d(TAG, "Change Fragment: addToBackTack " + backStateName);
transaction.addToBackStack(backStateName);
} else {
Log.d(TAG, "Change Fragment: NO addToBackTack");
}
transaction.commit();
} else {
manager.popBackStack();
}
} catch (IllegalStateException exception) {
Log.w(TAG, "Unable to commit fragment, could be activity as been killed in
}
}
just add android:background="#android:color/white" on the main view of the map_layout xml file
Here is the solution;
Home Fragment;
public class HomeFragment extends RootFragment {
private LocationManager locationManager;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Obtain the shared Tracker instance.
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.home_tab, container, false);
Button go = (Button) v.findViewById(R.id.btn_go);
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), MapFragment.class);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
//Toast.makeText(getContext(), "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
}
});
return v;
}
#Override
public void onResume() {
super.onResume();
}
}
MapFragment (it is now fragmentActivity not fragment);
public class MapFragment extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener {
MapView mMapView;
private GoogleMap googleMap;
// private GoogleMap map;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private Marker marker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mMapView = (MapView) findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(this.getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = null;
try {
googleMap.setMyLocationEnabled(true);
location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
} catch (SecurityException e) {
e.printStackTrace();
}
if (location != null) {
googleMap.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
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
}
Related
So, I basically put a GoogleMaps API inside a fragment in my app, and I want to give it a specific default search like we do with Intent, but in this case im using fragment instead of an intent.`public class LocalGymsFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_local_gyms, container, false);
mMapView = (MapView) rootView.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();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(-34, 151);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return rootView;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}`
I suggest that you try implementing the GoogleMaps API on a constraint layout or new GoogleMaps Activity. This is because Fragments aren't just a cup of tea. It is tough implementing this on fragments.
This question already has answers here:
Location is empty at the start
(5 answers)
Closed 3 years ago.
This topic is populated in SO, but due to my limited knowledge in java, I am unable to get my location.
If I manually put latitude and longitude, my code is working as expected. I use this to put the latitude and longitude hardcoded:
class latlang {
public static double Lat=28.28;
public static double Lang=84.0;
}
which is used in other fragments, as, but not only in map:
MapFragment.java
public class MapFragment extends Fragment {
private MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
mMapView = rootView.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();
}
mMapView.getMapAsync(mMap -> {
googleMap = mMap;
LatLng sydney = new LatLng(latlang.Lat, latlang.Lang);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
});
return rootView;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
Kindly help. I am totally confused with FusedLocationProviderClient
main_activity.java
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient mFusedLocationClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
//new SecondFragment();
//TabLayout tabs = findViewById(R.id.tabs);
//tabs.setupWithViewPager(viewPager);
FloatingActionButton fab = findViewById(R.id.fab);
FontDrawable drawable = new FontDrawable(this, R.string.fa_plus_solid, true, false);
drawable.setTextColor(ContextCompat.getColor(this, android.R.color.white));
fab.setImageDrawable(drawable);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
//Check permission
if (ContextCompat.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
}
}
First you need to initialize the fusedLocationClient like this :
In Fragment:
fusedLocationClient = LocationServices.getFusedLocationProviderClient(getContext());
In Activity:
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
then to retrieve last known location :
fusedLocationClient.getLastLocation()
.addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations, this can be null.
if (location != null) {
// Logic to handle location object
double latitude= location.getLatitude();
double longitude= location.getLongitude();
} else {
//handle null location
}
}
});
Hope this helps!
I would like guidance on how to properly implement a google map in a view pager. I have done so in an activity and have no problems producing a map in a activity but when trying to do the same with a view pager I am not having much success.
I have found this question that asks something similar but trying it out leads me to an error that I can't resolve: How to put Google Maps V2 on a Fragment using ViewPager
I updated get map to get map Async following this guide: Replace getMap with getMapAsync.
However I am still no close to getting a google map to display in my view pager. I am uncertain as where else to go to for tutorials. I have found plenty of tutorials on how to get a map to show in an activity but none on how to get it to show with a view pager. Unable to find any guides on the subject relating to view pagers inside of maps.
I am currently unable to display a map in my fragment google map resources fragment.
If there are any resources or tutorials I can be provided that are up to date feel free to share them, I am currently unable to find a solution on my own.
Any ideas would be appreciated.
public Class MainActivity extends AppCompatActivity implements OnMapReadyCallback{
private GoogleMap googleMap;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
//The adapter adds the fragments created to the view so it can be seen by the user
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new SucessfullFosterYouthFragment(), "Sucessfull Foster Youth");
adapter.addFragment(new ContactusFragment(), "Contact US");
adapter.addFragment(new GoogleMapResourcesFragment(), "resources");
viewPager.setAdapter(adapter);
}
#Override
public void onMapReady(GoogleMap googleMap) {
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.googlemap);
mapFragment.getMapAsync(this);
}
public void setUpMap() {
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
}
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public class GoogleMapResourcesFragment extends Fragment{
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_googlemapresources, container,
false);
mMapView = (MapView) v.findViewById(R.id.googlemap);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Perform any camera updates here
return v;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
You should use MapView here as well instead of MapFragment:
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.googlemap);
mapFragment.getMapAsync(this);
Try this example below:
public class SomeFragment extends Fragment {
MapView mapView;
GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.some_layout, container, false);
// Gets the MapView from the XML layout and creates it
mapView = (MapView) v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
// Updates the location and zoom of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
map.animateCamera(cameraUpdate);
return v;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
Layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.google.android.gms.maps.MapView android:id="#+id/mapview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
I'm having an issue with my Android app. I'm using navigation drawer with onCreateView() inside of a PlaceholderFragment like this:
// Google Map
private GoogleMap map;
private final LatLng LOCATION_DEPAUW = new LatLng(39.640343, -86.860687);
public static class PlaceholderFragment extends Fragment {
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#SuppressWarnings("unused")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = null;
...
else if(mTitle.equals("Map")){
Log.d("Map", "Worked");
rootView = inflater.inflate(R.layout.google_map, container, false);
try {
if (map == null) {
SupportMapFragment fm = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
map = fm.getMap();
}
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LOCATION_DEPAUW, 15);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Enabling MyLocation Layer of Google Map
map.setMyLocationEnabled(true);
map.getUiSettings().setZoomGesturesEnabled(true);
map.getUiSettings().setCompassEnabled(true);
map.getUiSettings().setRotateGesturesEnabled(true);
map.animateCamera(update);
/*
* for different colors:
* googlemap.addMarker(new MarkerOptions().position(new LatLng( 65.07213,-2.109375)).title("This is my title").snippet("and snippet").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
*
* .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE) is the key. change the HUE_ORANGE to anything that is available
*
*/
} catch (Exception e) {
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
}
}
I have already imported everything correctly and the map initializes correctly on the first view. The problem is when I navigate to another fragment and then go back to this map fragment, my app crashes. I've tried to use an eclipse emulator but couldnt get it configured correctly. Does anyone know a way to handle the life cycle of a map inside a placeholderfragment? Thanks!
So after a lot of research, I found out someone manage to handle this well.
Check out this github repository:
https://gist.github.com/joshdholtz/4522551
MapView mapView;
GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.some_layout, container, false);
// Gets the MapView from the XML layout and creates it
mapView = (MapView) v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
// Updates the location and zoom of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
map.animateCamera(cameraUpdate);
return v;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
initially though, I had issues cause I had multiple fragments to switch between, so i did this in mine:
public void onResume() {
try{
super.onResume();
mapView.onResume();
}catch(NullPointerException e){
Log.d("onResume", "NullPointerException: " + e);
}
}
#Override
public void onDestroy() {
try{
super.onDestroy();
mapView.onDestroy();
}catch(NullPointerException e){
Log.d("onDestroy", "NullPointerException: " + e);
}
}
#Override
public void onLowMemory() {
try{
super.onLowMemory();
mapView.onLowMemory();
}catch(NullPointerException e){
Log.d("onLowMemory", "NullPointerException: " + e);
}
}
I am trying to display a simple map in my Android application, using the MapView class.
I use the following onCreate method in my activity :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
MapsInitializer.initialize(this);
} catch (GooglePlayServicesNotAvailableException e) {
Log.e("Address Map", "Could not initialize google play", e);
}
MapView mapView = new MapView(this);
CameraUpdate camPos = CameraUpdateFactory.newLatLng(new LatLng(11.562276,104.920292));
mapView.getMap().moveCamera(camPos);
setContentView(mapView);
}
I have a NullPointerException, because the method mapView.getMap() returns null.
Don't understand why, Google play services are apparently present and initialized.
Could not get MapView to work, I finally ended using the class SupportMapFragment.
For those that it may help, here is the complete code of my activity :
public class AddressMap extends android.support.v4.app.FragmentActivity {
private final static int FRAGMENT_ID = 0x101;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
SupportMapFragment fragment = SupportMapFragment.newInstance();
layout.setId(0x101);
{
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(FRAGMENT_ID, fragment);
fragmentTransaction.commit();
}
setContentView(layout);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(FRAGMENT_ID)).getMap();
if (mMap != null) {
mMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(new LatLng(11.562276, 104.920292), 10));
}
}
}
}
Also, mapView.onCreate() must be called.
You are trying to access Google Maps Android v1 Api which is now deprecated, please use Google Map Android Api v2
I used it like this and it worked, this is with the new api:
compile 'com.google.android.gms:play-services-maps:10.2.6'
public class MapViewFragment extends Fragment{
public static final String TAG = MapViewFragment.class.getSimpleName();
MapView mapView;
GoogleMap map;
static MapViewFragment instance;
public static MapViewFragment newInstance(){
if(instance == null){
instance = new MapViewFragment();
return instance;
}else{
return instance;
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.i(TAG, "onCreateView: " );
View view = inflater.inflate(R.layout.map_view_fragment, container, false);
mapView = (MapView) view.findViewById(R.id.mvMap);
if(mapView != null){
mapView.onCreate(null); //Don't forget to call onCreate after get the mapView!
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
//Do what you want with the map!!
}
});
MapsInitializer.initialize(this.getActivity());
}else{
Log.i(TAG, "onCreateView: mapView is null");
}
return view;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
And here is my layout:
<?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">
<com.google.android.gms.maps.MapView
android:id="#+id/mvMap"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.google.android.gms.maps.MapView>
</LinearLayout>