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.
Related
I started working on an old application i have that uses a map fragment on a navigation drawer. It used to work OK but now, with the new permisson thing, I get some errors. I have searched on SO and on the internet generally but I dont know what I am missing. My map Fragment is below
public class Fragment_maps extends android.support.v4.app.Fragment implements OnMapLongClickListener, OnMapClickListener, OnMapReadyCallback {
MapView mMapView;
GoogleMap googleMap;
#Override
public void onMapReady(GoogleMap googleMap) {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// inflate and return the layout
View v = inflater.inflate(R.layout.fragment_maps, container, false);
mMapView = (MapView) v.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
//activate menu button
setHasOptionsMenu(true);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
//get the map
mMapView.getMapAsync(this);
// Detect location
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(false);
//googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Turns traffic layer on
googleMap.setTrafficEnabled(true);
// Enables indoor maps
googleMap.setIndoorEnabled(true);
// Enables indoor maps
googleMap.setIndoorEnabled(true);
// Turns on 3D buildings
googleMap.setBuildingsEnabled(true);
// Show Zoom buttons
googleMap.getUiSettings().setZoomControlsEnabled(true);
// latitude and longitude
double latitude = 40.639350;
double longitude = 22.944607;
googleMap.setOnMapLongClickListener(this);
googleMap.setOnMapClickListener(this);
// create marker
MarkerOptions thessaloniki = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Thessaloniki");
// Changing marker icon
thessaloniki.icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(thessaloniki);
CameraPosition cameraPositionThess = new CameraPosition.Builder() .target(new LatLng(40.639350, 22.944607)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory .newCameraPosition(cameraPositionThess));
// Perform any camera updates here
return v;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_maps, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("onOptionsItemSelected","yes");
switch (item.getItemId()) {
case R.id.HYBRID:
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
return true;
case R.id.SATELLITE:
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
return true;
case R.id.TERRAIN:
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
return true;
case R.id.NORMAL:
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onMapClick(LatLng point) {
Toast.makeText(getActivity(),point.toString(),Toast.LENGTH_SHORT).show();
googleMap.animateCamera(CameraUpdateFactory.newLatLng(point));
}
#Override
public void onMapLongClick(LatLng point) {
if (SelectUserActivity.flagOwner){
googleMap.addMarker(new MarkerOptions()
.position(point)
.title(MainActivity.onomaxarth)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
Toast.makeText(getActivity(),"Hotel pinned at: "+point.toString(),Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(),point.toString(),Toast.LENGTH_SHORT).show();
}
}
#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 used googleMap = mMapView.getMap(); to get the map but i have change it with mMapView.getMapAsync(this); by implementing OnMapReadyCallback and it forced me to create the onMapReady method, which I dont know how it is different from the onCreateView method so i leave it empty.
Now i get an error on googleMap.setMyLocationEnabled(true); for permission and when i debug my app the googleMap object is null.
When I run it, on selecting the map fragment the app crashes and terminates the activity that holds the Fragments.
On the Manifest i have
android:minSdkVersion="17"
android:targetSdkVersion="23"
and my gradle dependencies are
compile 'com.android.support:support-v4:24.2.1'
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.google.android.gms:play-services:+'
What am i missing here? How can i use the permission in the fragment and why googleMap is empty?
Move this code from your onCreateView to your onMapReady:
// Detect location
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(false);
//googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Turns traffic layer on
googleMap.setTrafficEnabled(true);
// Enables indoor maps
googleMap.setIndoorEnabled(true);
// Enables indoor maps
googleMap.setIndoorEnabled(true);
// Turns on 3D buildings
googleMap.setBuildingsEnabled(true);
// Show Zoom buttons
googleMap.getUiSettings().setZoomControlsEnabled(true);
// latitude and longitude
double latitude = 40.639350;
double longitude = 22.944607;
googleMap.setOnMapLongClickListener(this);
googleMap.setOnMapClickListener(this);
// create marker
MarkerOptions thessaloniki = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Thessaloniki");
// Changing marker icon
thessaloniki.icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(thessaloniki);
CameraPosition cameraPositionThess = new CameraPosition.Builder() .target(new LatLng(40.639350, 22.944607)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory .newCameraPosition(cameraPositionThess));
The line mMapView.getMapAsync(this); prepares the map and onMapReady gets called when the map is ready to be used.
Also, if you have defined private GoogleMap googleMap;, you will want to add this to the beginning of your onMapReady method:
this.googleMap = googleMap;
Background
I'm implementing a detailed view over a custom location. The activity uses a ViewPager holding different fragments where one should be a SupportMapFragment. I'm testing on a Moto E using 5.0.2.
Problem
When a marker is pressed a map toolbar should slide in from the right. This toolbar does not show. All other controls such as compass and the "pan to my location" button shows. When I do it the normal way with an Activity that has a fragment coded in the XML the controls slide in as they should.
I've also tried adding the fragment to an activity the usual way, like this:
Fragment fragment = MapFragment.newInstance(title, lat, lng);
getSupportFragmentManager().beginTransaction().replace(R.id.testMapContainer, fragment).commit();
Implementation
public class MapFragment extends SupportMapFragment implements OnMapReadyCallback {
private final static String TITLE_KEY = "titleKey";
private final static String LATITUDE_KEY = "latitudeKey";
private final static String LONGITUDE_KEY = "longitudeKey";
private final static float ZOOM = 14;
private String title;
private double latitude;
private double longitude;
public MapFragment() {
super();
}
public static MapFragment newInstance(String title, double latitude, double longitude) {
MapFragment fragment = new MapFragment();
Bundle bundle = new Bundle();
bundle.putString(TITLE_KEY, title);
bundle.putDouble(LATITUDE_KEY, latitude);
bundle.putDouble(LONGITUDE_KEY, longitude);
fragment.setArguments(bundle);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = super.onCreateView(inflater, container, savedInstanceState);
Bundle bundle = getArguments();
title = bundle.getString(TITLE_KEY);
latitude = bundle.getDouble(LATITUDE_KEY);
longitude = bundle.getDouble(LONGITUDE_KEY);
getMapAsync(this);
return v;
}
#Override
public void onMapReady(GoogleMap map) {
LatLng targetLatLng = new LatLng(latitude, longitude);
map.getUiSettings().setMapToolbarEnabled(true);
map.setBuildingsEnabled(true);
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(targetLatLng, ZOOM));
map.addMarker(new MarkerOptions()
.title(title)
.position(targetLatLng));
}
}
Does anyone know what the problem may be? I'm sure it has something to do with my implementation of the SupportMapFragment.
EDIT:
The problem was in the XML of the Activity that is hosting the ViewPager. The MapToolbar is there but off screen. I can barely see it if i rotate the device. If I collapse the appbar before viewing the map tab the MapToolbar is fully visible.
How can I fix the XML so the MapToolbar is always visible (and enables the collapsing of the toolbar)?
I have done this before, it can popup the MapToolbar in the project, take look at UpcomingFragment here to set up the map.
For the whole project, you can get here to test on. Just go to third tab, and click the marker, it will pop up the MapToolbar behind the red button. In your project, you don't have the red button, so it doesn't matter.
Sample code for setting map:
public class UpcomingFragment extends Fragment {
private SupportMapFragment mMapView;
public static UpcomingFragment newInstance(String param1, String param2) {
UpcomingFragment fragment = new UpcomingFragment();
return fragment;
}
MapView mapView;
GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_upcoming, 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();
}
}
And related 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 want to pin a new mark on my map but method onMapLongClick didn work.
My code is below. I have my map inside a fragment.
public class Fragment_maps extends android.support.v4.app.Fragment
implements OnMapLongClickListener, OnMapClickListener{
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflate and return the layout
View v = inflater.inflate(R.layout.fragment_maps, container,
false);
mMapView = (MapView) v.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
//activate menu button
setHasOptionsMenu(true);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
//get the map
googleMap = mMapView.getMap();
// Detect location
googleMap.setMyLocationEnabled(true);
//googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Turns traffic layer on
googleMap.setTrafficEnabled(true);
// Enables indoor maps
googleMap.setIndoorEnabled(true);
// Enables indoor maps
googleMap.setIndoorEnabled(true);
// Turns on 3D buildings
googleMap.setBuildingsEnabled(true);
// Show Zoom buttons
googleMap.getUiSettings().setZoomControlsEnabled(true);
// latitude and longitude
double latitude = 40.639350;
double longitude = 22.944607;
// create marker
MarkerOptions thessaloniki = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Thessaloniki");
//----------------
MarkerOptions LeykosPyrgos = new MarkerOptions().position(new LatLng(40.626401, 22.948352)).title("Leykos Pyrgos");
// Changing marker icon
thessaloniki.icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
//----------------
LeykosPyrgos.icon(BitmapDescriptorFactory .fromResource(R.drawable.whitetower));
// adding marker
googleMap.addMarker(thessaloniki);
CameraPosition cameraPositionThess = new CameraPosition.Builder() .target(new LatLng(40.639350, 22.944607)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory .newCameraPosition(cameraPositionThess));
//----------------
googleMap.addMarker(LeykosPyrgos);
CameraPosition cameraPositionLeykosPyrgos = new CameraPosition.Builder() .target(new LatLng(40.626401, 22.948352)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory .newCameraPosition(cameraPositionLeykosPyrgos));
// Perform any camera updates here
return v;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_maps, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d("onOptionsItemSelected","yes");
switch (item.getItemId()) {
case R.id.HYBRID:
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);;
return true;
case R.id.SATELLITE:
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
return true;
case R.id.TERRAIN:
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
return true;
case R.id.NORMAL:
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onMapClick(LatLng point) {
Toast.makeText(getActivity(),point.toString(),Toast.LENGTH_SHORT).show();
googleMap.animateCamera(CameraUpdateFactory.newLatLng(point));
}
#Override
public void onMapLongClick(LatLng point) {
googleMap.addMarker(new MarkerOptions()
.position(point)
.title("You are here")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}
#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();
}
}
As you can see I have both onMapClick and onMapLongClick methods but when I click on map nothing happens. I also have implement OnMapLongClickListener and OnMapClickListener. What am I doing wrong?
Thanks in advance.
Your class implements the listener but you don't set it:
googleMap.setOnMapLongClickListener(this);
same with the normal click listener:
googleMap.setOnMapClickListener(this);
I am building an android application where user is getting latLng by long touching in Google map.
Here is the code:
public class MainActivitytut extends FragmentActivity{
GoogleMap googleMap;
MarkerOptions markerOptions;
LatLng latLng;
private TextView myAddress;
String lat;
TextView txtmapinfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maintut);
//onBackPressed();
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
// Getting a reference to the map
googleMap = supportMapFragment.getMap();
// Setting a click event handler for the map
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng arg0) {
// Getting the Latitude and Longitude of the touched location
latLng = arg0;
lat = latLng.toString();
// Toast.makeText(getApplicationContext(), lat,
// Toast.LENGTH_LONG).show();
// getMyLocationAddress();
// Clears the previously touched position
googleMap.clear();
// Animating to the touched position
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Creating a marker
markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
// Adding Marker on the touched location with address
new ReverseGeocodingTask(getBaseContext()).execute(latLng);
}
});
}
protected void putExtra(String string, CharSequence text) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
// present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I had used lat = map.getCameraPosition().target; and when I toast the value of lat, it is toasting 0.0
What I need is that when on swiping the map the latlng change and toast.
Wait until the map has loaded and then call getCameraPosition:
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
LatLng pos = mMap.getCameraPosition().target;
Log.e("", "Pos: " + pos.toString());
mMap.addMarker(new MarkerOptions().position(pos));
}
});
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.