Resolve missing permissions require by GoogleMaps.setMyLocationEnalbled - android

I'm using Google maps to show my Office location inside Fragment. When I compile and run the application, It shows the maps but doesn't mark my location.
and on fragment java file, map.setMyLocationEnabled(true);
is been underlined by red color and I don't know how to solve it.
Below is my code from Fragment maps.
public class maps extends Fragment implements OnMapReadyCallback {
private Context mContext;
private SupportMapFragment supportMapFragment;
private GoogleMap map;
private MarkerOptions currentPositionMarker = null;
private Marker currentLocationMarker;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mContext = getActivity();
return inflater.inflate(R.layout.fragment_maps, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mContext = getActivity();
FragmentManager fm = getActivity().getSupportFragmentManager();/// getChildFragmentManager();
supportMapFragment = (SupportMapFragment) fm.findFragmentById(R.id.map_container);
if (supportMapFragment == null) {
supportMapFragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map_container, supportMapFragment).commit();
}
supportMapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
if (ActivityCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
map.setMyLocationEnabled(true);
map.animateCamera(CameraUpdateFactory.zoomTo(15));
/*map.setOnMapLongClickListener(MapyFragment.this);
map.setOnMapClickListener(MapFragment.this);*/
}
public void updateCurrentLocationMarker(Location currentLatLng){
if(map != null){
LatLng latLng = new LatLng(currentLatLng.getLatitude(),currentLatLng.getLongitude());
if(currentPositionMarker == null){
currentPositionMarker = new MarkerOptions();
currentPositionMarker.position(latLng)
.title("My Location").
icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_facebook_3));
currentLocationMarker = map.addMarker(currentPositionMarker);
}
if(currentLocationMarker != null)
currentLocationMarker.setPosition(latLng);
///currentPositionMarker.position(latLng);
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
Thanks in advance.

For the current location, you find the best solution with the proper example you find below google official document. Try it your self it will explore you.
https://developers.google.com/maps/documentation/android-api/current-places-tutorial?hl=pt-br

Related

current location in fragment

I have tried many sources but I am not getting what should be used for my fragment to get the current location.
This is my fragment:
public class GMapFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap googleMap;
MapFragment fragment;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gmap, container, false);
initilizeMap();
return rootView;
}
private void initilizeMap()
{
MapFragment fragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
if (fragment != null){
fragment.getMapAsync(this);
}
}
#Override
public void onMapReady(final GoogleMap googleMap) {
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
}
#Override
public void onPause() {
final FragmentManager fragManager = this.getFragmentManager();
final Fragment fragment = fragManager.findFragmentById(R.id.map);
if(fragment!=null){
fragManager.beginTransaction().remove(fragment).commit();
super.onPause();
}
}
#Override
public void onDestroy() {
super.onDestroy();
final FragmentManager fragManager = this.getFragmentManager();
final Fragment fragment = fragManager.findFragmentById(R.id.map);
if(fragment!=null){
fragManager.beginTransaction().remove(fragment).commit();
}
}
}
If anyone can help? I need a source or sample that can be used with this fragment. please help, I'm stuck here for days
from documentation
While enabled and the location is available
Do you have available location ?
Did you have ACCESS_FINE_LOCATION in your Manifest file?
Also, know that if your app is running on >= API 23 device, you have to request the permission grant from the users.
Follow the official GUIDE
EDIT:
Do you have initialized Google Play Services?
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(getActivity()).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
Connect the above google api client in onStart and disconnect in onstop
#Override
public void onStart() {
super.onStart();
if (mGoogleApiClient != null)
mGoogleApiClient.connect();
}
Override the methods.
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 (!NetworkHelper.isGpsEnabled(getActivity()))
PopUp.showAlertDialog(act, "Enable GPS",
"Help us to get your current location");
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, locationRequest, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if (location == null)
return;
myLocation = location;
showCurrentLocation(location);
}
});
}

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);
} }

google map is not showing marker on it

this is my activity
public class FindPeopleFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap googleMap;
MapFragment fragment;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_find_people, container, false);
initilizeMap();
return rootView;
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void initilizeMap() {
MapFragment fragment = (MapFragment) getChildFragmentManager().findFragmentById(R.id.map1);
if (fragment != null) {
fragment.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng marker = new LatLng(44.797283, 20.460663);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(44.797283, 20.460663), 12));
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(44.797283, 20.460663))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
googleMap.setMyLocationEnabled(true);
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public void onPause() {
final FragmentManager fragManager = this.getFragmentManager();
final Fragment fragment = fragManager.findFragmentById(R.id.map1);
if (fragment != null) {
fragManager.beginTransaction().remove(fragment).commit();
super.onPause();
}
}
#Override
public void onDestroy() {
super.onDestroy();
final FragmentManager fragManager = this.getFragmentManager();
final Fragment fragment = fragManager.findFragmentById(R.id.map1);
if (fragment != null) {
fragManager.beginTransaction().remove(fragment).commit();
}
}
}
I am using navigation drawer to show the map. my map is working but the marker on it does not show. I have used all permission and created the xml file well. I don't know what is the problem, I can't find a solution for this anywhere. I think I am having problem as I am using fragment, but I need it as I am using navigation drawer. please anybody? give me a solution, I'm stuck at this
You should implement onMapReadyCallback, you should set marker when map is ready. Once an instance of this interface is set on a MapFragment or MapView object, the onMapReady(GoogleMap) method is triggered when the map is ready to be used and provides a non null instance of GoogleMap.
The onMapReady() and method might not being called. Try to implement SupportMapFragment object that you retrieved from the XML layout. Then, call getMapAsync().
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final GoogleMap googleMap) {
// ...
}
});

App crashes when I close the app [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 8 years ago.
I have integrated Google Maps in ViewPager and afterward, when I close my app by pressing back button, I get "Unfortunately app has closed" message. If anyone have gone through issue and get solved, please let me know how to solve it.
Code
public class NearestBathroomMapView extends Fragment {
//Declare all necessary objects
public static View view;
public static GoogleMap gMap;
public static Double latitude,longitude;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(container==null){
return null;
}
//Inflate the view
view= inflater.inflate(R.layout.bathroomsmapview,
container, false);
latitude=27.706750;//declare latitude and logitude
longitude=85.314513;
setUpIfMapNeeded();
//call this function to obtain SupportMapFragment
return view;
}
//Get the map from SupportMapFragment
public void setUpIfMapNeeded(){
// Try to obtain the SupportMapFragment if map does not equal null.
if (gMap == null) {
gMap = ((SupportMapFragment) BathroomInformation.fragmentManager
.findFragmentById(R.id.location_map)).getMap();
//call this function to display map
if (gMap != null){
setUpMap();
}
}
}
private void setUpMap() {
gMap.setMyLocationEnabled(true);
//add marker in map
gMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My Home").snippet("Home Address"))
//setup map position and animate it
gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,
longitude), 12.0f));
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//view created to display map
if (gMap != null)
setUpMap();
//get SupportMapFragment if map is equal to null
if (gMap == null) {
gMap = ((SupportMapFragment) BathroomInformation.fragmentManager
.findFragmentById(R.id.location_map)).getMap();
//set up map if map is not null
if (gMap != null)
setUpMap();
}
}
//should I need to call this below function onBackPressed method ??
public void onDestroyView() {
super.onDestroyView();
//map fragment get remove from FragmentManager
if (gMap != null) {
BathroomInformation.fragmentManager.beginTransaction()
.remove(BathroomInformation.fragmentManager
.findFragmentById(R.id.location_map)).commit();
gMap = null;
}
}
}
I think you should eliminate your
public void onDestroyView()
function. I don't see correct to remove a fragment that is destroyed.
Hope it helps.

android MapFragment doesn't show on replace

I have two FrameLayout in an activity, I just replace fragments inside those FrameLayout.
It works great with everyfragment BUT the one containing the MapFragment for the GoogleMap.
When I first launch the app it works and I see the map (everything works) but when I replace the fragment and replace it back I just get a blank space like nothing is loaded.
public class MapFragment extends CustomFragment {
private GoogleMap mMap;
private Marker currentMarker;
private OnFragmentInteractionListener mListener;
public static final String ID = "MAP_FRAGMENT";
private static View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = null;
try {
view = inflater.inflate(R.layout.fragment_map, container, false);
} catch (InflateException e) {
Log.d("","");
}finally{
setUpMapIfNeeded();
if(view!=null)this.view=view;
return this.view;
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
Fragment f = getFragmentManager().findFragmentById(R.id.map);
if (f != null)getActivity().getFragmentManager().beginTransaction().remove(f).commit();
mMap=null;
currentMarker=null;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
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 = ((com.google.android.gms.maps.MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void update(FragmentMessage message) {
if(mMap!=null) {
Location loc = (Location) message.getMessages()[0];
if (currentMarker != null)
currentMarker.remove();
currentMarker = mMap.addMarker(new MarkerOptions().position(new LatLng(loc.getLatitude(), loc.getLongitude())).title("Marker"));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(loc.getLatitude(), loc.getLongitude())) // Sets the center of the map to Mountain View
.zoom(15) // Sets the zoom
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
}
The mMap is never null, so the MapFragment is working I guess but I don't get anything on the screen (see screenshots below).
Does anyone have an idea ? I really don't know what is wrong.

Categories

Resources