How can I get the longitude and latitude in my android app? - java

I've been trying to get the location for the particular phone for a while now. I have used the following code but instead of showing the location it will just crash when I try and run the app in my emulator.
Once I've got the longitude and latitude I am going to use it to map the current location on a google map!
public class Homescreen extends ActionBarActivity implements LocationListener {
final TextView t = (TextView)findViewById(R.id.textView1);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homescreen);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.homescreen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());
t.setText(latitude);
// Log.i("Geo_Location", "Latitude: " + latitude + ", Longitude: " + longitude);
}

Use This Activity. I hope it will help you.
package yourPackage;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.infologitech.spotways.constants.SpotwaysSettingsKeys.SettingDefaultValue;
import com.infologitech.spotways.constants.SpotwaysSettingsKeys.SettingKey;
import com.infologitech.spotways.custom.TransactionSupport;
public class GetCurrentLocationActivity extends Activity implements
LocationListener, ConnectionCallbacks, OnConnectionFailedListener {
private Context context = this;
private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
private Location mLocation;
private float minAccuracy = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (checkPlayServices()) {
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
//waitForLocation();
}else finish();
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
}
#Override
public void onConnected(Bundle arg0) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(5 * 1000);
mLocationRequest.setFastestInterval(2 * 1000);
mLocationRequest.setSmallestDisplacement(5f);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
#Override
public void onDisconnected() {
}
#Override
public void onLocationChanged(Location loc) {
if (loc != null) {
int latitude = (int) (loc.getLatitude());
int longitude = (int) (loc.getLongitude());
Toast.makeText(this,"Lat "+latitude+", Lng "+longitude);
}
}
#Override
protected void onDestroy() {
stopUpdate();
super.onDestroy();
}
private void stopUpdate() {
try {
mLocationClient.removeLocationUpdates(this);
mLocationClient.disconnect();
} catch (Exception e) {
}
}
public boolean checkPlayServices() {
final int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
resultCode, context, 3434);
if (dialog != null) {
dialog.show();
dialog.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
if (ConnectionResult.SERVICE_INVALID == resultCode) {
}
}
});
return false;
}
}
return false;
}
return true;
}
}

Related

Fatal Exception : java.lang.IllegalArgumentException: GoogleApiClient parameter is required

I'm trying to create an Android Location API using Google Play Services.
But I keep on getting " java.lang.IllegalStateException: GoogleApiClient is required ".
Can anyone tell me what I am doing wrong?
Here's the code which I have been trying.
CODE:
package com.example.jamshi.locationapi;
import android.app.Activity;
import android.location.Location;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
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.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends Activity implements ConnectionCallbacks,OnConnectionFailedListener {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private TextView tvLocation;
private Button btnShowLocation,btnLocationUpdates;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvLocation = (TextView) findViewById(R.id.tvLocation);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
btnLocationUpdates = (Button) findViewById(R.id.btnLocationUpdates);
boolean checkPlayServices = false;
if(checkPlayServices){
buildApiClient();
}
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayLocation();
}
});
}
private void displayLocation() {
//buildApiClient();
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
tvLocation.setText(latitude + ", " + longitude);
} else {
tvLocation.setText("(Couldn't get the location. Make sure location is enabled 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;
}
protected synchronized void buildApiClient() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
}
#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();
}
}
Because mGoogleApiClient is null.
buildApiClient() method is never called also, probably you made a mistake in onCreate
boolean checkPlayServices = false;
if(checkPlayServices){
buildApiClient();
}
Elaborated
This checkPlayServices variable here false, so it does not call buildApiClient() method, as a result mGoogleApiClient is null.
#Override
protected void onCreate(Bundle savedInstanceState) {
...
boolean checkPlayServices = false;
if(checkPlayServices){
buildApiClient();
}
}
connect method is not called, because mGoogleApiClient is null
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
After the activity is created, and when you call displayLocation() method, it crashes due to mGoogleApiClient is null
private void displayLocation() {
//buildApiClient();
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
...
}

Is this error the reason my code always returns "no location"?

I am making an app that will require the user's location. This is its code so far:
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends Activity implements LocationListener {
LocationManager locationManager;
String provider;
Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = LocationManager.NETWORK_PROVIDER;
location = locationManager.getLastKnownLocation(provider);
}
public void locationStuff(View view) {
if (location != null) {
Log.i("Location Info", "Location achieved!");
} else {
Log.i("Location Info", "No location :(");
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
Double lat = location.getLatitude();
Double lng = location.getLongitude();
Log.i("Location info: Lat", lat.toString());
Log.i("Location info: Lng", lng.toString());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
public void getLocation(View view) {
Location location = locationManager.getLastKnownLocation(provider);
onLocationChanged(location);
}
}
It only returns " no location". I am trying to get it to output "location achieved". I attached a link to a picture of the error. Please let me know if you see what is wrong.error image
You can use GoggleLocationClient for better results.
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, LocationListener {
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createLocationRequest();
TextView mTextView = (TextView)findViewById(R.id.mTextView);
mTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buildGoogleApipClient();
mGoogleApiClient.connect();
}
});
}
LocationRequest mLocationRequest;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected synchronized void buildGoogleApipClient() {
mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "Yes calling", Toast.LENGTH_LONG).show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation!=null){
Toast.makeText(this,mLastLocation.getLatitude()+"-----"+mLastLocation.getLongitude(),Toast.LENGTH_LONG).show();
}
if (true) {
startLocationUpdates();
}
}
protected void startLocationUpdates() {
/*LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);*/
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
location = location;
//mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
private void updateUI() {
Toast.makeText(this,mLastLocation.getLatitude()+"-----"+mLastLocation.getLongitude(),Toast.LENGTH_LONG).show();
}
}

Issue with using Accelerometer and GPS at the same time in Android Studio

I'm pretty new to programming in android studio, and I've been trying to figure this out for a while, but I'm not sure what the problem is. I'm trying to use a combination of the Accelerometer and GPS at the same time to get a more accurate number for the acceleration and speed of the device, but when I try to start the accelerometer it throws this exception:
java.lang.RuntimeException: Unable to start activity ComponentInfo
Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate()
Here is the MainActivity:
package com.example.accelerometergps;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements LocationListener {
private Accelerometer a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager l = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
l.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
this.onLocationChanged(null);
a = new Accelerometer();
//It works fine if I remove the following line
a.registerListener();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView) findViewById(R.id.textView);
if (location == null) {
tv.setText("no GPS");
} else {
double temp = location.getSpeed();
double speed = 2.23694 * temp;
// tv.setText(String.valueOf(speed));
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Here is the Accelerometer Class:
package com.example.accelerometergps;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class Accelerometer extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
double[] accelerationList = new double[5];
double averageAcceleration;
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void registerListener() {
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
public void unregisterListener() {
mSensorManager.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
double temp = sumAcceleration(x, y, z);
addToList(temp);
averageAcceleration = accelerationListAverage();
}
public double sumAcceleration(float i, float j, float k) {
float temp = i * i + j * j + k * k;
double linearAcceleration = Math.sqrt(temp) - 9.8;
return linearAcceleration;
}
public double accelerationListAverage() {
double sum = 0;
for (int i = 0; i < 5; i++) {
sum += accelerationList[i];
}
return (sum / 5);
}
public void addToList(double a) {
double b = accelerationList[0];
double c = accelerationList[1];
double d = accelerationList[2];
double e = accelerationList[3];
accelerationList[0] = a;
accelerationList[1] = b;
accelerationList[2] = c;
accelerationList[3] = d;
accelerationList[4] = e;
}
public double getAcceleration() {
return averageAcceleration;
}
}
Any help or suggestions would be greatly appreciated, thank you in advance.
You should NEVER create an activity directly. Your MainActivity is holding an Accelerometer, which is of type Activity. That's just wrong. You need to rearchitect things so Accelerometer is not an Activity. It should be passed in a Context to grab anything it needs from the current Activity.

MediaPlayer plays double sounds on change orientation

I have a big problem with this app. The problem with it is that when the orientation changes to landscape and then change it to portrait the music twice tracks plays at the same time. But when i start the app on portrait i have no problem with it.
package com.phone.sensor;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class sensorActivity extends Activity implements SensorEventListener{
public boolean musStatus = false;
public boolean musDeclare = true;
public MediaPlayer mp = null;
Sensor accelerometer;
SensorManager sm;
TextView acceleration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState == null){
if(mp != null){
mp.stop();
mp.reset();
mp = null;
}
} else {
if(mp != null){
mp.stop();
mp.reset();
mp = null;
}
}
setContentView(R.layout.activity_main);
sm=(SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
acceleration=(TextView)findViewById(R.id.acceleration);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSaveInstanceState (Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putBoolean("musStatus", musStatus);
outState.putBoolean("musDeclare", musDeclare);
}
public Object onRetainCustomNonConfigurationInstance() {
return this.mp;
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
acceleration.setText("X: "+event.values[0]+
"\nY: "+event.values[1]+
"\nZ: "+event.values[2]);
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
if(y > 8.9) {
if(musDeclare == true)
{
mp = MediaPlayer.create(this, R.raw.alexander);
musDeclare = false;
}
if(musStatus == false)
{
mp.start();
musStatus = true;
}
}
if(y < 5)
{
if(musStatus == true)
{
mp.stop();
mp.reset();
mp = null;
musStatus = false;
musDeclare = true;
}
}
}
}
Try putting this block of code in the OnPause method of your class
if(mp != null && mp.IsPlaying()){
mp.stop();
mp.reset();
mp = null;
}
}

Android - GMapsV2 - Why is my activity not drawing the polyline?

I'm trying to get a red polyline to draw whenever the user moves. Here is the following code I have:
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationSource, LocationListener {
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
TextView tvLocInfo;
LocationManager myLocationManager = null;
OnLocationChangedListener myLocationListener = null;
Criteria myCriteria;
Location lastLocationloc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvLocInfo = (TextView)findViewById(R.id.locinfo);
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment
= (MapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap = myMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
myCriteria = new Criteria();
myCriteria.setAccuracy(Criteria.ACCURACY_FINE);
myLocationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_legalnotices:
String LicenseInfo = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(
getApplicationContext());
AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(MainActivity.this);
LicenseDialog.setTitle("Legal Notices");
LicenseDialog.setMessage(LicenseInfo);
LicenseDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS){
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS",
Toast.LENGTH_LONG).show();
//Register for location updates using a Criteria, and a callback on the specified looper thread.
myLocationManager.requestLocationUpdates(
0L, //minTime
0.0f, //minDistance
myCriteria, //criteria
this, //listener
null); //looper
//Replaces the location source of the my-location layer.
myMap.setLocationSource(this);
}else{
GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
}
}
#Override
protected void onPause() {
myMap.setLocationSource(null);
myLocationManager.removeUpdates(this);
super.onPause();
}
#Override
public void activate(OnLocationChangedListener listener) {
myLocationListener = listener;
}
#Override
public void deactivate() {
myLocationListener = null;
}
/*#Override
public void onLocationChanged(Location location) {
if (myLocationListener != null) {
myLocationListener.onLocationChanged(location);
double lat = location.getLatitude();
double lon = location.getLongitude();
tvLocInfo.setText(
"lat: " + lat + "\n" +
"lon: " + lon);
}
}*/
#Override
public void onLocationChanged(Location location) {
if (lastLocationloc == null) {
lastLocationloc = location;
}
LatLng lastLatLng = locationToLatLng(lastLocationloc);
LatLng thisLatLng = locationToLatLng(location);
//Log.e(TAG, "Last LatLng is :"+lastLatLng);
//Log.e(TAG, "Last LatLng is :"+thisLatLng);
myMap.addPolyline(new PolylineOptions().add(lastLatLng).add(thisLatLng).width(3).color(Color.RED));
lastLocationloc = location;
}
public static LatLng locationToLatLng(Location loc) {
if (loc != null)
return new LatLng(loc.getLatitude(), loc.getLongitude());
return null;
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
When I go to run application on an actual device nothing happens. No polyline appears. What am I doing wrong?

Categories