Getting all markers from database to map - android

I have stored places in the database with their Longitude and Latitude, and i want to get the Latlngs for all the places and show them on Google Map v2.
I tried to put a test marker in the OnCreate function, but it dose not work, maybe because i put it in a wrong place ?
Here is my code: (the code works without the part of the add marker):
public class NearbyActivity extends FragmentActivity implements LocationListener,OnInfoWindowClickListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener{
private GoogleMap mMap;
private LocationManager locationManager;
private SupportMapFragment mapFragment;
private GoogleMap map;
private LocationClient mLocationClient;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
// Define a DialogFragment that displays the error dialog
public static class ErrorDialogFragment extends DialogFragment {
// Global field to contain the error dialog
private Dialog mDialog;
// Default constructor. Sets the dialog field to null
public ErrorDialogFragment() {
super();
mDialog = null;
}
// Set the dialog to display
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
// Return a Dialog to the DialogFragment.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby);
mLocationClient = new LocationClient(this, this, this);
mapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
map = mapFragment.getMap();
map.setMyLocationEnabled(true);
// This is working byt with fixed values not from database..
Marker melbourne = map.addMarker(new MarkerOptions()
.position(new LatLng(26.2412591, 50.5961323))
.title("0000")
.snippet("Manama Capital of Arab Tourism")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.palace)));
onInfoWindowClick(melbourne);
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Intent intent = new Intent(NearbyActivity.this,Description.class);
intent.putExtra("id", "klkl");
startActivity(intent);
} });
// end of add marker.
}
#Override
protected void onStart() {
super.onStart();
// Connect the client.
if(isGooglePlayServicesAvailable()){
mLocationClient.connect();
}
}
/*
* Called when the Activity is no longer visible.
*/
#Override
protected void onStop() {
// Disconnecting the client invalidates it.
mLocationClient.disconnect();
super.onStop();
}
/*
* Handle results returned to the FragmentActivity
* by Google Play services
*/
#Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
// Decide what to do based on the original request code
switch (requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST:
/*
* If the result code is Activity.RESULT_OK, try
* to connect again
*/
switch (resultCode) {
case Activity.RESULT_OK:
mLocationClient.connect();
break;
}
}
}
private boolean isGooglePlayServicesAvailable() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d("Location Updates", "Google Play services is available.");
return true;
} else {
// Get the error dialog from Google Play services
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog( resultCode,
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(errorDialog);
errorFragment.show(getSupportFragmentManager(), "Location Updates");
}
return false;
}
}
/*
* 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) {
// Display the connection status
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
Location location = mLocationClient.getLastLocation();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17);
map.animateCamera(cameraUpdate);
}
/*
* 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 {
Toast.makeText(getApplicationContext(), "Sorry. Location services not available to you", Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nearby, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15);
mMap.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
#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
}
#Override
public void onInfoWindowClick(Marker arg0) {
// TODO Auto-generated method stub
}
}

Try adding the marker in onResume(). I'm surprised you're not getting a null pointer exception on map.setMyLocationEnabled(true), because in my experience, the map in a map fragment is not instantiated until onStart. Therefore you can't add markers to it in onCreate().

First you need to get all your database values to a list: example a store list with latitude and longitude. Then you have to add each and every marker to the map in this way (below code handles the click also):
private final void addLocationsToMap() {
int i = 0;
for (Stores store : storeList) {
LatLng l = new LatLng(store.getLatitude(), store.getLongtitude());
MarkerOptions marker = new MarkerOptions()
.position(l)
.title(store.getStoreName())
.snippet("" + i)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
googleMap.addMarker(marker);
++i;
}
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
try {
popUpWindow.setVisibility(View.VISIBLE);
Stores store = storeList.get(Integer.parseInt(marker
.getSnippet()));
// set details
email.setText(store.getEmail());
phoneNo.setText(store.getPhone());
address.setText(store.getAddress());
// setting test value to phone number
tempString = store.getPhone();
SpannableString spanString = new SpannableString(tempString);
spanString.setSpan(new UnderlineSpan(), 0,
spanString.length(), 0);
phoneNo.setText(spanString);
// setting test value to email
tempStringemail = store.getEmail();
SpannableString spanString1 = new SpannableString(tempStringemail);
spanString1.setSpan(new UnderlineSpan(), 0, spanString1.length(), 0);
email.setText(spanString1);
storeLat = store.getLatitude();
storelng = store.getLongtitude();
} catch (ArrayIndexOutOfBoundsException e) {
Log.e("ArrayIndexOutOfBoundsException", " Occured");
}
}
});
}

you should draw marker in onResume(), and you must be sure check the map != null before operate it.

Related

Unable to get current location in android

Greetings of the day. I'm working on app in which i need to show a map.
I want a map to be shown by default at my current location but i'm not able to do so. I've tried several ways to get Current Location (LatLng).
I followed this link too, the link works fine on emulator when i send LatLng from Android Device Monitor but fails on real device.
and wrote a simple piece of code given below
Location myLoc=mMap.getMyLocation();
double cLat=myLoc.getLatitude();
double cLng=myLoc.getLongitude();
showMap(cLat,cLng);
the above code returns NULL. Got stucked . Please help
You should handle the case where the Location is null, and fallback to a sensible default, like centering the map on a major city. Google's documentation states that the Location can be null in rare cases. In practice I have found this happens most often when the device has been indoors for a long time, or has had location services disabled.
public class SplashScreen extends Activity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
// LogCat tag
private static final String TAG = MainActivity.class.getSimpleName();
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private Location mLastLocation;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
CheckGPS();
ImageView textView = (ImageView) findViewById(R.id.center);
Animation logoMoveAnimation = AnimationUtils.loadAnimation(this, R.anim.splash);
textView.startAnimation(logoMoveAnimation);
}
private void setUpLocation() {
// First we need to check availability of play services
if (checkPlayServices()) {
// Building the GoogleApi client
buildGoogleApiClient();
}
}
/**
* Method to display the location on UI
*/
private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
getCities(latitude, longitude);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(SplashScreen.this, MainActivity.class));
finish();
}
}, 4000);
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(SplashScreen.this, MainActivity.class));
finish();
}
}, 4000);
}
}
private void getCities(double lat, double lng) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(lat, lng, 1);
String cityName = addresses.get(0).getLocality();
//String locality = addresses.get(0).getSubLocality();
API.OnCityID(SplashScreen.this, cityName);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Creating google api client object
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
/**
* Method to verify google play services on the device
*/
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 onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
#Override
protected void onResume() {
super.onResume();
checkPlayServices();
}
/**
* Google api callback methods
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
// Once connected with google api, get the location
displayLocation();
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
private void CheckGPS() {
// Get Location Manager and check for GPS & Network location services
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
// Build the alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Location Services Not Active");
builder.setMessage("Please enable Location Services and GPS");
builder.setPositiveButton("Setting", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
// Show location settings when the user acknowledges the alert dialog
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
finish();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
// Show location settings when the user acknowledges the alert dialog
dialogInterface.dismiss();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(SplashScreen.this, MainActivity.class));
finish();
}
}, 1500);
}
});
Dialog alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
} else {
setUpLocation();
}
}
}

How to create a class to get latitude and longitude of user, using Google API - Android

I'm developing an Android app, and I need to get latitude and longitude of the user.
I googled and found that Google API is the best for this, and I found a tutorial on this link: http://www.androidhive.info/2015/02/android-location-api-using-google-play-services/
How I don't need location updates (just click in a button, and get the location), I just copied this piece of code from tutorial:
public class MainActivity1 extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
private Location mLastLocation;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
// UI elements
private TextView lblLocation;
private Button btnShowLocation, btnStartLocationUpdates;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lblLocation = (TextView) findViewById(R.id.lblLocation);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
btnStartLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates);
// First we need to check availability of play services
if (checkPlayServices()) {
// Building the GoogleApi client
buildGoogleApiClient();
}
// Show location button click listener
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayLocation();
}
});
}
/**
* Method to display the location on UI
* */
private void displayLocation() {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
lblLocation.setText(latitude + ", " + longitude);
} else {
lblLocation
.setText("(Couldn't get the location. Make sure location is enabled on the device)");
}
}
/**
* Creating google api client object
* */
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
/**
* Method to verify google play services on the device
* */
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 onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
#Override
protected void onResume() {
super.onResume();
checkPlayServices();
}
/**
* Google api callback methods
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
// Once connected with google api, get the location
displayLocation();
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
}
and it worked!!!
But I want to create a method (in another class) that get the current location and return it (instead of doing this inside activity).
So, I modified what I did above, and finished with the following:
public class UserLocation implements ConnectionCallbacks, OnConnectionFailedListener {
private Location mLastLocation;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
public HashMap<String, Double> getUserLocation(Activity act) {
HashMap<String, Double> getLocation = new HashMap<>();
if (checkPlayServices(act)) {
buildGoogleApiClient(act);
}
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
getLocation.put("latitude", latitude);
getLocation.put("longitude", longitude);
return getLocation;
} else {
Log.i("FAIL: ", "(Couldn't get the location. Make sure location is enabled on the device)");
return null;
}
}
/**
* Creating google api client object
*/
protected synchronized void buildGoogleApiClient(Activity act) {
mGoogleApiClient = new GoogleApiClient.Builder(act)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
/**
* Method to verify google play services on the device
*/
private boolean checkPlayServices(Activity act) {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(act);
if (resultCode != ConnectionResult.SUCCESS) {
return false;
}
return true;
}
/**
* Google api callback methods
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i("Fail: ", "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
}
And I call it from the main Activity this way:
HashMap<String, Double> userLoc = ul.getUserLocation(this);
ul.getUserLocation(getActivity());
But with this new class, I don't get the location... I debuged, and saw that mLastLocation is always null...
Can somebody tell me what I'm doing wrong?
In the activity you get last location after Google API client connected and it is right. In UserLocation class you are trying to get location before connection established and it is wrong.
From the docs:
If not connected null will be returned.
You need to move getting location in onConnected() method and somehow notify the activity. You can create callback for it or simply let the activity implement ConnectionCallbacks instead of UserLocation.

Email address google maps app in a message to the mobile phone?

I am creating an app in android -studio , and I have a problem .
The app contains the Google Maps which shows us our location , but what really would make was that the push of a button , our location was sent by sms to a number of mobile phone , it will be possible ?
I created a demo app and it can:
Show your current location on the map as a marker.
Have a button. When you click it, it will create a SMS massage that you can send
your location via SMS.
Sample code:
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
ResultCallback<LocationSettingsResult>,
View.OnClickListener {
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;
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private LocationSettingsRequest mLocationSettingsRequest;
private Button btn_send_location;
private double mCurrentLatitude;
private double mCurrentLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
btn_send_location = (Button) findViewById(R.id.send_my_location_btn);
btn_send_location.setOnClickListener(this);
long interval = 10 * 1000; // 10 seconds, in milliseconds
long fastestInterval = 1 * 1000; // 1 second, in milliseconds
float minDisplacement = 0;
// // Check if has GPS
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
}
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
// mLocationRequest = LocationRequest.create()
// .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
// .setInterval(interval)
// .setFastestInterval(fastestInterval)
// .setSmallestDisplacement(minDisplacement);
// Check if has GPS by using Google play service
// buildLocationSettingsRequest();
// checkLocationSettings();
}
#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();
}
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
mCurrentLatitude = location.getLatitude();
mCurrentLongitude = location.getLongitude();
LatLng latLng = new LatLng(mCurrentLatitude, mCurrentLongitude);
//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.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
}
#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);
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
/**
* Uses a {#link com.google.android.gms.location.LocationSettingsRequest.Builder} to build
* a {#link com.google.android.gms.location.LocationSettingsRequest} that is used for checking
* if a device has the needed location settings.
*/
protected void buildLocationSettingsRequest() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
mLocationSettingsRequest = builder.build();
}
protected void checkLocationSettings() {
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(
mGoogleApiClient,
mLocationSettingsRequest
);
result.setResultCallback(this);
}
#Override
public void onResult(LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// NO need to show the dialog;
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. Show the user a dialog
try {
// Show the dialog by calling startResolutionForResult(), and check the result
// in onActivityResult().
status.startResolutionForResult(this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
//unable to execute request
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are inadequate, and cannot be fixed here. Dialog not created
break;
}
}
#Override
public void onClick(View v) {
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("sms:"));
sendIntent.putExtra("sms_body", "My location at \nLatitude: " + mCurrentLatitude + " \nLongitude: " + mCurrentLongitude);
startActivity(sendIntent);
}
}
And the xml file activity_maps.xml is:
<LinearLayout 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:orientation="vertical">
<Button
android:id="#+id/send_my_location_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send My location via SMS"/>
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity"/>
</LinearLayout>
If you want to get the whole project, please refer to here.

Handling Location updates

I am trying to create a page that will outlay (using Google Maps) a race circuit and will use a dot of some kind to show and update the users current location.
The code I have for this is:
public class TopGearLocationTracker extends FragmentActivity implements
//Specifies methods that Location Services calls when a location client
//is connected or disconnected.//
GooglePlayServicesClient.ConnectionCallbacks,
//Specifies a method that Location Services calls if an error occurs while
//attempting to connect the location client. This method uses the previously-
//defined showErrorDialog method to display an error dialog that attempts to
//fix the problem using Google Play services.
GooglePlayServicesClient.OnConnectionFailedListener,
//The callback method that Location Services invokes to send a location update
//to your application is specified in the LocationListener interface, in the method
//onLocationChanged(). The incoming argument is a Location object containing the
//location's latitude and longitude. The following snippet shows how to specify
//the interface and define the method:
LocationListener
{
// Global constants
/*
* 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;
// Global variable to hold the current location
Location mCurrentLocation;
private GoogleMap aMap;
// Global constants
// Milliseconds per second
private static final int MILLISECONDS_PER_SECOND = 1000;
// Update frequency in seconds
public static final int UPDATE_INTERVAL_IN_SECONDS = 5;
// Update frequency in milliseconds
private static final long UPDATE_INTERVAL =
MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;
// The fastest update frequency, in seconds
private static final int FASTEST_INTERVAL_IN_SECONDS = 1;
// A fast frequency ceiling in milliseconds
private static final long FASTEST_INTERVAL =
MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS;
// Define an object that holds accuracy and frequency parameters
LocationRequest mLocationRequest;
// Global variables
LocationClient mLocationClient;
boolean mUpdatesRequested;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.top_gear_location_tracker);
// Set the map up
// Set the map to Top Gear track location
LatLng topGearTrack = new LatLng(51.116492, -0.541767);
aMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
aMap.getUiSettings().setAllGesturesEnabled(false);
aMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
aMap.setMyLocationEnabled(true);
aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(topGearTrack, 15));
setUpMapIfNeeded();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create();
// Use high accuracy
mLocationRequest.setPriority(
LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the update interval to 5 seconds
mLocationRequest.setInterval(UPDATE_INTERVAL);
// Set the fastest update interval to 1 second
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
// Open the shared preferences
//mPrefs = getSharedPreferences("SharedPreferences",
//Context.MODE_PRIVATE);
// Get a SharedPreferences editor
//mEditor = mPrefs.edit();
/*
* Create a new location client, using the enclosing class to
* handle callbacks.
*/
mLocationClient = new LocationClient(this, this, this);
// Start with updates turned off
mUpdatesRequested = false;
}
public void setUpMapIfNeeded()
{
//Do a null check to confirm that we have not already instantiated the map.
if (aMap == null)
{
aMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
//Check if we were successful in obtaining the map.
if (aMap != null)
{
//The Map is verified. It is now safe to manipulate the map.
}
}
}
/*
* Called when the Activity becomes visible.
*/
#Override
protected void onStart()
{
super.onStart();
// Connect the client.
mLocationClient.connect();
}
/*
* Called when the Activity is no longer visible.
*/
#Override
protected void onStop()
{
// Disconnecting the client invalidates it.
mLocationClient.disconnect();
super.onStop();
}
// *************** CHECK FOR GOOGLE PLAY SERVICES *************** //
#SuppressWarnings("unused")
private boolean servicesConnected()
{
// Check that Google Play services is available
int resultCode =
GooglePlayServicesUtil.
isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode)
{
// In debug mode, log the status
Log.d("Location Updates",
"Google Play services is available.");
// Continue
return true;
// Google Play services was not available for some reason
}
else
{
// Get the error code
// Get the error dialog from Google Play services
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
resultCode,
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null)
{
// Create a new DialogFragment for the error dialog
ErrorDialogFragment errorFragment =
new ErrorDialogFragment();
// Set the dialog in the DialogFragment
errorFragment.setDialog(errorDialog);
// Show the error dialog in the DialogFragment
errorFragment.show(getSupportFragmentManager(),
"Location Updates");
}
}
return false;
}
// Define a DialogFragment that displays the error dialog
public static class ErrorDialogFragment extends DialogFragment
{
// Global field to contain the error dialog
private Dialog mDialog;
// Default constructor. Sets the dialog field to null
public ErrorDialogFragment()
{
super();
mDialog = null;
}
// Set the dialog to display
public void setDialog(Dialog dialog)
{
mDialog = dialog;
}
// Return a Dialog to the DialogFragment.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
return mDialog;
}
}
/*
* Handle results returned to the FragmentActivity
* by Google Play services
*/
#Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data)
{
// Decide what to do based on the original request code
switch (requestCode)
{
case CONNECTION_FAILURE_RESOLUTION_REQUEST :
/*
* If the result code is Activity.RESULT_OK, try
* to connect again
*/
switch (resultCode) {
case Activity.RESULT_OK :
/*
* Try the request again
*/
break;
}
}
}
// ******************** CALLBACK METHODS AND INTERFACES ******************** //
/*
* 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)
{
// Display the connection status
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
// If already requested, start periodic updates
if (mUpdatesRequested)
{
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
}
/*
* 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 cancelled 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.
*/
showErrorDialog(connectionResult.getErrorCode());
}
}
private void showErrorDialog(int errorCode)
{
new AlertDialog.Builder(this)
.setMessage(String.valueOf(errorCode))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.dismiss();
}
}).show();
}
// Define the callback method that receives location updates
#Override
public void onLocationChanged(Location location)
{
// Report to the UI that the location was updated
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
When I try to load this 'page' by clicking a button from a previous page it doesn't load up. I was at least expecting the map (of Top Gear test track) to load up.
What could be stopping the map from loading up?
Is my approach to creating what I'm after correct?
I have pretty much followed:
http://developer.android.com/training/location/retrieve-current.html
http://developer.android.com/training/location/receive-location-updates.html
(I haven't bothered with the Shared Preferences thing).
I think to test it I would be best to use my home location lat/lang but for the moment I can't get the map to appear? This was tested on my HTC One so shouldn't be a Google Play Services issue as the screen that loads this one is a static (except zoom in/out) Map of the same place.
I appreciate this is a 'large' question and I would appreciate feedback from people that have experience/created a 'location-aware' application.
Thanks.
You may refer to the article https://software.intel.com/en-us/articles/implementing-map-and-geofence-features-in-android-business-apps
Add Android Manifest permissions:
<uses-permission android:name=”android.permission.INTERNET"/>
and
<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="copy your API Key here"/>
To add a map fragment:
and
…
private static final LatLng CHANDLER = new LatLng(33.455,-112.0668);
…
private static final StoreLocation[] ALLRESTURANTLOCATIONS = new StoreLocation[] {
new StoreLocation(new LatLng(33.455,-112.0668), new String("Phoenix, AZ")),
new StoreLocation(new LatLng(33.5123,-111.9336), new String("SCOTTSDALE, AZ")),
new StoreLocation(new LatLng(33.3333,-111.8335), new String("Chandler, AZ")),
new StoreLocation(new LatLng(33.4296,-111.9436), new String("Tempe, AZ")),
new StoreLocation(new LatLng(33.4152,-111.8315), new String("Mesa, AZ")),
new StoreLocation(new LatLng(33.3525,-111.7896), new String("Gilbert, AZ"))
};
…
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.geolocation_view);
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.storelocationmap)).getMap();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(CHANDLER, ZOOM_LEVEL));
Drawable iconDrawable = getResources().getDrawable(R.drawable.ic_launcher);
Bitmap iconBmp = ((BitmapDrawable) iconDrawable).getBitmap();
for(int ix = 0; ix < ALLRESTURANTLOCATIONS.length; ix++) {
mMap.addMarker(new MarkerOptions()
.position(ALLRESTURANTLOCATIONS[ix].mLatLng)
.icon(BitmapDescriptorFactory.fromBitmap(iconBmp)));
}
Then you add the LocationListener and the location update callbacks.

android google maps v2 get last know location and always start with network provider

This Google Maps v2 api confuses me quite a bit. I have implemented it now in some way i would like to use it. I just have two small problems that i don't know how to go about.
Sometimes I don't get a location when i start the app with gps enabled or it takes way too long to get one.
So I would like it to always load with the internet location provider first to have a very fast location fix as well as always using the getlastknownlocation() first. Cant figure out how to go about it.
Here my code:
public class MapViewMain extends FragmentActivity implements LocationListener, LocationSource
{
private GoogleMap mMap;
private OnLocationChangedListener mListener;
private LocationManager locationManager;
final int RQS_GooglePlayServices = 1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mapviewmain);
//start power button service
Intent intent=new Intent("com.epicelements.spotnsave.START_SERVICE");
this.startService(intent);
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
Toast.makeText(this, "Google Service not found", Toast.LENGTH_LONG).show();
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if(locationManager != null)
{
boolean gpsIsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean networkIsEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!gpsIsEnabled) {
// Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
PopIt("No GPS found", "Would you like to go to the settings to activate it?");
}
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 some generic error dialog because something must have gone wrong with location manager.
}
setUpMapIfNeeded();
}
}
#Override
public void onPause()
{
if(locationManager != null)
{
locationManager.removeUpdates(this);
}
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
locationManager.getBestProvider(criteria, true);
if(mListener != null){
}
setUpMapIfNeeded();
mMap.setMyLocationEnabled(true); // Enable the my-location layer
if(locationManager != null)
{
mMap.setMyLocationEnabled(true); // Enable the my-location layer
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
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.
* <p>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap()
{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mMap.setPadding(0,60,0,150);
Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE);
}
#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 );
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng coordinate = new LatLng(lat, lng);
//save coordinate
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putFloat("lat", (float) location.getLatitude());
editor.putFloat("lng", (float) location.getLongitude());
editor.putFloat("accuracy", (float) location.getAccuracy());
editor.commit();
//marker stuff
mMap.clear();
mMap.addMarker(new MarkerOptions()
.position(coordinate)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 16));
}
}
#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();
}
// Alarm Dialog if GPS not enabled
public void PopIt( String title, String message ){
new AlertDialog.Builder(this)
.setTitle( title )
.setMessage( message )
.setCancelable(false)
.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//do stuff onclick of YES
//AlertDialog.dismiss();
}
})
.setNegativeButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//do stuff onclick of CANCEL
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}).show();
}
}
You can use LocationClient for your purpose its give LastLocation very fast.
first declare class variable
private LocationClient client;
after in onCreate
try {
if (map == null) {
MapsInitializer.initialize(this);
client = new LocationClient(this, new ConnectionCallbacks() {
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle connectionHint) {
// TODO Auto-generated method stub
Toast.makeText(MotoFreightHomeMapMainActivity.this,
"onConnected", Toast.LENGTH_LONG).show();
Location currentLocation = client.getLastLocation();
if (currentLocation != null) {
//do you stuff here
}
}
}, new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
}
});
client.connect();
}
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
etMap.setVisibility(View.INVISIBLE);
btnEditLocation.setVisibility(View.INVISIBLE);
Toast.makeText(this, "Please install Google Play Library",
Toast.LENGTH_SHORT).show();
}
see full code here
http://developer.android.com/training/location/retrieve-current.html
You can find a sample and tutorial from here.

Categories

Resources