Replace getMap with getMapAsync with custom support fragment - android

trying to update my google dependencies from 9.0.0 to 15.0.0. But I have to update
getMap();
with
getMapAsync();
Because getMap(); is deprecated in newest versions of google libraries.
The issue is I am using custom fragment to load the view. I am doing it this way because I have 3 different map types that can be loaded into the map view based on user selection. But it's not letting me do getMapAsync without error.
Here is my code:
private void setUpMapIfNeeded() {
if (mMapFragment == null) {
mMapFragment = new CustomSupportMapFragment();
mMapFragment.setOnMapCreatedListener(new CustomSupportMapFragment.MapViewCreatedListener() {
#Override
public void onMapCreated() {
boolean needUpdate = mMap == null;
mMap = mMapFragment.getMapAsync();
if (mMap != null)
setUpMap(needUpdate);
}
});
}
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.map, mMapFragment);
ft.commit();
}
But I am getting error:
getMapAsync (OnMapReadyCallback) in SupportMapFragment cannot be applied to ()
So I tried adding this, getContext() in like this:
getMapAsync(this);
getMapAsync(getContext));
but both come back with errors about it cannot be applied.
Any ideas? Sorry for my understanding of java is new and I am learning. I tried searching StackOverflow and google already for this issue but can only find resolutions when using regular supportmapfragment and not custom supportmapfragment.
Here is my setUpMap method if it helps for you to understand:
private void setUpMap(boolean needUpdate) {
boolean location_permission_granted = (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);
if (!location_permission_granted) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 200);
} else {
mMap.setMyLocationEnabled(true);
}
mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
if (LOAD_PARTICULAR_MAP == 1) {
if (cameraPosition.zoom > AppConstants.MAX_ZOOM) {
CameraUpdate upd = CameraUpdateFactory.newLatLngZoom(cameraPosition.target, AppConstants.MAX_ZOOM);
mMap.moveCamera(upd);
}
float maxZoom = 4f;
if (cameraPosition.zoom > maxZoom) {
mMap.animateCamera(CameraUpdateFactory.zoomTo(maxZoom));
return;
}
float minZoom = 0f;
if (cameraPosition.zoom < minZoom) {
mMap.animateCamera(CameraUpdateFactory.zoomTo(minZoom));
return;
}
}
}
});
mMap.setOnMapLongClickListener(this);
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMapClickListener(this);
mMap.setOnMarkerDragListener(this);
mMap.setOnMarkerClickListener(this);
// mBtnMapType.setVisibility(View.VISIBLE);
mMap.getUiSettings().setScrollGesturesEnabled(true);
//mBtnLegend.setVisibility(View.VISIBLE);
//updateLegendButton();
updateMapType(mSettings.getMapType(GoogleMap.MAP_TYPE_TERRAIN));
/*mTileProvider = new TranslucentUrlTileProvider(AppConstants.SERVER_URL, AppConstants.SERVER_URL_FREE);
// mTileProvider.setPro(!mIsPro.showPurchaseDialog());
//mTileProvider.setOpacity(mOpacity);
mTileOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider(mTileProvider));*/
if (needUpdate)
if (LOAD_PARTICULAR_MAP != 4) {
gotoMyLocation();
}
// mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
// #Override
// public boolean onMarkerClick(Marker marker) {
// if (marker != null) {
// openGoogleMap(marker);
// return true;
// }
// return false;
// }
// });
switch (LOAD_PARTICULAR_MAP) {
case 1:
auroraOverMap();
mMap.animateCamera(CameraUpdateFactory.zoomTo(0f));
break;
case 2:
lightPollutionMap();
break;
case 3:
loadCloudMap();
break;
case 4:
highestValueView();
// mMap.animateCamera( CameraUpdateFactory.zoomTo( 12f ) );
break;
}
}

You can't get GoogleMap object by calling
mMap = mMapFragment.getMapAsync();
you should use code like that:
mMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
});
where mMap is global variable:
public class MainActivity extends AppCompatActivity {
private GoogleMap mMap;
...
and after you got mMap you can use it for setup your map:
mMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (mMap != null)
setUpMap(needUpdate);
}
});
Also, take a look at Official Tutorial.

Related

Google maps v2 not initializing in fragment

I want to show my current location using Google maps v2 from a fragment however the Google maps is not initializing on start up. When i run the application, it is nor crashing but the map is not showing my current location neither is it displaying anything. I have used this code on my activity and it is fully functional.
Below is my java code:
public class MapFragment extends Fragment implements LocationListener,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,OnMapReadyCallback {
SupportMapFragment mSupportMapFragment;
MapView mMapView;
Location mLastLocation;
Marker mCurrLocationMarker;
private MarkerOptions markerOptions;
protected GoogleApiClient mGoogleApiClient;
private LatLng latLng;
public GoogleMap mMap;
private Marker marker;
LocationRequest mLocationRequest;
private GoogleMap googleMap;
private TextView lastTrip, lastDeliveryText, lastDelivery, lastAmountText, lastAmount, kes,
todayTotal, totalDeliveryText, totalDelivery, totalAmount, totalAmountText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
buildGoogleApiClient();
// inflat and return the layout
View v = inflater.inflate(R.layout.map_fragment, container,
false);
mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapwhere);
if (mSupportMapFragment == null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
mSupportMapFragment = SupportMapFragment.newInstance();
fragmentTransaction.replace(R.id.mapwhere, mSupportMapFragment).commit();
}
if (mSupportMapFragment != null) {
mSupportMapFragment.getMapAsync(this);
}
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Log.d("one","one");
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//mMap.getUiSettings().setZoomControlsEnabled(true);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
Log.d("two","two");
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
Log.d("three","three");
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
Log.d("four","four");
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
Log.d("five","five");
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//mMap.getUiSettings().setZoomControlsEnabled(true);
final Double lat = location.getLatitude();
final Double lng = location.getLongitude();
Log.d("LATLANGz", lat + "|" + lng);
latLng = new LatLng(lat, lng);
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Positionn");
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(false);
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.user_location));
marker = mMap.addMarker(markerOptions);
//move map camera_main
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
#Override
public void onResume() {
super.onResume();
Log.d("hey2","hey2");
// mMapView.onResume();
mSupportMapFragment.onResume();
}
#Override
public void onPause() {
super.onPause();
Log.d("hey1","hey1");
// mMapView.onPause();
mSupportMapFragment.onPause();
}
/* #Override
public void onDestroy() {
super.onDestroy();
// mMapView.onDestroy();
mSupportMapFragment.onDestroy();
}*/
#Override
public void onLowMemory() {
super.onLowMemory();
// mMapView.onLowMemory();
mSupportMapFragment.onLowMemory();
}
#Override
public void onDetach() {
Log.d("detach", "detach");
super.onDetach();
mSupportMapFragment.onDetach();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d("six","six");
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (mGoogleApiClient.isConnected()){
Log.d("seven","six");
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
first of all Chaeck permission in manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
then check method for current location
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
marker = map.addMarker(new MarkerOptions().position(loc));
if(map != null){
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
}
};
then use
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
and be patience map take laoding time depend on you network speed
comment if any query
First check your permissions and your google api key in your manifest
Your xml layout must be something like this without any thing else:
. <fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.isg_biz.isg_tracking.MainActivity" />
You have to implement OnMapReadyCallback, then
your code should be something like this in onCreate() :
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Do not to copy and past the same xml code literally you have to change (tools : .....) to same that exist in your xml
for documentation, java code & more Please read :
https://developers.google.com/maps/documentation/android-api/map-with-marker

Adding marker on current location

I'm a beginner in android programming and I'm currently working on google maps. What I want to do is to get the current location of the user and then put a marker on that location.
I'm practicing on this but I really can't get it to work. This only shows the current location of the user. But what I want to do is to display a marker on it as well. Any suggestions how to do it?
public class MapsActivity extends AppCompatActivity implements GoogleMap.OnMyLocationButtonClickListener,
OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback {
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private boolean mPermissionDenied = false;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMyLocationButtonClickListener(this);
enableMyLocation();
}
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
android.Manifest.permission.ACCESS_FINE_LOCATION, true);
} else if (mMap != null) {
mMap.setMyLocationEnabled(true);
}
}
#Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "Showing current location", Toast.LENGTH_SHORT).show();
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
return;
}
if (PermissionUtils.isPermissionGranted(permissions, grantResults,
Manifest.permission.ACCESS_FINE_LOCATION)) {
enableMyLocation();
} else {
mPermissionDenied = true;
}
}
Get you last location-
LatLng location = getLatLngFromLastLocation();
Then use this code block to put marker on map:
MarkerOptions markerOptions = new MarkerOptions()
.position(location)
.icon(getMarkerIcon(mProfileTheme.getColorCodeLight()));
public BitmapDescriptor getMarkerIcon(int color) {
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
return BitmapDescriptorFactory.defaultMarker(hsv[0]);
}

Google maps loading slow inside fragment

I have main activity with fragments and one of the fragments is Map Fragment. Now, when i tap there, every time it opens slow. I am using singleton instance of fragment, but it still doesnt work as expected. Here is a good of that class:
public MapsFragment() {
gson = new Gson();
}
public static MapsFragment getInstance() {
if (mInstance == null)
mInstance = new MapsFragment();
return mInstance;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable final Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_maps, container, false);
mOnSavedinstance = savedInstanceState;
mMapView = (MapView) v.findViewById(R.id.map);
mMapWrapperLayout = (MapWrapperLayout) v.findViewById(R.id.map_relative_layout);
mMapView.getMapAsync(MapsFragment.this);
mMapView.onCreate(savedInstanceState);
mMapView.requestFocus();
MapsInitializer.initialize(getActivity());
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
// MapWrapperLayout initialization
// 39 - default marker height
// 20 - offset between the default InfoWindow bottom edge and it's content bottom edge
mMapWrapperLayout.init(mGoogleMap, Constants.MARKER_HEIGHT);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mGoogleMap.setMyLocationEnabled(false);
}
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
setUpMap();
}
private void setUpMap() {
new Thread(new Runnable() {
#Override
public void run() {
final ArrayList<MarkerOptions> markerOptionses = new ArrayList<MarkerOptions>();
int counter = 0;
for (final Places places : Model.getInstance().getPlaces()) {
LatLng location = new LatLng(Double.parseDouble(places.getLat()), Double.parseDouble(places.getLon()));
final MarkerOptions options = new MarkerOptions();
options.snippet(gson.toJson(places));
options.position(location);
options.title(String.valueOf(counter));
markerOptionses.add(options);
counter++;
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
for (MarkerOptions markerOptionse : markerOptionses) {
mGoogleMap.addMarker(markerOptionse).setIcon(BitmapDescriptorFactory.fromResource(Model.getInstance().getPlaces()
.get(Integer.parseInt(markerOptionse.getTitle())).getMapsRes(getActivity())));
}
}
});
final CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(45.4654, 9.1859)) // Sets the center of the map to location user
.zoom(Constants.CAMERA_ZOOM_LOCATION) // Sets the zoom
.build(); // Creates a CameraPosition from the builder
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mGoogleMap.setOnMapClickListener(MapsFragment.this);
// mGoogleMap.setOnInfoWindowClickListener(mInfoListener);
}
});
}
}).start();
}
#Override
public void onResume() {
mMapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mGoogleMap.clear();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
You can try to add markers only if it would be visible? I mean: first move camera to start position and set zoomLevel and just after that add Markers but only if it's in visible sector. And update markers on camera move.

How to use Google Maps in a fragment

I'm trying to put this class in a fragment , how can I make it into a fragment class?
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
I need these methods working in my fragment . But I'm not able to drive through the button
public void onSearch(View view) {
EditText location_tf = (EditText) findViewById(R.id.TFaddress);
String location = location_tf.getText().toString();
List<Address> addressList = null;
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
public void onZoom(View view) {
if (view.getId() == R.id.Bzoomin) {
mMap.animateCamera(CameraUpdateFactory.zoomIn());
}
if (view.getId() == R.id.Bzoomout) {
mMap.animateCamera(CameraUpdateFactory.zoomOut());
}
}
public void changeType(View view) {
if (mMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL) {
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
} else
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
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.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
All these actions are connected to the layout through " onClick "
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
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;
}
mMap.setMyLocationEnabled(true);
}
}
what works for me is this
childFragmentManager.fragments[0] as SupportMapFragment?
Let me explain : I have a fragment : Map Fragment and inside it there is an other fragmenr with the map so it is his only child. Be aware that i it is not the best practice but i works for now
class MapFragment : Fragment(), OnMapReadyCallback {
private lateinit var mMap: GoogleMap
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView: View = inflater.inflate(R.layout.fragment_map, container, false)
val mapFragment =
childFragmentManager.fragments[0] as SupportMapFragment?
mapFragment!!.getMapAsync(this)
return rootView
}
override fun onMapReady(googleMap: GoogleMap?) {
mMap = googleMap!!
// Add a marker in Sydney and move the camera
val sydney = LatLng(-34.0, 151.0)
mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
}
my xml of my fragment is
<?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=".ui.MainActivity">
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</FrameLayout>
Fragment Class should like this...
public MyMapFragment extends Fragment{
private GoogleMap map;
public GoogleApiClient mGoogleApiClient;
private LocationRequest locationRequest;
private Location myLocation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(getActivity()).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
}
#Override
public void onActivityCreated(Bundle savedInstance) {
super.onActivityCreated(savedInstance);
map = ((MapFragment) act.getFragmentManager()
.findFragmentById(R.id.map)).getMap();
map.getUiSettings().setRotateGesturesEnabled(false);
map.getUiSettings().setZoomControlsEnabled(false);
map.setTrafficEnabled(true);
map.setOnMarkerDragListener(dragListener);
map.setOnMapLongClickListener(longClickListener);
}
#Override
public void onStart() {
super.onStart();
if (mGoogleApiClient != null)
mGoogleApiClient.connect();
}
private void showCurrentLocation(Location location) {
if (map.getCameraPosition().zoom < MAP_ZOOM_LEVEl) {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
location.getLatitude(), location.getLongitude()), 12));
}
CameraPosition cameraPosition = new CameraPosition(new LatLng(
location.getLatitude(), location.getLongitude()),
map.getCameraPosition().zoom, 45, 360);
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
}
myLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (myLocation != null) {
showCurrentLocation(myLocation);
return;
}
if ("Check for GPS Status")
Show the error if not enabled
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, locationRequest, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if (location == null)
return;
myLocation = location;
showCurrentLocation(location);
}
});
}
protected void createLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onStop() {
super.onStop();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
}
#Override
public void onDestroyView() {
super.onDestroyView();
MapFragment mapFragment = (MapFragment) getActivity()
.getFragmentManager().findFragmentById(R.id.map);
if (mapFragment != null)
getActivity().getFragmentManager().beginTransaction()
.remove(mapFragment).commit();
}
}
Layout for that fragment
<?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" >
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
In my project, Maps was implemented in the following way:
No meu projeto em implementei o Maps da seguindo maneira:
public class MainFragment extends Fragment implements OnMapReadyCallback {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
MapFragment fragment = (MapFragment) getChildFragmentManager().findFragmentById(R.id.map);
fragment.getMapAsync(this);
} }

android GoogleMap is null, displays fine but can't add markers/polylines

I have a GoogleMap which displays fine (within a SupportMapFragment) and uses the GoogleMapOptions for the target camera location. However, I am unable to add markers/polylines to the GoogleMap. Here is the method for creating the map:
private void createMap(List<LatLng> latLngs) {
if(map == null) {
GoogleMapOptions options = new GoogleMapOptions();
mapFragment = SupportMapFragment.newInstance(options);
map = mapFragment.getMap();
float zoom = 13;
CameraPosition cameraP = new CameraPosition(latLngs.get(0), zoom, 0, 0);
options.camera(cameraP);
//TODO MAP IS NULL - SORT OUT!
// check it has been instantiated
if (map != null) {
Log.d(TAG, "map is not null");
map.clear();
//Calculate target zoom, based on trip size
map.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraP));
// Add LatLngs to polyline
PolylineOptions poly = new PolylineOptions().color(Color.RED);
MarkerOptions startMarker = new MarkerOptions()
.position(latLngs.get(0)).title("Start");
MarkerOptions endMarker = null;
if(latLngs.size() > 1) {
endMarker = new MarkerOptions().position(
latLngs.get(latLngs.size() - 1)).title("End");
}
for (LatLng latLng : latLngs) {
poly.add(latLng);
}
map.addPolyline(poly);
map.addMarker(startMarker);
map.addMarker(endMarker);
}
ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.trip_summary_map_container, mapFragment);
ft.commit();
}
}
As you can see from the inline comments, the map is still null (although it is displaying and using the options). Just can't add things to it. I assume I am not instantiating it properly?
The Activity extends FragmentActivity, and I have set up all the necessary stuff for using the Maps API.
Thank you for any help.
EDIT: I have posted a new answer with the solution I prefer to use now.
I had the same problem some days ago and I solved it extending SupportMapFragment class so that it executes a callback method once the map is finally ready.
public class ExtendedSupportMapFragment extends SupportMapFragment {
public static interface MapReadyListener {
public void mapIsReady(GoogleMap map);
}
#Deprecated
public static SupportMapFragment newInstance() {
return null;
}
#Deprecated
public static SupportMapFragment newInstance(GoogleMapOptions options) {
return null;
}
public static ExtendedSupportMapFragment newInstance(MapReadyListener mapReadyListener) {
ExtendedSupportMapFragment fragment = new ExtendedSupportMapFragment();
fragment.mapReadyListener = mapReadyListener;
return fragment;
}
private MapReadyListener mapReadyListener;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (mapReadyListener != null)
mapReadyListener.mapIsReady(getMap());
}
}
Then you just need to do something like this:
public class RutaMapaFragment extends SherlockFragment implements ExtendedSupportMapFragment.MapReadyListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragmentMapa = ExtendedSupportMapFragment.newInstance(RutaMapaFragment.this);
}
...
#Override
public void mapIsReady(GoogleMap map) {
//Do whatever you want with your map.
}
}
So, time has passed and all. The fact is that I don't use the solution in my previous answer anymore, but prefer to use a ViewTreeObserver instead. The following code shows a rather simple fragment with a SupportMapFragment being added to it.
The method createMap() adds the SupportMapFragment and then executes setupMap(), but only via a OnGlobalLayoutListener that will basically be executed once the map is actually ready. Of course, this listener is removed immediately—there's no need to keep it there any longer.
public class MyMapFragment extends Fragment {
private View mMapContainer;
private SupportMapFragment mMapFragment;
private GoogleMap mMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(/* ... */);
// ...
mMapContainer = view.findViewById(R.id.map_fragment_container);
createMap();
return view;
}
private void createMap() {
mMapFragment = new SupportMapFragment();
getFragmentManager().beginTransaction()
.replace(R.id.map_fragment_container, mMapFragment)
.commit();
mMapContainer.getViewTreeObserver()
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
mMapContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
mMapContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
mMap = mMapFragment.getMap();
setupMap();
}
});
}
private void setupMap() {
mMap.setMyLocationEnabled(true);
// ...
}
}
Try to add the Marker & PolyLines in the map using below code:
GoogleMap mMap;
static final CameraPosition BONDI =
new CameraPosition.Builder().target(new LatLng(-33.891614, 151.276417))
.zoom(15.5f)
.bearing(300)
.tilt(50)
.build();
changeCamera(CameraUpdateFactory.newCameraPosition(BONDI));
mMap.addMarker(new MarkerOptions().position(new LatLng(-33.891614, 151.276417)).title("Bondi"));
private void changeCamera(CameraUpdate update) {
changeCamera(update, null);
}
/**
* Change the camera position by moving or animating the camera depending on the state of the
* animate toggle button.
*/
private void changeCamera(CameraUpdate update, CancelableCallback callback) {
boolean animated = ((CompoundButton) findViewById(R.id.animate)).isChecked();
if (animated) {
mMap.animateCamera(update, callback);
} else {
mMap.moveCamera(update);
}
}
Add the PolyLines as below:
// A simple polyline with the default options from Melbourne-Adelaide-Perth.
mMap.addPolyline((new PolylineOptions())
.add(BONDI));

Categories

Resources