Android Google Maps API V2 not zooming to Location - android

Im not sure whats wrong but Im trying to get my google maps fragment to zoom in to a particular location on start. For some reason, it is not working and still zooms in to africa by default. Here is my code.
public class OutbreakMap extends Activity implements LocationListener {
double lat=50;
double longi=50;
private LocationManager locationManager;
private String provider;
private MapFragment mMapFragment;
private GoogleMap googleMap;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Check if enabled and if not send user to the GSP settings
// Better solution would be to display a dialog and suggesting to
// go to the settings
if (!enabled) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set title
alertDialogBuilder.setTitle("Turn On Your GPS");
// set dialog message
alertDialogBuilder
.setMessage("Please turn on your GPS to track sickness in your area!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
OutbreakMap.this.finish();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
Toast.makeText(getApplicationContext(),"Location not found",Toast.LENGTH_SHORT);
}
mMapFragment = MapFragment.newInstance();
FragmentTransaction fragmentTransaction =
getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.map, mMapFragment);
fragmentTransaction.commit();
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
setUpMapIfNeeded();
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
if(location != null) {
lat=location.getLatitude();
longi=location.getLongitude();
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(lat,longi)) // Sets the center of the map to Mountain View
.zoom(17) // Sets the zoom
// Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
UiSettings uiSettings=googleMap.getUiSettings();
uiSettings.setAllGesturesEnabled(false);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
Toast.makeText(getApplicationContext(),"Couldn't Find Location",Toast.LENGTH_SHORT);
}
ParseGeoPoint userLoc= new ParseGeoPoint(lat,longi);
ParseQuery query= new ParseQuery("Outbreak");
query.whereWithinMiles("location",userLoc,1);
query.findInBackground(new FindCallback() {
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
GetOutbreaks.getOutBreaksNearMe(googleMap,lat,longi,objects);
Toast.makeText(getApplicationContext(),"Recieved Outbreak Data",Toast.LENGTH_SHORT);
} else {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Could Not Download Data",Toast.LENGTH_SHORT);
}
}
});
// moveToPrescription();
// moveToPrescription();
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void moveToPrescription(){
Intent intent = new Intent(this,Prescription.class);
startActivity(intent);
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (googleMap != null) {
// The Map is verified. It is now safe to manipulate the map.
}
}
}
}
Also, here is my xml layout for the map fragment activity
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
</LinearLayout>
And my Android manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.parse.starter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15"/>
<permission
android:name="com.example.mapdemo.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.mapdemo.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<!-- 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"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
android:name="ParseApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".ParseStarterProjectActivity"
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=".Register"/>
<activity android:name=".Login"/>
<activity android:name=".Home"/>
<activity android:name=".OutbreakMap"/>
<activity android:name=".Prescription"/>
<activity android:name=".MyPrescriptions"/>
<receiver android:name=".AlarmManagerBroadcastReceiver"></receiver>
<uses-library android:name="com.google.android.maps"/>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="My Maps API Key is Here"/>
</application>
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
</manifest>
The LogCat is not showing any errors. Thanks for the help!

You are adding second SupportMapFragment in code on top of Fragment having GoogleMap you interact with. Just remove unnecessary code.

Use SupportMapFragment
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
/>
GoogleMap gm;
gm = ((SupportMapFragment(getSupportFragmentManager().findFragmentById(R.id.map))).getMap();

Comment out the following lines of code
mMapFragment = MapFragment.newInstance();
FragmentTransaction fragmentTransaction =
getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.map, mMapFragment);
fragmentTransaction.commit();
and its going to work like a charm.

Related

Current Location in Map fragment Android Studio

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.

Unable to view map using mapView in android studio

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

Based On Co-ordinates show location on MAP in android

I have made an app which gives you current latitude and longitude using GPS service.
Now i plan to show location on MAP based on this co-ordinates
I want to create 2 activities. 1st already created in which i am showing latitude and longitude in TextView. in 2nd activity i want to display map in which location will be displayed. to go from one activity to another i will use a button in 1st activity.
here is my code (Not Full)
protected LocationManager locMan;
protected LocationListener locLis;
protected Context contex;
TextView txtview;
String lat,provider;
protected String latitude,longtitude;
protected boolean gps_enable,network_enable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F44336")));
txtview = (TextView)findViewById(R.id.locView);
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location loc){
txtview = (TextView)findViewById(R.id.locView);
txtview.setText("Latitude = "+loc.getLatitude()+", Longitude = "+ loc.getLongitude());
}
Note :- I have refer javapapers website for my current app
Regards
Create Map Activity and pass the location via bundle or save it in sharedpreference
public class MapActivity extends ActionBarActivity{
private GoogleMap googleMap;
FragmentManager fm;
private Location mLocation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fm = getSupportFragmentManager();
// get location from bundle or sharedprefs
// mLocation = ...
try {
if (googleMap == null) {
googleMap = ((SupportMapFragment) fm.findFragmentById(R.id.map)).getMap();
googleMap.getUiSettings().setZoomGesturesEnabled(true);
}
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
} catch (Exception e) {
e.printStackTrace();
}
MarkerOptions TP = new MarkerOptions().title("title").position(new LatLng(mLocation.getLatitude(), mLocation.getLongitude())).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_map_marker));
googleMap.addMarker(TP);
}}
xml layout for this activity is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
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="match_parent"/>
You need to use MapView and MyLocationOverLay to the map, as Android will handle displaying the user's location for you.
map=(MapView)findViewById(R.id.whatever_your_mapview_id_is);
map.getOverlays().add(new MyLocationOverlay(this, map));
Refer : display google maps using coordinates obtained using gps
You can pass the location to the Maps Activity using a LatLng Object since it's parcelable, see this answer.
Then, you could create a Marker in your MapsActivity, and use the CameraPosition class to move the map view to the specified location.
First, make sure that you have double values with the current location in your existing Activity:
//instance variables:
double lat;
double lon;
Set lat/lon in your onLocationChanged() callback:
#Override
public void onLocationChanged(Location loc){
lat = loc.getLatitude(); //added
lon = loc.getLongitude(); //added
txtview = (TextView)findViewById(R.id.locView);
txtview.setText("Latitude = "+loc.getLatitude()+", Longitude = "+ loc.getLongitude());
}
Create a Button in your layout in your existing Activity, and in the click listener you would create a LatLng object and send it in the Intent to the Maps Activity:
Button b = (Button) findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LatLng fromPostion = new LatLng(lat, lon );
Bundle args = new Bundle();
args.putParcelable("location", fromPostion);
Intent i = new Intent(this, MapsActivity.class);
i.putExtras(args);
startActivity(i);
}
});
Then, in your Maps Activity, you would get the LatLng object in onCreate() from the Bundle:
LatLng latlng; //Create as instance variable
In onCreate():
Bundle b = getIntent().getExtras();
if (b != null){
latlng = (LatLng) b.getParcelable("location");
}
Then, add the Marker at that location and set the camera position and zoom:
private void setUpMap() {
mMap.getUiSettings().setMapToolbarEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.setMyLocationEnabled(true);
MarkerOptions marker = new MarkerOptions().position(latlng).title("My Location");
// Changing marker icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
Marker m = mMap.addMarker(marker);
//move camera position and zoom to specified location
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latlng).zoom(8).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
Your full Maps Activity might look something like this:
public class MapsActivity extends ActionBarActivity implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, OnMapReadyCallback {
private GoogleMap mMap;
LatLng latlng;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
LocationManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Bundle b = getIntent().getExtras();
if (b != null){
latlng = b.getParcelable("location");
}
manager =(LocationManager) getSystemService(Context.LOCATION_SERVICE);
setUpMapIfNeeded();
buildGoogleApiClient();
mGoogleApiClient.connect();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
!manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle("Location is disabled")
.setMessage("Please enable your location")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 100);
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
Log.v("Connection Status", String.valueOf(mGoogleApiClient.isConnected()));
mGoogleApiClient.connect();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == 100) {
Toast.makeText(this, "location enabled", Toast.LENGTH_LONG).show();
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Toast.makeText(this, "location enabled", Toast.LENGTH_LONG).show();
//At least one provider enabled, connect GoogleApiClient
mGoogleApiClient.connect();
}
}
}
#Override
protected void onPause(){
super.onPause();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
protected synchronized void buildGoogleApiClient() {
Toast.makeText(this,"buildGoogleApiClient",Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
Toast.makeText(this,"onConnected", Toast.LENGTH_SHORT).show();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10);
mLocationRequest.setFastestInterval(10);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setSmallestDisplacement(0.1F);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
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();
}
}
}
private void setUpMap() {
mMap.getUiSettings().setMapToolbarEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.setMyLocationEnabled(true);
MarkerOptions marker = new MarkerOptions().position(latlng).title("My Location");
// Changing marker icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
Marker m = mMap.addMarker(marker);
//move camera position and zoom to specified location
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latlng).zoom(8).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
Log.d("locationtesting", "lat: " + location.getLatitude() + " lon: " + location.getLongitude());
}
}
layout xml for MapsActivity:
<fragment 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:id="#+id/map" tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
Note that you will also need to enable Google Maps in the Google Developer Console, and include Google Play Services in your build.gradle file (update version with the version that you are using):
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.1'
compile 'com.google.android.gms:play-services:7.3.0'
}
The last thing is to set up your AndroidManifest.xml for the Google Maps API v2:
permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<!--
The ACCESS_COARSE/FINE_LOCATION 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" />
meta-data tags, make sure they are inside the application tag:
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="Your-API-Key" />

google maps v2 center mylocation

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

Google Maps v2 - Android Studio - OnLocationChanged not being called

First of all, I´ve been searching for an answer for this the whole evening. I have read many of the questions -probably all- asking why OnloCationChanged is not called... nothing helped me.
I have a Fragment that displays a map. I can add markers to it and it also shows the current location of the user correctly. Everything seems to be ok but, I want to zoom in the user´s location and that´s why I need the method "OnLocationChanged" to be called.
Also, locationManager.getLastKnownLocation(provider) returns always null.
I have tested this in a real device.
Here is my configuration, I hope somebody can point me in the right direction.
Thanks
Fragment Class
public class MapMainFragment extends BaseFragment implements LocationListener{
private SupportMapFragment fragment;
private GoogleMap map;
private LocationManager locationManager;
private static final long MIN_TIME = 500;
private static final float MIN_DISTANCE = 0;
String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// LOCATION
locationManager = (LocationManager) mActivity.getSystemService(Context.LOCATION_SERVICE);
boolean enabledGPS = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Check if enabled and if not send user to the GSP settings
if (!enabledGPS && !enabledWiFi) {
Toast.makeText(mActivity, "GPS signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
Toast.makeText(mActivity, "Selected Provider " + provider,
Toast.LENGTH_SHORT).show();
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, MIN_TIME, MIN_DISTANCE, this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.app_tab_b_second_screen, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getChildFragmentManager();
fragment = (SupportMapFragment) fm.findFragmentById(R.id.map);
if (fragment == null) {
fragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map, fragment).commit();
}
}
#Override
public void onResume() {
super.onResume();
map = fragment.getMap();
// Enabling MyLocation Layer of Google Map
map.setMyLocationEnabled(true);
// Add Marker
final LatLng TEST_MARKER = new LatLng(50.34927, 6.26887);
map.addMarker(new MarkerOptions()
.position(TEST_MARKER)
.title("Title")
.snippet("Sheeps: 4,137,400")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
}
#Override
public void onLocationChanged(Location location) {
Log.e("onLocationChanged", "called");
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(mActivity, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(mActivity, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
BaseFragment class
public class BaseFragment extends Fragment {
public AppMainTabActivity mActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = (AppMainTabActivity) this.getActivity();
}
public boolean onBackPressed(){
return false;
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
}
}
Manifest.xml
<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="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
I think in your onlocation change it runs but the you remove the updates and it doesn't run any more
Comment out this line in onlocationchanged
locationManager.removeUpdates(this);
And your getbestprovider method use true instead of false

Categories

Resources