Hello I am new with android. this code work with extend Activity class but i use this class with extend with Fragment, Its not working. I addes added all the permissions in manifest. I use this Fragment class with the Bottom navigation menu. Please help me.
This is my Fragment Class (LoctionFragment.java)
public class LoctionFragment extends Fragment implements OnMapReadyCallback, LocationListener{
GoogleMap map;
LocationManager locationManager;
TextView viewLocation;
public LoctionFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.location_layout, container, false);
viewLocation = v.findViewById(R.id.viewLocation);
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), android.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.
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, (LocationListener) this);
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
}
#Override
public void onLocationChanged(Location location) {
map.clear();
LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(currentLocation);
markerOptions.title("MY LOCATION");
map.addMarker(markerOptions);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 17.0f));
if (location != null) {
double latti = location.getLatitude();
double longi = location.getLongitude();
viewLocation.setText("Current Location is :" + latti + "," + longi);
} else {
viewLocation.setText("Unable to find current location . Try again later");
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
This is layout xml map view (location_layout.xml)
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="383dp"
android:layout_x="1dp"
android:layout_y="39dp" />
You put the MapFragment as a child fragment of the LocationFragment, so you need to use getChildFragmentManager:
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
Related
Being very new to java, I am very confused about getting lastknownlocation and updated location.
Over last few days, I have managed to get the mark on a predefined location, but I am struggling very much on getting my current location using fusedlocationproviderclient.
I will be grateful if somebody kindly help me on getting this.
I am using :
compile 'com.google.android.gms:play-services-maps:11.8.0'
compile 'com.google.android.gms:play-services-location:11.8.0'
Though not for the updated location, below is the code for marker at a fixed position
public class SecondFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
public GoogleMap getMap() {
return mMap;
}
public static SecondFragment newInstance() {
SecondFragment fragment = new SecondFragment();
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_maps, null, false);
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return view;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
I am using this to get my location:
LocationManager locationManager = (LocationManager)getActivity().getSystemService(getContext().LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
and listener for this:
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.e("osm", "onLocationChanged: "+location.getLongitude() );
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
Do not forget write to manifest this:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
and runtime permission for new version of android(6 and up) :
String[] permission = new String[]{Manifest.permission.CALL_PHONE,Manifest.permission.ACCESS_FINE_LOCATION};
ActivityCompat.requestPermissions(this,permission,PERMISSON_CODE);`
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
I wrote code in Android studio to display my location in a Google Map fragment but it is not doing so. The map is being displayed but the coordinates I want is not getting marked. The code is the following:
public class SEMapTab extends Fragment implements OnMapReadyCallback {
private View rootView;
private MapFragment mMapFrag;
private GoogleMap mMap;
private LocationManager locationManager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null)
parent.removeView(rootView);
}
try {
rootView = inflater.inflate(R.layout.single_entity_map, container, false);
} catch (InflateException e) {
}
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
if (mMapFrag == null) {
super.onViewCreated(view, savedInstanceState);
FragmentManager fragment = getActivity().getFragmentManager();
mMapFrag = (MapFragment) fragment.findFragmentById(R.id.map);
mMapFrag.getMapAsync(this);
}
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), 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;
}
//if network provider is enabled
if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double Latitude= location.getLatitude(); //Get latitude
double Longitude = location.getLongitude(); //Get longitude
LatLng latLng= new LatLng(Latitude, Longitude);
//Map latitude and longitude
mMap.addCircle(new CircleOptions().center(latLng).fillColor(Color.BLUE).radius(10));
//Zoom in to current location
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,18));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
//else if gps provider is enabled
else if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double Latitude= location.getLatitude(); //Get latitude
double Longitude = location.getLongitude(); //Get longitude
LatLng latLng= new LatLng(Latitude, Longitude);
//Map latitude and longitude
mMap.addCircle(new CircleOptions().center(latLng).fillColor(Color.BLUE).radius(10));
//Zoom in to current location
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,18));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
}
}
I have also included the necessary permissions in AndroidManifest.xml file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
The Map fragment is opening but there is no circle getting marked at my current location. Alternatively, if I hard code a GPS location in OnMapReady function, then that is gettig marked and is working fine. I request you to help me resolve this issue.
At onMapReady add googleMap.setMyLocationEnabled(true). No need to handle "manually" the location manager and these providers. Just be sure that user has given the permission to the app to access his location before call this, otherwise the app will crash.
I don't know why my map doesn't call to onLocationChanged when I press my button. These are my permissions:
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_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.INTERNET" />
This is my class:
public class NuevaCarreraFragment extends Fragment implements OnMapReadyCallback, LocationListener, View.OnClickListener {
private View view;
private LiveButton btnIniciarCarrera;
private LiveButton btnFinalizarCarrera;
private SupportMapFragment mapFragment;
private GoogleMap mGoogleMap;
private LocationManager locationManager;
public static NuevaCarreraFragment newInstance() {
Bundle args = new Bundle();
NuevaCarreraFragment fragment = new NuevaCarreraFragment();
fragment.setArguments(args);
return fragment;
}
/** Ciclo de vida **/
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// Comprobamos si la vista ya ha sido inflada previamente
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {// Si no ha sido inflada previamente...
view = inflater.inflate(R.layout.fragment_nueva_carrera, container, false);
// Instanciamos los componentes
btnIniciarCarrera = (LiveButton) view.findViewById(R.id.button_iniciar_carrera);
btnFinalizarCarrera = (LiveButton) view.findViewById(R.id.button_finalizar_carrera);
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
// Escuchamos a nuestros componentes
btnIniciarCarrera.setOnClickListener(this);
btnFinalizarCarrera.setOnClickListener(this);
// Sincronizamos nuestro mapa
mapFragment.onCreate(savedInstanceState);
mapFragment.getMapAsync(this);
} catch (InflateException e) {
e.printStackTrace();
}
return view;
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
if (mapFragment != null) {
mapFragment.onResume();
}
}
#Override
public void onPause() {
if (mapFragment != null) {
locationManager.removeUpdates(this);
mapFragment.onPause();
}
super.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroy() {
Fragment fragment = getFragmentManager().findFragmentById(R.id.map);
if (fragment != null) {
getFragmentManager().beginTransaction()
.remove(fragment)
.commit();
}
super.onDestroy();
}
#Override
public void onDestroyView() {
super.onDestroyView();
Fragment fragment = getFragmentManager().findFragmentById(R.id.map);
if (fragment != null) {
getFragmentManager().beginTransaction()
.remove(fragment)
.commit();
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
if (mapFragment != null) {
mapFragment.onLowMemory();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mapFragment != null) {
mapFragment.onSaveInstanceState(outState);
}
}
/** OnClickListener **/
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_iniciar_carrera:
// Inicializamos el localizador
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
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;
}
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
break;
case R.id.button_finalizar_carrera:
locationManager.removeUpdates(this);
break;
}
}
/** OnMapReadyCallback and LocationListener interface methods **/
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
LatLng sydney = new LatLng(-33.867, 151.206);
mGoogleMap.addMarker(new MarkerOptions()
.title("Sydney")
.snippet("The most populous city in Australia.")
.position(sydney));
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));
}
/** LocationListener interface methods **/
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng misCoordenadas = new LatLng(latitude, longitude);
Geocoder geocoder = new Geocoder(getContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String direccion = addressList.get(0).getAddressLine(0);
direccion += "," + addressList.get(0).getLocality();
direccion += "," + addressList.get(0).getCountryName();
mGoogleMap.addMarker(new MarkerOptions()
.position(misCoordenadas)
.title(direccion)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(misCoordenadas, 17));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
The map is properly displayed, but it does not get my location :(.
Any idea ?
UPDATE
Finally I was able to solve de problem implementing Google API Client and Fused Location Api.
Does the app has permission ? Did you handle the not granted case ?
And those provider(s) the app requests are enabled ?
Did you debug the app, and reach the any of locationManager.requestLocationUpdates line ?
Seems like the app is not requesting due to lacking of 1 and 2
This is not the first question im posting regarding this matter in Stack Overflow. I really need help to zoom my map fragment to the current location. Please don't think I'm not trying anything. I tried a lot.
I need to zoom my map to the current location and no matter how hard I tried map zoom to another location not my current location. Cannot even possibly think what is happening here.
Here is my GoogleMapsFragment.java
public class GoogleMapsFragment extends android.support.v4.app.Fragment implements LocationListener, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
View rootView;
private GoogleApiClient mGoogleApiClient;
private GoogleMap map;
private LatLng latlng;
public GoogleMapsFragment()
{
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(!isGooglePlayServiceAvailable())
{
return null;
}
if(rootView != null)
{
ViewGroup parent = (ViewGroup)rootView.getParent();
if(parent != null)
{
parent.removeView(rootView);
}
}
else
{
rootView = inflater.inflate(R.layout.google_maps, container, false);
map = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
.getMap();
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
if (mapFragment != null)
mapFragment.getMapAsync(this);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
}
return rootView;
}
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions().position(latLng));
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
private boolean isGooglePlayServiceAvailable()
{
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if(ConnectionResult.SUCCESS == status)
{
return true;
}
else
{
GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
return false;
}
}
//Zoom to the current location
public Location getMyLocation() {
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
return location;
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(5), 5000, null);
map.getUiSettings().setZoomControlsEnabled(false);
map.getUiSettings().setCompassEnabled(false);
map.getUiSettings().setMyLocationButtonEnabled(true);
}
#Override
public void onConnected(Bundle bundle) {
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
}
I think I've dome a small mistake and it zooms to another location and it is not even close to my country.
Here is the image of my zooming location.
Someone please tell me how to zoom my map fragment to the current location.
Any kind of help may appreciated. :)
~ Edit for Gaurav ~
Added getMyLocation() inside onMapReady()
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
getMyLocation();
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(5), 5000, null);
map.getUiSettings().setZoomControlsEnabled(false);
map.getUiSettings().setCompassEnabled(false);
map.getUiSettings().setMyLocationButtonEnabled(true);
}
~ Edited full code ~
public class GoogleMapsFragment extends android.support.v4.app.Fragment implements LocationListener, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
View rootView;
private GoogleApiClient mGoogleApiClient;
private GoogleMap map;
private LatLng latlng;
public GoogleMapsFragment()
{
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(!isGooglePlayServiceAvailable())
{
return null;
}
if(rootView != null)
{
ViewGroup parent = (ViewGroup)rootView.getParent();
if(parent != null)
{
parent.removeView(rootView);
}
}
else
{
rootView = inflater.inflate(R.layout.google_maps, container, false);
map = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
.getMap();
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
if (mapFragment != null)
mapFragment.getMapAsync(this);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
}
return rootView;
}
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions().position(latLng));
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
private boolean isGooglePlayServiceAvailable()
{
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if(ConnectionResult.SUCCESS == status)
{
return true;
}
else
{
GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
return false;
}
}
//Zoom to the current location
public Location getMyLocation() {
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
return location;
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
Location myLocation = getMyLocation();
LatLng latLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
latLng
, 15));
}
private LocationRequest mLocationRequest;
private static final long INTERVAL = 1000 * 1000;
private static final long FASTEST_INTERVAL = 1000 * 900;
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
}
~ Error Log ~
06-16 11:23:28.180 6647-6647/com.myayubo E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.myayubo, PID: 6647
java.lang.NullPointerException
at com.myayubo.GoogleMapsFragment.onMapReady(GoogleMapsFragment.java:151)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzl$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:361)
at com.google.android.gms.maps.internal.v$a$a.a(:com.google.android.gms.alldynamite:82)
at maps.ei.bu$6.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
at dalvik.system.NativeStart.main(Native Method)
Here it is:
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
Location myLocation = getMyLocation();
LatLng latLng = new LatLng(myLocation.getlatitude(), myLocation.getLongitude());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
latLng
, 15));
}
and
private LocationRequest mLocationRequest;
private static final long INTERVAL = 1000 * 1000;
private static final long FASTEST_INTERVAL = 1000 * 900;
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
this will call onLocationChanged();
Try calling onLocationChanged(), from within getMyLocation()
Firstly check whether you are receiving location coordinates values or not, if receiving try using this one
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
This could be useful for you.