Subclassing of SupportMapFragment in ViewPager wont show map toolbar - android

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>

Related

Marker's not showing: Google Map Android

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

Map does not detect touches/swipes in android

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

Android google map in a Fragment

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.

Google map in android,display in small size mapview

I want to display location in map view & map size should be 200X200.
I tried loading map in mapview but its not displaying properly after tapping on direction pointer 2 to 3 times its displaying correct map but not moving.
But when I use complete size of screen for displaying map without changing any code it's loading correctly.How can i display same iin small view?
map code-
static GoogleMap map;
private MapView mapView;
MapsInitializer.initialize(getApplicationContext());
switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()) )
{
case ConnectionResult.SUCCESS:
//Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT).show();
mapView = (MapView)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(location, 10);
map.animateCamera(cameraUpdate);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
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(getApplicationContext(), GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()), Toast.LENGTH_SHORT).show();
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(location).zoom(10).bearing(0) // Sets the orientation of the camera to east
.tilt(70) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.setBuildingsEnabled(true);
map.setMyLocationEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
Solution -
Done using fragment -
map_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:id="#+id/mapfragment"
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_alignParentTop="true"
android:layout_gravity="center_horizontal"
class="com.google.android.gms.maps.SupportMapFragment" />
<TextView
android:id="#+id/reg_office_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/mapfragment"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:gravity="center"
android:text="#string/tata_auto"
android:textColor="#color/tatablue"
android:textSize="18sp" />
</RelativeLayout>
java code -
public class MapFragment extends Fragment {
private View view;
public GoogleMap map;
private Location location;
private LatLng mAddress1;
public static boolean inMap=false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// TODO Auto-generated method stub
view= inflater.inflate(R.layout.contact_map, container, false);
setMapView();
return view;
}
private void setMapView(){
CurrentLocation mCurrentLoc=new CurrentLocation(getActivity());
location = CurrentLocation.locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
mCurrentLoc.onLocationChanged(location);
} else {
mCurrentLoc.onLocationChanged(location);
}
//class="com.google.android.gms.maps.SupportMapFragment"
map = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.mapfragment)).getMap();
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(mAddress1).zoom(8).bearing(0) // Sets the orientation of the camera to east
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.setBuildingsEnabled(true);
map.setMyLocationEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
mAddress1 is latitude and longitude of your location.
I tested the code below and there is no problems with the map to the size 200dp x 200dp
Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical">
<fragment
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="200dp"
android:layout_height="200dp" />
</LinearLayout>
Fragment:
public class LocationFragment extends Fragment
{
GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_location, container, false);
googleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
MapsInitializer.initialize(getActivity().getApplicationContext());
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(38.7222524, -9.139336599999979))
.title("MyLocation")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_mobileedge_navpoint)));
// Move the camera instantly with a zoom of 15.
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom( new LatLng( 38.7222524, -9.139336599999979), 15));
// Zoom in, animating the camera.
googleMap.animateCamera(CameraUpdateFactory.zoomTo(12), 1000, null);
return v;
}
}
Update - 11 August 2020
MapView.getMap() has been replaced with MapView.getMapAsync()
I see that you are using MapView instead of MapFragment. In Google Maps V2, the old MapView class com.google.android.maps.MapView is obsolete. So make sure you use the correct MapView both in your Java code and XML layout which should be
import com.google.android.gms.maps.MapView;
and
<com.google.android.gms.maps.MapView
android:id="#+id/map_view"
android:layout_width="your_width"
android:layout_height="your_height" />
Also make sure you have made all necessary changes in AndroidManifest.xml, which includes defining the API_KEY for Maps V2 as described here.
Apart from this, there is a major thing you have to do if you are using MapView in place of a MapFragment, you have to call the MapView's overridden functions explicitly inside the corresponding overrides of residing Activity just like,
public class YourMapActivity extends Activity {
MapView mMapView;
GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Your OnCreate with Map Initialization */
mMapView = (MapView) findViewById(R.id.map_view);
mMapView.onCreate(Bundle.EMPTY);
mMap = mMapView.getMap();
MapsInitializer.initialize(this);
}
#Override
protected void onResume() {
mMapView.onResume();
super.onResume();
}
#Override
protected void onPause() {
mMapView.onPause();
super.onPause();
}
#Override
protected void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
mMapView.onLowMemory();
super.onLowMemory();
}
}
This should be enough for loading a custom sized MapView in your Acitivity. You may also use the following functions to make it suit your requirement.
mMapView.setClickable(false);
mMap.getUiSettings().setMyLocationButtonnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
mMap.getUiSettings().setCompassEnabled(false);
mMap.getUiSettings().setZoomGesturesEnabled(false);
mMap.getUiSettings().setScrollGesturesEnabled(false);
mMap.setMyLocationEnabled(true);

Android Google Maps v2: on click listener not responding

I'm trying to put a marker when the user clicks on map. I'm using a SupportMapFragment inside an ActionBarActivity. But the map doesn't respond, furthermore, a map.setMapType() operation isn't working.
Here's my code:
private GoogleMap map;
private Marker marker;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ActionBarActivity activity = (ActionBarActivity) getActivity();
activity.getSupportActionBar().setTitle(R.string.select_location);
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.map, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d("Map","On view created");
map = getMap();
map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
map.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
Log.d("Map","Map clicked");
marker.remove();
drawMarker(point);
}
});
...
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
//PLACE THE INITIAL MARKER
drawMarker(new LatLng(location.getLatitude(),location.getLongitude()));
}
}
Logcat is showing the "on view created" message and the map shows the current location with a marker, so the last part of the code is being executed. But the onMapClickListener is overrided or something because it doesn't work, and the map isn't a satellite.
Can anybody help me?
If you have extended SupportMapFragment you can simply do this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ActionBarActivity activity = (ActionBarActivity) getActivity();
activity.getSupportActionBar().setTitle(R.string.select_location);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
map = getMap();
map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
map.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
Log.d("Map","Map clicked");
marker.remove();
drawMarker(point);
}
});
Note that getMap() is called in onActivityCreated and inflater.inflate(R.layout.map, container, false) is not necessary if you don´t use a custom layout.
You don´t even need a map.xml layout!
You are extending SupportMapFragment but you are inflating another MapView (not the one tied to SupportMapFragment by default), that´s why you are not viewing the changes in your map. Because you were acting on the default View got from getMap() but you are viewing another. See the docs about getMap():
public final GoogleMap getMap ()
Gets the underlying GoogleMap that is tied to the view wrapped by this
fragment.
Hope it helps ;)
Well you are placing a listener for your map, but you need to make a listener for your markers.
map.setOnMarkerClickListener(this);
...
#Override
public boolean onMarkerClick(Marker arg0) {
Log.i(TAG,"marker arg0 = "+arg0);
return false;
}
or for the InfoWindows on top of the markers:
map.setOnInfoWindowClickListener(this);
Also, your initialitizing of map making it show satelite is almost correct:
map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
change it to:
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
Instead of doing map = getMap(), a few lines later I had this code:
SupportMapFragment fm = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
map = fm.getMap();
So I've just put the code above that line and it's done.
Instead of doing map = getMap() you can try this.
if (map == null) {
// Try to obtain the map from the SupportMapFragment.
this.map = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.mapView))
.getMap();
setUpMap(lat, longi, R.drawable.marker2, title);
}
private void setUpMap(double lat, double lng, int drawableResource, String title) {
if(map != null) {
marker = map.addMarker(new MarkerOptions().position(new LatLng(lat, lng))
.title(title)
.icon(BitmapDescriptorFactory.fromResource(drawableResource)));
geocoder = new Geocoder(this, Locale.getDefault());
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 15));
map.animateCamera(CameraUpdateFactory.zoomTo(13), 2500, null);
}
}

Categories

Resources