I'm new to Android Development and I am trying to development an application which will display a google map with the users current location. I have been sucessful in incorporating the map in and adding markers but having issues with getting the current location. I have added location permissions in.
activity_location.xml
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
Android Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.alicearmstrong.coffeysloyaltyprojectv1">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme.NoActionBar">
<uses-library android:name="org.apache.http.legacy" android:required="false" />
<activity
android:name=".NavigationMainOwner"
android:label="#string/title_activity_navigation_main_owner" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/api_map_key" />
....
LocationFragment.java
public class LocationFragment extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private LocationViewModel locationViewModel;
private GoogleMap gMap;
private MapView mapView;
private Location currentLocation;
private int LOCATION_PERMISSION_REQUEST_CODE = 1234;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
locationViewModel = ViewModelProviders.of( this ).get( LocationViewModel.class );
View view = inflater.inflate( R.layout.fragment_location_customer, container, false );
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated( view, savedInstanceState );
mapView = (MapView) view.findViewById( R.id.map );
if (mapView != null)
{
mapView.onCreate( null );
mapView.onResume();
mapView.getMapAsync( this );
checkLocationPermission();
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
MapsInitializer.initialize( getContext() );
gMap = googleMap;
LatLng coffeys = new LatLng( 54.572720, -5.959151 );
gMap.addMarker( new MarkerOptions().position( coffeys ).title( "Coffey's Butchers" ) );
gMap.moveCamera( CameraUpdateFactory.newLatLngZoom( coffeys, 12 ) );
}
private final LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// GPS may be turned off
if (location == null) {
return;
}
Double lat = location.getLatitude();
Double lng = location.getLongitude();
currentLocation = location;
Toast.makeText( getActivity(), "Updated Location: " + lat + lng, Toast.LENGTH_SHORT ).show();
}
};
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public boolean checkLocationPermission()
{
if (ContextCompat.checkSelfPermission( getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION )
!= PackageManager.PERMISSION_GRANTED)
{
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale( getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION ))
{
//Prompt the user once explanation has been shown
requestPermissions( new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE
);
} else {
// No explanation needed, we can request the permission.
requestPermissions( new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE );
}
return false;
}
else
{
return true;
}
}
}
Any help in the right direction would be greatly appreciated! Many Thanks.
You can use Google Maps default current location setting it with gMap.setmylocationenabled(true). Or you can use moveCamera(CameraUpdate update) when getting your current location in your locationListener.
Related
After the first inclusion, the application requests permission to detect the location and the setMyLocationEnabled (true) button is not displayed on map.
The setMyLocationEnabled (true) button is displayed only after I restart the application or switch to another fragment, then return to the map again.
Could it be that I use fragments and because of this the application works this way?
please help solve this problem.
public class MapFragment extends Fragment implements OnMapReadyCallback {
private FusedLocationProviderClient _mFusedLocationProviderClient;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 101;
private GoogleMap _map;
private Location _mLastKnownLocation;
SharedManager _manager;
Connect _connect;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_manager = new SharedManager(getActivity());
_connect = new Connect();
_mFusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(getActivity());
}
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_map, container, false);
getLocation();
return root;
}
#Override
public void onMapReady(GoogleMap googleMap) {
_map = googleMap;
_map.getUiSettings().setZoomControlsEnabled(false);
_map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
_map.setMyLocationEnabled(true);
_map.getUiSettings().setMyLocationButtonEnabled(true);
}
private void getLocation() {
if (ActivityCompat.checkSelfPermission(
getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(
getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{
Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
return;
}
Task<Location> locationResult = _mFusedLocationProviderClient.getLastLocation();
locationResult.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
SupportMapFragment mapFrag = (SupportMapFragment)
getChildFragmentManager().findFragmentById(R.id.map_View);
mapFrag.getMapAsync(MapFragment.this);
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
getLocation();
}
break;
}
}
}
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I will be glad to any advice.
I want to zoom to the current location of user when activity started. I have two java class. One of is MapActivity.java and the other is MapFragment.java. I'm trying to do this job on MapFragment.java.
private Actvity activity;
private volatile GoogleMap googleMap;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
}
MapFragment.java/onMapReady ;
#Override
public void onMapReady(GoogleMap map) {
googleMap = map;
mGoogleApiClient=new GoogleApiClient.Builder(activity)
.addApi(LocationServices.API)
.addConnectionCallbacks(activity)
.addOnConnectionFailedListener(activity)
.build();
mGoogleApiClient.connect();
}
In this onMapReady, .addConnectionCallbacks(activity) and .addOnConnectionFailedListener(activity) are giving warning like in the image;
enter image description here
In the examples that I have analyzed before they are implementing GoogleApiClient.ConnectionCallbacks and GoogleApiCleint.OnConnectionFailedListener not casting. Without implementing, I couldn't get these functions;
#Override
public void onConnected(Bundle bundle) {
mLocationRequest=LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
And also I have to get LocationListeners's method;
#Override
public void onLocationChanged(Location location) {
if(location == null){
Toast.makeText(this,"Cant get current location",Toast.LENGTH_LONG).show();
}
else{
LatLng ll= new LatLng(location.getLatitude(),location.getLongitude());
CameraUpdate update= CameraUpdateFactory.newLatLngZoom(ll,15);
mGoogleMap.animateCamera(update);
}
}
If I implement them by hand in the fragment, does it cause any problem? What is the proper way to get current location in fragment activity?
If I implement them by hand in the fragment, does it cause any
problem?
No. All you need to do is implement ConnectionCallbacks and OnConnectionFailedListener.
What is the proper way to get current location in fragment activity?
public class MyFragment extends Fragment implements
ConnectionCallbacks, OnConnectionFailedListener {
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient); // this is your location
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
}
Reference
I have implemented a Fragment in Activity and Location listener and MapReady is called in fragment to get current location. Refer the below code.
MainActivity.Java
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setFragment(new MapFragment());
}
// class for being re-used by several instances
protected void setFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment);
fragmentTransaction.commit();
}
}
Activity_Main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<FrameLayout
android:id="#+id/frame_containerone"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/imagenext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="16dp"
/>
</RelativeLayout>
MapFragment.Java
public class MapFragment extends Fragment implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener, OnMapReadyCallback {
private static final String TAG = "MapFragment";
MainActivity mActivity;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
SupportMapFragment mapFragment;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.map_fragment, null, true);
mActivity = ((MainActivity) getActivity());
initViews(view);
return view;
}
private void initViews(View view) {
mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
handleNewLocation(location);
}
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(mActivity, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
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.
mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);// mapFragment.getMapAsync((OnMapReadyCallback) mActivity);
}
}
#Override
public void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
}
map_fragment.xml
<?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:orientation="vertical">
<!-- <fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />-->
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="388dp"
android:layout_weight="0.40" />
</LinearLayout>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.theme.fragment">
<permission
android:name="com.theme.fragment.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.theme.fragment.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Required to show current location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Goolge API Key -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="Your_Api key" />
</application>
</manifest>
I am new to android development. I am working on Android Studio and developing an app on which i have 3 tabs. One tab is for maps, second is for camera and 3rd is for pictures. I am using google map for viewing map. The map will show current GPS location of the user. For this i am using a mapViewand done all of the work, but still unable to view the map.
Below is my manifest
<permission android:name="com.example.accurat.faisal.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.accurat.faisal.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.hardware.camera"/>
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:name="android.support.multidex.MultiDexApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="MY_Key"
/>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
The location class is as follows
public class MyLocation extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener{
GoogleMap mGoogleMap;
MapView mapView;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
TextView tv_loc;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View rootView = inflater.inflate(R.layout.my_location, container, false);
mapView = (MapView)rootView.findViewById(R.id.map);
tv_loc = (TextView)rootView.findViewById(R.id.textView);
mapView.getMapAsync(this);
return rootView;
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if(mGoogleApiClient !=null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
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 onLocationChanged(Location location) {
double lattitude = location.getLatitude();
double longitude = location.getLongitude();
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(lattitude, longitude);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("I am here");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
tv_loc.append("Lattitude: " + lattitude + " Longitude: " + longitude);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(getActivity())
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
/*super.onRequestPermissionsResult(requestCode, permissions, grantResults);*/
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED)
{
if(mGoogleApiClient == null)
{
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
//finish();
Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}}
Update 1
Below is my layout for location
<RelativeLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.accurat.faisal.MyLocation$PlaceholderFragment">
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/section_label"
android:id="#+id/textView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textAppearance="#style/TextAppearance.AppCompat.Body2" />
<com.google.android.gms.maps.MapView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:id="#+id/map" /></RelativeLayout>
When i run my app i just see an empty tab, map doesn't shows. I must be missing something and i don't know what. I have searched many articles on it but couldn't find appropriate help so that's why i am posting a question here.
Any help would be highly appreciated
I am having a small issue when starting my app. The tiles which should show up are only loaded after tapping on the map... afterwards all seems to work fine!
In logcat I see the following error:
E/EnterpriseContainerManagerīš ContainerPolicy Service is not yet
ready!!!
public class MainActivity extends FragmentActivity {
private static final String TAG = "MAIN_ACTIVITY";
private MyLocationListener locListener;
private SupportMapFragment supportMapFragment;
private GoogleMap gmap;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setUpMap();
list = new ArrayList<GPSCoordinates>();
new Object();
}
#Override
protected void onStart() {
super.onStart();
if (gmap == null) {
gmap = supportMapFragment.getMap();
Log.i(TAG, "gmap set!");
}
if(locListener == null) {
this.initLocationManager();
}
Log.i(TAG, "gmap start!");
}
#Override
protected void onStop() {
super.onStop();
Log.i(TAG, "gmap stop!");
}
private void setUpMap() {
GoogleMapOptions options = new GoogleMapOptions();
options.mapType(GoogleMap.MAP_TYPE_NORMAL)
.camera(CameraPosition.fromLatLngZoom(new LatLng(47.384906, 15.093149), 25));
//supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
if(supportMapFragment == null) {
supportMapFragment = SupportMapFragment.newInstance(options);
getSupportFragmentManager().beginTransaction().replace(R.id.map, supportMapFragment).commit();
}
}
}
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="at.ac.unileoben.infotech.paapp.MainActivity"
tools:ignore="MissingPrefix">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment" />
</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="at.ac.unileoben.infotech.paapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="at.ac.unileoben.infotech.paapp.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<permission android:name="at.ac.unileoben.infotech.paapp.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="at.ac.unileoben.infotech.paapp.MainActivity"
android:label="#string/app_name"
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="at.ac.unileoben.infotech.paapp.SettingsActivity"
android:label="#string/action_settings" />
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="XXX" />
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version"/>
</application>
</manifest>
edit:
i changed the code of my main_activity to the following..
public class MainActivity extends FragmentActivity {
private ArrayList<GPSCoordinates> list;
private static final String TAG = "MAIN_ACTIVITY";
private static Context context;
private MyLocationListener locListener;
private SupportMapFragment supportMapFragment;
private GoogleMap gmap;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setUpMap();
list = new ArrayList<GPSCoordinates>();
// access context global
MainActivity.context = getApplicationContext();
new Object();
}
#Override
protected void onStart() {
super.onStart();
if (gmap == null) {
gmap = supportMapFragment.getMap();
Log.i(TAG, "gmap set!");
}
if(locListener == null) {
this.initLocationManager();
}
Log.i(TAG, "gmap start!");
}
#Override
protected void onResume() {
super.onResume();
Log.i(TAG, "gmap resume!");
}
private void setUpMap() {
if(supportMapFragment == null) {
supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
}
}
later on im calling my simulatelocationmanager with:
private void initLocationManager() {
locListener = new MyLocationListener(gmap);
// Define a listener that responds to location updates
// Register the listener with the Location Manager to receive location updates
SimulateLocationManager simulatedLocationManager = new SimulateLocationManager();
//LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
simulatedLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 0, locListener);
Log.i(TAG, "locListener");
}
in the locationmanager i call the function viewlocation onlocationchanged
public void viewLocation(double latitude, double longitude)
{
float bearing = this.bearing();
Log.i(TAG2, "bearing" + bearing);
gmap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition.Builder()
.target(new LatLng(latitude, longitude))
.bearing(bearing)
.tilt(55f)
.zoom(gmap.getCameraPosition().zoom).build()));
}
as i allready said before the problem is that the tiles arent shown till i tap on the map..
all the other things seem to work because i can see the camera moving. but why are the tiles not loaded?
thank you for your reply!
Already accepted answer is there about your issue :Find here
If you set up the SupportMapFragment via the <fragment> element in the layout, you can call getMap() successfully in onCreate(). But, if you create the SupportMapFragment via the constructor, that's too soon -- the GoogleMap does not yet exist. You can extend SupportMapFragment and override onActivityCreated(), as getMap() is ready by then.
However, getMap() can also return null for a bigger problem, such as Google Play Services not being installed. You would need to use something like GooglePlayServicesUtil.isGooglePlayServicesAvailable() to detect this condition and deal with it however you wish.
I am having some prolems with my google maps app. For now the app was only suppost to get my location em zoom in it, but is not working. My location aways ends in the top of the map. Here is my code:
MainActivity:
public class MainActivity extends Activity implements LocationListener {
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (isGooglePlayOk()) {
setContentView(R.layout.activity_main);
setMap();
googleMap.setMyLocationEnabled(true);
}
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.action_legalnotices:
startActivity(new Intent(this, LegalNoticeActivity.class));
return true;
default:
return false;
}
}
private boolean isGooglePlayOk() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status == ConnectionResult.SUCCESS) {
return (true);
}
else {
((Dialog) GooglePlayServicesUtil.getErrorDialog(status, this, 10))
.show();
}
return (false);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.main.map)).getMap();
if (googleMap != null) {
}
googleMap.setMyLocationEnabled(true);
LocationManager la = (LocationManager) getSystemService(LOCATION_SERVICE);
String provider = la.getBestProvider(new Criteria(), true);
Location loc = la.getLastKnownLocation(provider);
if (provider != null) {
onLocationChanged(loc);
}
googleMap.setOnMapLongClickListener(onLongClickMapSettiins());
}
}
private OnMapLongClickListener onLongClickMapSettiins() {
// TODO Auto-generated method stub
return new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
Toast.makeText(getApplicationContext(), "OK",
Toast.LENGTH_SHORT).show();
}
};
}
#Override
public void onLocationChanged(Location location) {
LatLng latlong = new LatLng(location.getLatitude(),
location.getLongitude());
googleMap.setMyLocationEnabled(true);
CameraPosition cp = new CameraPosition.Builder().target(latlong)
.zoom(15).build();
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cp));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+main/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mapateste"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<!--
The following two permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="(My Api is working fine)" />
<activity
android:name="com.example.mapateste.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.mapateste.LegalNoticeActivity"
android:label="#string/title_activity_legal_notice" >
</activity>
</application>
I can only test in my device. The map is working fine but i cannot get my position on the center of the screen right away only clicking at the mylocationbutton. Somebody can help me?
Just declare a point where you want to center your point.
LatLng cur_Latlng = new LatLng(21.0000, 78.0000);
gm.moveCamera(CameraUpdateFactory.newLatLng(cur_Latlng));
gm.animateCamera(CameraUpdateFactory.zoomTo(4));
the desired zoom level is in the range of 2.0 to 21.0.
// try this
#Override
public void onLocationChanged(Location location) {
LatLng latlong = new LatLng(location.getLatitude(),
location.getLongitude());
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latlong));
googleMap.animateCamera(CameraUpdateFactory.zoomBy(15));
}
Your min sdk is 8. You should use SupportMapFragment. Your class must extend FragmentActivtiy
Check the line above developers guide heading in the below link
https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/MapFragment
<fragment
class="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Use SupportMapFragment
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
GoogleMap mMap = fm.getMap();
Make sure you have added support library
Also make sure you imported the below
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.SupportMapFragment
To zoom
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latlong,20);
googleMap.moveCamera(update);
This is working Current Location with zoom for Google Map V2
double lat= location.getLatitude();
double lng = location.getLongitude();
LatLng ll = new LatLng(lat, lng);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 20));
Note that the My Location layer does not return any data. If you wish to access location data programmatically, use the Location API.
In your MainActivity (onCreate Method)
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(MainActivity.this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
On method onMapReady
#Override
public void onMapReady(GoogleMap googleMap) {
GoogleMap mMap = googleMap;
// Set blue point on the map at your cuurent location
mMap.setMyLocationEnabled(true);
// Show zoon controls on the map layer
mMap.getUiSettings().setZoomControlsEnabled(true);
//Show My Location Button on the map
mMap.getUiSettings().setMyLocationButtonEnabled(true);
}
on method onConnected
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
LocationListener.latlonInit= new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude());
CameraPosition target = CameraPosition.builder().tilt(66.0f).target(LocationListener.latlonInit)
.zoom(MainActivity.ZOOM).build();
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(target));
}
}
You class should extend Fragment Activity
public class MainActivity extends FragmentActivity {
//assign any arbitrary value to GPS_ERRODIALOG_REQUEST
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
GoogleMap googlemap;
}
for Google Service Ok method I would do Following:
public boolean isGooglePlayOk(){
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
}
else if(GooglePlayServicesUtil.isUserRecoverableError(isAvailable)){
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, GPS_ERRORDIALOG_REQUEST);
dialog.show();
}
else {
Toast.makeText(this, "Can't connect to Goolge Play", Toast.LENGTH_SHORT).show();
}
return false;
}
In the .xml file, when you declare the fragment, you need to support Map Fragment since your min skd is 8:
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:maps="http://schemas.android.com/apk/res-auto"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
activity_map.xml is for displaying map if condition is true for setMap else go to you regular activity_main.xml.
public class MainActivity extends FragmentActivity {
GoogleMap mMap;
if (isGooglePlayOk()) {
setContentView(R.layout.activity_map);
if (setMap()) {
mMap.setMyLocationEnabled(true);
}
else {
//your code
}
}
else {
setContentView(R.layout.activity_main);
}
method for setMap:
private boolean setMap() {
if (mMap == null) {
SupportMapFragment mapFrag =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFrag.getMap();
}
return (mMap != null);
}
If you want to automatically zoom to some point in google maps v2 u can do like this
private float previousZoomLevel = 13.00f;
LatLng zoomPoint = new LatLng(12.977286, 77.632720);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(zoomPoint,previousZoomLevel));
here previousZoomLevel is level of zoom