Hide buttons in an activity after a while in android studio - android

I am working on a map application, using android studio.
I have a map activity and I need some buttons on my map, for example zoom in,zoom out,search,...
I want to hide these buttons after a while and show them again onClick.
but I don't know how to do that.
here is my code
MapActivity.java
package com.example.tourismproject;
import android.location.Location;
import android.content.IntentSender;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public static final String TAG = MapsActivity.class.getSimpleName();
/*
* Define a request code to send to Google Play services
* This code is returned in Activity.onActivityResult
*/
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap mMap; // Might be null if Google Play services APK is not available
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private float zoomLevel = 15; //street view
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1000); // 1 second, in milliseconds
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
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();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
//mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location"));
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
}
#Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
and my XML file is :
<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.example.tourismproject.MapsActivity" />

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//hide buttons after 1 sec
yourbutton.setVisibility(false);
}
}, 1000);

someView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(button.getVisibility()==View.VISIBLE){
button.setVisibility(View.GONE);
} else {
button.setVisibility(View.VISIBLE);
}
}
});
Also for better usability you can add some fading animation with something like this:
ObjectAnimator alpha = ObjectAnimator.ofFloat(button, "alpha", 1, 0);
//alpha.setDelay(500);
//alpha.setDuration(1000);
alpha.start();

You can use
#Override
public void onClick(View v) {
button.setVisibility(false);
}
you can use
Thread.sleep(3000);//for three seconds
button.setVisibility(false);
to make it invisible after a while //in this case after three seconds
i hope this is helpful

Related

Why isnt my location logging out in my Android app's onLocationChanged method?

I'm not getting any errors when running my application, but Im also not seeing any log messages. Heres the part of my code that is supposed to be logging the location:
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
Log.i("location", location.toString());
// updateUI();
}
Heres my full class code:
package com.example.haotian.tutorial32;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.text.DateFormat;
import java.util.Date;
public class MapsActivity extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
protected Location mCurrentLocation;
protected String mLastUpdateTime;
protected TextView mLastUpdateTimeTextView;
protected TextView mLatitudeTextView;
protected TextView mLongitudeTextView;
public static final String TAG = "MapsActivity";
public static final int THUMBNAIL = 1;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private Button picButton; //takes user to camera
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();;
createLocationRequest();
buildGoogleApiClient();
picButton = (Button) findViewById(R.id.photobutton);
picButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
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();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(20, 20)).title("EECS397/600"));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
#Override
public void onConnected(Bundle connectionHint) {
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int cause) {
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
Log.i("location", location.toString());
// updateUI();
}
// private void updateUI() {
// mLatitudeTextView.setText(String.valueOf(mCurrentLocation.getLatitude()));
// mLongitudeTextView.setText(String.valueOf(mCurrentLocation.getLongitude()));
// mLastUpdateTimeTextView.setText(mLastUpdateTime);
// }
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
protected void createLocationRequest() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
}
You need to call the connect() method in order for onConnected() to be called, which is where you correctly start location updates.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();;
createLocationRequest();
buildGoogleApiClient();
mGoogleApiClient.connect(); //Add this line!
//................

Error in Google Map API inside Navigation Bar Fragments

I am trying to build an app with Navigation bar and Google Map API in it.
I followed both of these:
http://www.androidhive.info/2015/04/android-getting-started-with-material-design/
http://blog.teamtreehouse.com/beginners-guide-location-android
tutorial and when I put the map tutorial into one of the fragment inside the navigation bar I'm getting these error:
myGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
The error is in the "this" inside the Builder.
This is my complete class code:
package com.clark.androbotics.projectapp;
import android.app.Activity;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapFragment extends Fragment implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public static final String TAG = MapFragment.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleApiClient myGoogleApiClient;
private LocationRequest myLocationRequest;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
public MapFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setUpMapIfNeeded();
myGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
myLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
myGoogleApiClient.connect();
}
#Override
public void onPause() {
super.onPause();
if (myGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(myGoogleApiClient, this);
myGoogleApiClient.disconnect();
}
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link com.google.android.gms.maps.SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
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) getFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
UiSettings mapSettings;
mapSettings = mMap.getUiSettings();
mapSettings.setZoomControlsEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
private void handleNewLocation(Location myLocation) {
double currentLatitude = myLocation.getLatitude();
double currentLongitude = myLocation.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions().position(latLng).title("I am here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onConnected(Bundle bundle) {
Location myLocation = LocationServices.FusedLocationApi.getLastLocation(myGoogleApiClient);
if (myLocation == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(myGoogleApiClient, myLocationRequest, this);
}
else {
handleNewLocation(myLocation);
};
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
}
I believe I added the necessary imports, but I can't seem to fix it.
I'm new to Android Development, so I'm not really quite sure what seems to be the problem.
EDIT: The app runs but force closed whenever I go to this fragment.
Seems like there's an error about null object reference.
Here's my logcat:
05-08 15:42:20.468 24080-24080/com.clark.androbotics.projectapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.clark.androbotics.projectapp, PID: 24080
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.SupportMapFragment.getMap()' on a null object reference
at com.clark.androbotics.projectapp.MapFragment.setUpMapIfNeeded(MapFragment.java:108)
at com.clark.androbotics.projectapp.MapFragment.onCreate(MapFragment.java:46)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1763)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:915)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:456)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5293)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
I've believe it was something about .getMap on the fragment, but I'm not sure. Also I've tried putting it in the OnCreateView, but I still have the same error.
Any help is very much appreciated.
The GoogleApiClient.Builder constructor takes a Context such as an Activity, Service, etc, but you are passing this which in this case is a Fragment (which doesn't extend Context).
Instead, you pass in getActivity(), which returns the Activity the fragment is currently attached to:
myGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();

How can my android app draw a line or tracks of my movements with gps on google map

I'm developing an android app that can trace the users locations and movements, using GPS and draw and save a line or the tracks that can be sent to a receiver who can open and see the saved tracks on Google map.
I already have a working code that can send the location but the receiver can only see the single position where the user sent from with a marker.
But I want it to track the movement and send so that the receiver can see all the places the user went when the app was on.
I would be really grateful if anyone can help me with this.
This is the code, #Ranjith or if anyone can help me detect the problem here. My tracks/lines are still not drawing
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.StreetViewPanorama;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
GoogleMap.OnMyLocationButtonClickListener,
OnMapReadyCallback {
/**
* The desired interval for location updates. Inexact. Updates may be more or less frequent.
*/
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
/**
* The fastest rate for active location updates. Exact. Updates will never be more frequent
* than this value.
*/
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
UPDATE_INTERVAL_IN_MILLISECONDS / 2;
// Keys for storing activity state in the Bundle.
protected final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
protected final static String LOCATION_KEY = "location-key";
protected final static String LAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key";
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private Location mCurrentLocation;
/**
* Tracks the status of the location updates request. Value changes when the user presses the
* Start Updates and Stop Updates buttons.
*/
protected Boolean mRequestingLocationUpdates;
protected Button mStartUpdatesButton;
protected Button mStopUpdatesButton;
protected Button mSendPositionButton;
protected TextView mLastUpdateTimeTextView;
protected TextView mLatitudeTextView;
protected TextView mLongitudeTextView;
/**
* Stores parameters for requests to the FusedLocationProviderApi.
*/
protected LocationRequest mLocationRequest;
/**
* Time when the location was updated represented as a String.
*/
protected String mLastUpdateTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Locate the UI widgets.
mStartUpdatesButton = (Button) findViewById(R.id.start_updates_button);
mStopUpdatesButton = (Button) findViewById(R.id.stop_updates_button);
mSendPositionButton = (Button) findViewById(R.id.send_position_button);
mLatitudeTextView = (TextView) findViewById(R.id.latitude_text);
mLongitudeTextView = (TextView) findViewById(R.id.longitude_text);
mLastUpdateTimeTextView = (TextView) findViewById(R.id.last_update_time_text);
mRequestingLocationUpdates = false;
mLastUpdateTime = "";
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mMap = mapFragment.getMap();
// Update values using data stored in the Bundle.
updateValuesFromBundle(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
createLocationRequest();
}
#Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
#Override
public void onPause() {
super.onPause();
mGoogleApiClient.disconnect();
}
#Override
public void onMapReady(GoogleMap map) {
map.setMyLocationEnabled(true);
map.setOnMyLocationButtonClickListener(this);
}
/**
* Implementation of {#link LocationListener}.
*/
#Override
public void onLocationChanged(Location location) {
/**
if (location.distanceTo(mCurrentLocation) > 10)
mMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(),
location.getLongitude())).title("Marker"));
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
Toast.makeText(this, getResources().getString(R.string.location_updated_message),
Toast.LENGTH_SHORT).show();
*/
}
public void handleGetDirectionsResult(ArrayList<LatLng> directionPoints) {
PolylineOptions rectLine = new PolylineOptions().width(15).color(Color.RED);
Polyline routePolyline = null;
for (int i = 0; i < directionPoints.size(); i++) {
rectLine.add(directionPoints.get(i));
}
if (routePolyline != null){
routePolyline.remove();
}
routePolyline = mMap.addPolyline(rectLine);
}
#Override
public void onConnected(Bundle connectionHint) {
if (mCurrentLocation == null) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
}
updateUI();
}
#Override
public void onConnectionSuspended(int cause) {
// Do nothing
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Do nothing
}
#Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, mCurrentLocation.toString(), Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
/**
* Sets up the location request. Android has two location request settings:
* {#code ACCESS_COARSE_LOCATION} and {#code ACCESS_FINE_LOCATION}. These settings control
* the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in
* the AndroidManifest.xml.
* <p/>
* When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update
* interval (5 seconds), the Fused Location Provider API returns location updates that are
* accurate to within a few feet.
* <p/>
* These settings are appropriate for mapping applications that show real-time location
* updates.
*/
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
// Sets the desired interval for active location updates. This interval is
// inexact. You may not receive updates at all if no location sources are available, or
// you may receive them slower than requested. You may also receive updates faster than
// requested if other applications are requesting location at a faster interval.
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
// Sets the fastest rate for active location updates. This interval is exact, and your
// application will never receive updates faster than this value.
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
public void sendPositionButtonHandler(View view)
{
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "http://maps.google.com/?q=" +
mCurrentLocation.getLatitude() + "," + mCurrentLocation.getLongitude());
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
/**
* Handles the Start Updates button and requests start of location updates. Does nothing if
* updates have already been requested.
*/
public void startUpdatesButtonHandler(View view) {
if (!mRequestingLocationUpdates) {
mRequestingLocationUpdates = true;
setButtonsEnabledState();
startLocationUpdates();
}
}
/**
* Handles the Stop Updates button, and requests removal of location updates. Does nothing if
* updates were not previously requested.
*/
public void stopUpdatesButtonHandler(View view) {
if (mRequestingLocationUpdates) {
mRequestingLocationUpdates = false;
setButtonsEnabledState();
stopLocationUpdates();
}
}
/**
* Ensures that only one button is enabled at any time. The Start Updates button is enabled
* if the user is not requesting location updates. The Stop Updates button is enabled if the
* user is requesting location updates.
*/
private void setButtonsEnabledState() {
if (mRequestingLocationUpdates) {
mStartUpdatesButton.setEnabled(false);
mStopUpdatesButton.setEnabled(true);
} else {
mStartUpdatesButton.setEnabled(true);
mStopUpdatesButton.setEnabled(false);
}
}
/**
* Requests location updates from the FusedLocationApi.
*/
protected void startLocationUpdates() {
// The final argument to {#code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
/**
* Removes location updates from the FusedLocationApi.
*/
protected void stopLocationUpdates() {
// It is a good practice to remove location requests when the activity is in a paused or
// stopped state. Doing so helps battery performance and is especially
// recommended in applications that request frequent location updates.
// The final argument to {#code requestLocationUpdates()} is a LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
/**
* Updates the latitude, the longitude, and the last location time in the UI.
*/
private void updateUI() {
if (mCurrentLocation != null) {
mLatitudeTextView.setText(String.valueOf(mCurrentLocation.getLatitude()));
mLongitudeTextView.setText(String.valueOf(mCurrentLocation.getLongitude()));
mLastUpdateTimeTextView.setText(mLastUpdateTime);
mMap.addMarker(new MarkerOptions().position(new LatLng(mCurrentLocation.getLatitude(),
mCurrentLocation.getLongitude())).title("Marker"));
}
}
/**
* Updates fields based on data stored in the bundle.
*
* #param savedInstanceState The activity state saved in the Bundle.
*/
private void updateValuesFromBundle(Bundle savedInstanceState) {
if (savedInstanceState != null) {
// Update the value of mRequestingLocationUpdates from the Bundle, and make sure that
// the Start Updates and Stop Updates buttons are correctly enabled or disabled.
if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY)) {
mRequestingLocationUpdates = savedInstanceState.getBoolean(
REQUESTING_LOCATION_UPDATES_KEY);
setButtonsEnabledState();
}
// Update the value of mCurrentLocation from the Bundle and update the UI to show the
// correct latitude and longitude.
if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
// Since LOCATION_KEY was found in the Bundle, we can be sure that mCurrentLocation
// is not null.
mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
}
// Update the value of mLastUpdateTime from the Bundle and update the UI.
if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) {
mLastUpdateTime = savedInstanceState.getString(LAST_UPDATED_TIME_STRING_KEY);
}
updateUI();
}
}
}
Refer the PolylineOptions in developer document,
https://developers.google.com/android/reference/com/google/android/gms/maps/model/PolylineOptions
Here is sample code,
If you pass the list of LatLng values, you can draw a line on the map.
public void handleGetDirectionsResult(ArrayList<LatLng> directionPoints) {
PolylineOptions rectLine = new PolylineOptions().width(15).color(Color.RED); //red color line & size=15
Polyline routePolyline;
for (int i = 0; i < directionPoints.size(); i++) {
rectLine.add(directionPoints.get(i));
}
//clear the old line
if (routePolyline != null) {
routePolyline.remove();
}
// mMap is the Map Object
routePolyline = mMap.addPolyline(rectLine);
}

Displaying google map in android app with specified options

I'm new to android development and I had been trying to display a map in my application for some time now. I finally managed to do it but I want to display it with some specified options such as zoom level, location, etc but its proving difficult.
The following is my .xml file
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
And the following is my .java file
package com.fourapps.cabkonnect;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import android.location.Location;
import android.graphics.Color;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
/**
* Created by nanakay on 6/6/13.
*/
public class Home extends FragmentActivity {
GoogleMap map;
private static final LatLng GOLDEN_GATE_BRIDGE = new LatLng(37.828891,-122.485884);
private static final LatLng APPLE = new LatLng(37.3325004578, -122.03099823);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if (map == null) {
Toast.makeText(this, "Google maps not available", Toast.LENGTH_LONG).show();
}
}
}
The map is displaying but I would want to display it with my own options.
I would be very happy if someone could help. Thanks
First have to obtain the current location:
private Location mCurrentLocation;
mCurrentLocation = mLocationClient.getLastLocation();
Read here to know more.
And then you can animate to the location using:
LatLng myLaLn = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
CameraPosition camPos = new CameraPosition.Builder().target(myLaLn)
.zoom(15)
.bearing(45)
.tilt(70)
.build();
CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
map.animateCamera(camUpd3);
I give you a simple but complete example to show a map and the current location:
public class MainActivity extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private LocationClient mLocationClient;
private Location mCurrentLocation;
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
setUpLocationClientIfNeeded();
mLocationClient.connect();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the
// map.
if (map == null) {
// Try to obtain the map from the SupportMapFragment.
map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (map == null) {
Toast.makeText(this, "Google maps not available",
Toast.LENGTH_LONG).show();
}
}
}
private void setUpLocationClientIfNeeded() {
if (mLocationClient == null) {
Toast.makeText(getApplicationContext(), "Waiting for location",
Toast.LENGTH_SHORT).show();
mLocationClient = new LocationClient(getApplicationContext(), this, // ConnectionCallbacks
this); // OnConnectionFailedListener
}
}
#Override
public void onPause() {
super.onPause();
if (mLocationClient != null) {
mLocationClient.disconnect();
}
}
/*
* Called by Location Services when the request to connect the client
* finishes successfully. At this point, you can request the current
* location or start periodic updates
*/
#Override
public void onConnected(Bundle dataBundle) {
mCurrentLocation = mLocationClient.getLastLocation();
if (mCurrentLocation != null) {
Toast.makeText(getApplicationContext(), "Found!",
Toast.LENGTH_SHORT).show();
centerInLoc();
}
}
private void centerInLoc() {
LatLng myLaLn = new LatLng(mCurrentLocation.getLatitude(),
mCurrentLocation.getLongitude());
CameraPosition camPos = new CameraPosition.Builder().target(myLaLn)
.zoom(15).bearing(45).tilt(70).build();
CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
map.animateCamera(camUpd3);
MarkerOptions markerOpts = new MarkerOptions().position(myLaLn).title(
"my Location");
map.addMarker(markerOpts);
}
/*
* Called by Location Services if the connection to the location client
* drops because of an error.
*/
#Override
public void onDisconnected() {
// Display the connection status
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
/*
* Called by Location Services if the attempt to Location Services fails.
*/
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects. If the error
* has a resolution, try sending an Intent to start a Google Play
* services activity that can resolve error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available
*/
Log.e("Home", Integer.toString(connectionResult.getErrorCode()));
}
}
}
Note1: I omitted the "Check for Google Play Services" part by simplicity but it should be added as a good practice.
Note2: You need the google-play-services_lib project and reference it from yours.
You can find all information about interacting with google maps in android here
From the google maps documentation referenced above, just some examples:
Zoom controls:
The Maps API provides built-in zoom controls that appear in the bottom right hand corner of the map. These are enabled by default, but can be disabled by calling UiSettings.setZoomControlsEnabled(boolean).
My Location button:
The My Location button appears in the top right corner of the screen only when the My Location layer is enabled. When a user clicks the button, the camera animates to focus on the user's current location if the user's location is currently known. A click will also trigger the GoogleMap.OnMyLocationButtonClickListener. You can disable the button from appearing altogether by calling UiSettings.setMyLocationButtonEnabled(boolean).
Add a marker:
The below example demonstrates how to add a marker to a map. The marker is created at coordinates 0,0, and displays the string "Hello world" in an infowindow when clicked.
private GoogleMap mMap;
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Hello world"));

google maps V2 my location issue

I put the following code inside a new class I created (I hope I did the right thing by creating a new class). I am trying to get the current location of the user to show up on my map. The one problem that is showing up is that it is saying that "basic_map" is not a valid field. All that I have right now is just the map itself. I hope someone can help me.
ps.. Sorry about how the code looks on here. I can't seem to get it fixed to look like real code all the way.
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
public class mylocation extends FragmentActivity implements LocationListener, LocationSource
{
/**
* Note that this may be null if the Google Play services APK is not available.
*/
private GoogleMap mMap;
private OnLocationChangedListener mListener;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_map);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if(locationManager != null)
{
boolean gpsIsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean networkIsEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(gpsIsEnabled)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L, 10F, this);
}
else if(networkIsEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000L, 10F, this);
}
else
{
//Show an error dialog that GPS is disabled.
}
}
else
{
//Show a generic error dialog since LocationManager is null for some reason
}
setUpMapIfNeeded();
}
#Override
public void onPause()
{
if(locationManager != null)
{
locationManager.removeUpdates(this);
}
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
setUpMapIfNeeded();
if(locationManager != null)
{
mMap.setMyLocationEnabled(true);
}
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView
* MapView}) will show a prompt for the user to install/update the Google Play services APK on
* their device.
* <p>
* A user can return to this Activity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the Activity may not have been
* completely destroyed during this process (it is likely that it would only be stopped or
* paused), {#link #onCreate(Bundle)} may not be called again so we should call this method in
* {#link #onResume()} to guarantee that it will be called.
*/
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();
}
//This is how you register the LocationSource
mMap.setLocationSource(this);
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap()
{
mMap.setMyLocationEnabled(true);
}
#Override
public void activate(OnLocationChangedListener listener)
{
mListener = listener;
}
#Override
public void deactivate()
{
mListener = null;
}
#Override
public void onLocationChanged(Location location)
{
if( mListener != null )
{
mListener.onLocationChanged( location );
//Move the camera to the user's location once it's available!
mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
}
}
#Override
public void onProviderDisabled(String provider)
{
// TODO Auto-generated method stub
Toast.makeText(this, "provider disabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider)
{
// TODO Auto-generated method stub
Toast.makeText(this, "provider enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
// TODO Auto-generated method stub
Toast.makeText(this, "status changed", Toast.LENGTH_SHORT).show();
}
}
Try this:
setContentView(R.layout.basic_map);
Set map:
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
Layout: basic_map.xml
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_below="#id/lltop"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />

Categories

Resources