I'm trying to get Google maps to start on the users current location. Right now it starts zoomed all the way out. I have the correct code for finding and animating the camera to the user's location but this code only works if I put it in a button and touch it on my own. How can I get it to move at the start of the activity?
I've been trying a lot of different things. this was one of them.
public class FindBar extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener, LocationListener,
OnMyLocationButtonClickListener {
private GoogleMap mMap;
private LocationClient mLocationClient;
// Button test;
boolean locationClientConnected = false;
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
setUpMapIfNeeded();
setUpLocationClientIfNeeded();
mLocationClient.connect();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (mLocationClient != null) {
mLocationClient.disconnect();
Log.d("tag", "locationclient disconnected");
}
}
private void setUpMapIfNeeded() {
Log.d("tag", "entered set up map");
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this);
Log.d("tag", "map location set true and click listener set");
}
}
private void setUpLocationClientIfNeeded() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(getApplicationContext(), this, // ConnectionCallbacks
this); // OnConnectionFailedListener
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// removes the title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.fragment_find_bar);
// Get a handle to the Map Fragment
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
// test = (Button) findViewById(R.id.bTest);
// test.setOnClickListener(new OnClickListener() {
//
// #Override
// public void onClick(View v) {
// // TODO Auto-generated method stub
// moveCameraTo(mMap.getMyLocation());
// }
//
// });
moveCameraTo(mLocationClient.getLastLocation());
}
// Takes a Location and centers camera on that location
public void moveCameraTo(Location mLocation) {
Log.d("camera", "entered moveToCamera");
LatLng camPos = new LatLng(mLocation.getLatitude(),
mLocation.getLongitude());
Log.d("camera", "created camera position");
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(camPos, 15));
Log.d("camera", "moved camera");
}
#Override
public boolean onMyLocationButtonClick() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle connectionHint) {
// TODO Auto-generated method stub
Log.d("camera", "entered onConnected");
// moveCameraTo(mMap.getMyLocation());
locationClientConnected = true;
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
}
this code comes pretty much out of the samples. If you get a non null location from getLastLocation() then plug that location into your setupmap method.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
// mMap = mMapFragment.getMap();
// // Check if we were successful in obtaining the map.
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
// use the settings maptype
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
// Start Parsing the map
}
}
private void setUpMap() {
final View mapView = getSupportFragmentManager().findFragmentById(
R.id.map).getView();
if (mapView.getViewTreeObserver().isAlive()) {
mapView.getViewTreeObserver().addOnGlobalLayoutListener(
new OnGlobalLayoutListener() {
#SuppressWarnings("deprecation")
// We use the new method when supported
#SuppressLint("NewApi")
// We check which build version we are using.
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
mapView.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
} else {
mapView.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
}
//
// put your move code here replacing code below
// which moves the map.
//
if (currentCameraPosition != null) {
mMap.moveCamera(CameraUpdateFactory
.newCameraPosition(currentCameraPosition));
} else {
// else move to bounds of the map
if (bounds != null) {
mMap.moveCamera(CameraUpdateFactory
.newLatLngBounds(bounds, 50));
}
}
}
});
}
}
Related
I am trying to get users current location using FusedLocationApi using the following code. I am following the guide provided here https://developer.android.com/training/location/retrieve-current.html
public class MapActivity extends ActionBarActivity implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,LocationListener {
private Toolbar mToolbar;
private GoogleMap googleMap;
GoogleApiClient mGoogleApiClient;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST =5000;
private Location mLastLocation;
private LocationRequest mLocationRequest;
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mToolbar = (Toolbar)findViewById( R.id.toolbar );
mToolbar.setTitle(R.string.title_activity_map);
setSupportActionBar(mToolbar);
try {
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
if (checkPlayServices()) {
buildGoogleApiClient();
}
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000);
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
googleMap.setMyLocationEnabled(true);
}
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
checkPlayServices();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
if (arg0.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
arg0.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Log.e("Fail", "Location services connection failed with code " + arg0.getErrorCode());
}
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
new GetLocation().execute();
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
private class GetLocation extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
Log.e("If", "If");
} else {
Log.e("else", "else");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
}
When I run the code it always shows else in log, this means that I am not getting any Location. Is there something missing? what am I doing wrong?
Moved from comments:
make sure you have gps enabled on your phone. When enabling gps, phone may also ask you to send data anonymously to google, you should accept it.
Fatal Exception: java.lang.RuntimeException
Unable to destroy activity : java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
problem is Samsung SM G355H and micromax A106
Here is my code
public class EnRouteFragment extends Fragment implements LocationListener{
View rootView;
LayoutInflater inflater;
ViewGroup container;
Context context;
private GoogleMap googleMap;
// flag for GPS status
boolean isGPSEnabled = false;
boolean canGetLocation = false;
// flag for network status
boolean isNetworkEnabled = false;
Location location; // location
Double dblIntLat=null; // latitude
Double dblIntLog=null; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 0; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
MarkerOptions dynamicMarker;
Marker markerCurre;
public EnRouteFragment()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
// TODO Auto-generated method stub
this.inflater = inflater;
this.container = container;
initializeVariables();
initializeUIVariables();
initializeListeners();
attachEventListeners();
return rootView;
}
#Override
public void initializeVariables() {
// TODO Auto-generated method stub
context=getActivity();
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null)
parent.removeView(rootView);
}
try {
rootView = inflater.inflate(R.layout.fragment_enroute_marchent, container, false);
} catch (InflateException e) {
/* map is already there, just return view as it is */
}
}
#Override
public void initializeUIVariables() {
// TODO Auto-generated method stub
}
#Override
public void initializeListeners() {
// TODO Auto-generated method stub
}
#Override
public void attachEventListeners() {
// TODO Auto-generated method stub
}
// ------------------------------------fetch lat long from GPS OR NETWORK provider-------
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
dblIntLat = location.getLatitude();
dblIntLog = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
dblIntLat = location.getLatitude();
dblIntLog = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
// -----------------------------------------end---------------
// --------------------------------------initialize google map---------------
private void initilizeMap() {
if (googleMap == null) {
System.out.println("--------- initilizeMap() if");
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.enroute_map)).getMap();
googleMap.setMyLocationEnabled(true);
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.getUiSettings().setRotateGesturesEnabled(false);
googleMap.getUiSettings().setZoomControlsEnabled(true);
if(dblIntLat!=null && dblIntLog !=null)
{
markerCurre = googleMap.addMarker(new MarkerOptions().position(
new LatLng(dblIntLat, dblIntLog)).icon(BitmapDescriptorFactory.fromResource(R.drawable.bike)));
}
if(dblIntLat!=null && dblIntLog !=null)
{
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dblIntLat,dblIntLog) , 12.0f) );
}
if (googleMap == null) {
Toast.makeText(context,
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
else
{
System.out.println("--------- initilizeMap() else");
if(markerCurre!=null)
{
markerCurre.remove();
}
if(dblIntLat!=null && dblIntLog !=null)
{
markerCurre = googleMap.addMarker(new MarkerOptions().position(
new LatLng(dblIntLat, dblIntLog)).icon(BitmapDescriptorFactory.fromResource(R.drawable.bike)));
}
}
}
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
dblIntLat = loc.getLatitude();
dblIntLog = loc.getLongitude();
initilizeMap();
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
Fragment fragment = getFragmentManager().findFragmentById(R.id.enroute_map);
if(fragment!=null)
{
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commitAllowingStateLoss();
}
}
#Override
public void onPause() {
super.onPause();
if(locationManager!=null)
{
locationManager.removeUpdates(this);
}
}
#Override
public void onResume() {
super.onResume();
getLocation();
}
#Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
//super.onSaveInstanceState(outState);
}
}
here is the error log cat
java.lang.RuntimeException: Unable to destroy activity : java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3733)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3751)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3951)
at android.app.ActivityThread.access$1000(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1287)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5511)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(NativeStart.java)
Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1323)
at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1341)
at android.app.BackStackRecord.commitInternal(BackStackRecord.java:597)
at android.app.BackStackRecord.commit(BackStackRecord.java:575)
at com.matrix.hungerz.EnRouteFragment.onDestroyView(EnRouteFragment.java:744)
at android.app.Fragment.performDestroyView(Fragment.java:1898)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:954)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1044)
at android.app.FragmentManagerImpl.dispatchDestroy(FragmentManager.java:1887)
at android.app.Activity.performDestroy(Activity.java:5493)
at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1123)
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3720)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3751)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3951)
at android.app.ActivityThread.access$1000(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1287)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5511)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(NativeStart.java)
This logcat error doesn't correspond to the code you've provided.
Note this line in the logcat:
android.app.BackStackRecord.commit(BackStackRecord.java:575)
This means that the error was caused by a call to FragmentTransaction.commit(), but your code suggests that you call FragmentTransaction.commitAllowingStateLoss().
I can think of three possible reasons:
You are looking at the wrong part of the code
You previously had commit() in place of commitAllowingStateLoss(), and the errors happen on the older version of your app
Your code has been run on a custom ROM that screwed up parts of AOSP code (see below).
The relevant parts of AOSP code:
From BackStackRecord:
public int commit() {
return commitInternal(false);
}
public int commitAllowingStateLoss() {
return commitInternal(true);
}
int commitInternal(boolean allowStateLoss) {
if (mCommitted) {
throw new IllegalStateException("commit already called");
}
...
mManager.enqueueAction(this, allowStateLoss);
return mIndex;
}
From FragmentManagerImpl:
public void enqueueAction(Runnable action, boolean allowStateLoss) {
if (!allowStateLoss) {
checkStateLoss();
}
...
}
private void checkStateLoss() {
if (mStateSaved) {
throw new IllegalStateException(
"Can not perform this action after onSaveInstanceState");
}
if (mNoTransactionsBecause != null) {
throw new IllegalStateException(
"Can not perform this action inside of " + mNoTransactionsBecause);
}
}
This is my code i want to plot multiple marker in google map
when i write mapview.getoverlay().add(overlaymarker) it is not working
i am not use MapActivity i use fragment so this is not supported getoverlays() please help me.......
fragmnt1.java
public class one extends Fragment implements LocationListener {
MapView mapView;
GoogleMap googleMap;
private boolean mapsSupported = true;
Location location;
double latitude; // latitude
double longitude;
LatLng latlang;
LocationManager manager;
Overlay_Marker overmarker;
frag provider;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final RelativeLayout parent = (RelativeLayout) inflater.inflate(R.layout.one, container, false);
mapView = (MapView) parent.findViewById(R.id.map);
provider=new frag(getActivity());
Log.d("spn", "oncreate view");
return parent;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
MapsInitializer.initialize(getActivity());
} catch (Exception ex) {
mapsSupported = false;
}
if (mapView != null) {
mapView.onCreate(savedInstanceState);
}
initializeMap();
Log.d("spn", "onactivity created");
}
private void initializeMap() {
if (googleMap == null && mapsSupported) {
mapView = (MapView) getActivity().findViewById(R.id.map);
googleMap = mapView.getMap();
Drawable dmarker=getResources().getDrawable(R.drawable.ic_launcher);
dmarker.setBounds(0, 0, dmarker.getIntrinsicWidth(), dmarker.getIntrinsicHeight());
overmarker=new Overlay_Marker(dmarker,getActivity());
Drawable windmill = getResources().getDrawable(R.drawable.ic_launcher);
Drawable bigBen = getResources().getDrawable(R.drawable.ic_launcher);
Drawable eiffelTower = getResources().getDrawable(R.drawable.ic_launcher);
overmarker.addOverlayItem(52372991, 4892655, "Amsterdam", windmill);
overmarker.addOverlayItem(51501851, -140623, "London", bigBen);
overmarker.addOverlayItem(48857522, 2294496, "Paris", eiffelTower);
//List<Overlay_Marker> temp = (List<Overlay_Marker>) mapView.getOverlay();
// temp.add(overmarker);
mapView.getOverlay().add(overmarker); /// Not working
GetLongitude_Latitude();
}
}
public void GetLongitude_Latitude()
{
manager=(LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
location=provider.getLocation(LocationManager.NETWORK_PROVIDER);
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
String provider = manager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// Get the location from the given provider
Location location = manager.getLastKnownLocation(provider);
manager.requestLocationUpdates(provider, 20000, 1, this);
if(location!=null)
onLocationChanged(location);
// Toast.makeText(getActivity(), "Location retrieved"+location.getLatitude()+" and "+location.getLongitude(), Toast.LENGTH_SHORT).show();
//else
// Toast.makeText(getActivity(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "No Provider Found", Toast.LENGTH_SHORT).show();
}
Log.d("spn", "location"+location);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
initializeMap();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onLocationChanged(Location location) {
latitude=location.getLatitude();
longitude=location.getLongitude();
latlang=new LatLng(latitude, longitude);
MarkerOptions marker=new MarkerOptions().position(latlang);
googleMap.addMarker(marker);
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder().target(
latlang).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
I have a problem with the SupportMapFragment and moving the camera to a location on the map.
public class MapPositionFragment extends SupportMapFragment implements LocationListener{
private GoogleMap map = null;
private Button lockButton = null;
private Location currentLocation = null;
private LocationManager locationManager = null;
private View mapView = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mapView = super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.fragment_route_map, container, false);
SetUpMap(v);
return v;
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
if (isVisibleToUser){
SetUpLocationService();
}
}
private void SetUpLockButton(){
lockButton = (Button)getActivity().findViewById(R.id.lock_screen_button);
lockButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ToggleLockButton();
}
});
}
private void ToggleLockButton(){
BaseSwipeActivity baseActivity = (BaseSwipeActivity)getActivity();
boolean swipeEnabled = baseActivity.TogglePaging();
if (swipeEnabled){
lockButton.setBackgroundResource(R.drawable.stock_lock_open);
}
else{
lockButton.setBackgroundResource(R.drawable.stock_lock);
}
}
private void SetUpLocationService(){
boolean gpsIsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean networkIsEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (networkIsEnabled){
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
} else if (gpsIsEnabled){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
private void SetCurrentLocation(final Location location){
if (map != null){
getActivity().runOnUiThread(new Runnable() {
public void run() {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.moveCamera(cameraUpdate);
}
});
}
}
private void SetUpMap(View view) {
if (map == null){
getActivity().runOnUiThread(new Runnable() {
public void run() {
map = getMap();
map.getUiSettings().setMyLocationButtonEnabled(true);
map.setIndoorEnabled(true);
map.getUiSettings().setZoomControlsEnabled(false);
locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
}
});
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
SetUpLockButton();
}
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
SetCurrentLocation(location);
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
It's SupportMapFragment which is positioned inside a ViewPager. The map is shown, but I cannot change the map settings and i'm not able to change the camera position. I thought maybe because it's in a other thread I have to use the UI Thread, but that doesn't change anything.
So maybe someone has an idea, it would be great!
thx Manuel
I encountered the same problem today. Here's my solution for it.
As you had:
// # SetUpMap()
map = getMap();
Replace it with:
// Remeber to change the map id (R.id.map) to what you have in the layout .xml
map = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
Seems like this solution doesn't work with Android support library 21.0.x (I have tested for .2 and .3). As this method works with older Android support libraries there might be a bug etc.
I am trying to get GPS data without using map view.The code that I have below is from O'Rielly's Programming Android book and is supposed to work but is not. I am using an Android 2.2.1 phone and the app closes immediately after it starts.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvLattitude = (TextView) findViewById(R.id.tvLattitude);
tvLongitude = (TextView) findViewById(R.id.tvLongitude);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
tvLattitude.setText(Double.toString(loc.getLatitude()));
tvLongitude.setText(Double.toString(loc.getLongitude()));
locListenD = new DispLocListener();
lm.requestLocationUpdates("gps", 30000L, 10.0f, locListenD);}
private class DispLocListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
tvLattitude.setText(Double.toString(location.getLatitude()));
tvLongitude.setText(Double.toString(location.getLongitude()));}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
lm.removeUpdates(locListenD);}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
lm.requestLocationUpdates("gps", 30000L, 10.0f, locListenD);}
Perhaps you need to add the permissions
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
to your manifest?
Well, I set up a similar project and found a problem with your code: in onCreate you immediately try to set the location from previous locations (which on first run obviously wouldn't be available). I erased those lines and the code seems to run fine
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvLattitude = (TextView) findViewById(R.id.tvLattitude);
tvLongitude = (TextView) findViewById(R.id.tvLongitude);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locListenD = new DispLocListener();
lm.requestLocationUpdates("gps", 30000L, 10.0f, locListenD);
}
private LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateNearestLocation(location);
}
private boolean updateNearestLocation(Location lastKnownLocation) {
String locationProvider = LocationManager.NETWORK_PROVIDER;
LocationManager m_locationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
try {
m_locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} catch (IllegalArgumentException iae) {
Log.i(TAG, "Could not find a location provider");
return false;
}
if (lastKnownLocation == null) {
lastKnownLocation = m_locationManager
.getLastKnownLocation(locationProvider);
} else {
m_locationManager.removeUpdates(locationListener);
}
if (lastKnownLocation != null) {
lastKnownLocation.getLatitude();
lastKnownLocation.getLongitude();
}
}
Perhaps you need to turn on the locations in your phone's settings:
Settings --> Location and Security --> My Location
Also if you are using an emulator keep in mind it won't generate location data unless you do it manually through the DDMS.