I can not get the GPS to work. I am saving it in a SharedPreference called gps and it will print in a Toast as "http://maps.google.com/?q=" + lat + " , " + lon
this is so when it is sent in a SMS they receiver can just push the link and it opens the map. But when the toast comes up it is blank. Below is my code.
private void showLocation() {
LocationManager locationManager = (LocationManager)
getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
LocationListener loc_listener = new LocationListener() {
public void onLocationChanged(Location l) {}
public void onProviderEnabled(String p) {}
public void onProviderDisabled(String p) {}
public void onStatusChanged(String p, int status, Bundle extras) {}
};
locationManager
.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
location = locationManager.getLastKnownLocation(bestProvider);
double lat, lon;
try {
lat = location.getLatitude();
lon = location.getLongitude();
} catch (NullPointerException e) {
lat = -1.0;
lon = -1.0;
}
prefs.setPreferenceString(getApplicationContext(),"gps" ,"http://maps.google.com/?q=" + lat + " , " + lon);
}
to find your location try to use GPSTracker. link
And use this code.
gps = new GPSTracker(LauncherActivity.this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
And one more things, check your device, is it support GPS? And is it (GPS) enable? If your device's GPS is not enable, you will get null....
For more help... check my github repo
I am trying to make such app, here are the code for toast that works well:
Handler handler3 = new Handler(Looper.getMainLooper());
handler3.post(new Runnable(){
#Override
public void run(){
Toast.makeText(context,"mensagem",Toast.LENGTH_LONG).show();
}
});
Related
I am trying to get the latitude and longitude of the current location using the following:
GoogleMap map;
map = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
lat = map.getMyLocation().getLatitude();
lng = map.getMyLocation().getLongitude();
For some reason the last two lines are causing the app to crash due to a NullPointerException. What am I doing wrong?
The biggest thing that bugs me about this is the fact that map.setMyLocationEnabled(true); does indeed set my current location.
Thanks to anyone looking at this
Try this:
public Double Lat = null;
public Double Lng = null;
String LatLng = null;
private LocationClient mLocationClient;
in your onCreateView() add this
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.yourLayout, container, false);
mLocationClient = new LocationClient(getActivity(), this, this);
rootView.findViewById(R.id.ATestButton).setOnClickListener(
// Get the current location
Location currentLocation = mLocationClient.getLastLocation();
Lat = currentLocation.getLatitude();
Lng = currentLocation.getLongitude();
LatLng = Double.toString(Lat) + "," + Double.toString(Lng);
Toast.makeText(getActivity(), LatLng, 0).show();
});
Look at my complete github for a working example.
// I would a test button so can click it to see if anything is returned.
public void turnGPSOn() {
String provider = Settings.Secure.getString(getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) {
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
void getLocation()
{
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!locManager
.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
turnGPSOn();
}
try {
locManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 10,
locationListener);
} catch (Exception ex) {
}
}
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void updateWithNewLocation(Location location) {
String latLongString = "";
try {
if (location != null) {
Log.e("test", "gps is on send");
latitude = Double.toString(location.getLatitude());
longitude = Double.toString(location.getLongitude());
Log.e("test", "location send");
latLongString = "Lat:" + latitude + "\nLong:" + longitude;
Log.w("CurrentLocLatLong", latLongString);
} else {
latLongString = "No location found";
}
} catch (Exception e) {
}
}
Your app is crashing because
map.getMyLocation()
returns null if there is no location data available.So you can have !=null check like this
if( map.getMyLocation() !=null){
lat = map.getMyLocation().getLatitude();
lng = map.getMyLocation().getLongitude();
}
Also this method is deprecated, so you should use FusedLocationProviderApi instead. See official documentation here
Here is a very good implementation of FusedLocation Api, you can check out that too.
map.getMyLocation() is null
you should check for that condition
I have found a solution. While I am still not sure why the other methods is giving me a null pointer, the below works just fine and will suit my needs.
LocationManager locman = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = locman .getLastKnownLocation(LocationManager.GPS_PROVIDER);
double lng = location.getLongitude();
double lat = location.getLatitude();
I am trying to get latitude and longitude but sometime network is available but I am not getting value of latitude and longitude. I am using MyLocationListener class and put condition all but some time value is not getting.
protected void showCurrentLocation()
{
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null)
{
counter++;
latitude=location.getLatitude();
longitude=location.getLongitude();
altitude=location.getAltitude();
}
}
private class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location)
{
counter++;
latitude=location.getLatitude();
longitude=location.getLongitude();
altitude=location.getAltitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle b)
{
}
#Override
public void onProviderDisabled(String s)
{
}
#Override
public void onProviderEnabled(String s)
{
}
}
Here Best way to get Longitude Latitude:
/** PROCESS for Get Longitude and Latitude **/
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
Log.d("msg", "changed Loc : "+longitude + ":"+latitude);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if GPS enabled
if(isGPSEnabled){
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
Log.d("msg", "Loc : "+longitude + ":"+latitude);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}else
{
/*
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setCostAllowed(true);
String provider = locationManager.getBestProvider(criteria, true);
*/
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null)
{
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}else
{
longitude = "0.00";
latitude = "0.00";
}
}
}
if device is not able to get currentLocation using GPS then it'll be take fron NetworkProvider or else it'll take 0,0 as my requirement but you can modify as per your requirement
May it'll helpful to you.
Happy Coding :D
See, this is a very common problem. In order to have exact Latitude and Longitude ,You must use GPS also it must me activated on the mobile device but GPS too have some limitations. GPS works most efficiently under open sky. you will not have a clear range inside a building. So try your code under open sky and check the response.
I have a simple class GPSListener which gets the GPS coordinates:
public class GPSListener implements LocationListener {
public static double latitude;
public static double longitude;
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.d("GPSLISTENER ", "lat: "+latitude+" long:"+longitude);
} ...
Then trying to make use of this class in my activity, I simply invoke the class in my onCreate() function in my activity:
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new GPSListener();
Criteria criteria = new Criteria();
String bestProvider = mlocManager.getBestProvider(criteria, false);
mlocManager.requestLocationUpdates(bestProvider, 0, 0, mlocListener);
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
lat = GPSListener.latitude;
lon = GPSListener.longitude;
Log.d("GPS", "lat: "+lat+" long:"+lon);
} else {
// TODO: GPS not enabled
Log.d("GPSERROR", "GPS not enabled");
}
But whenever I run the application, lat and lon in my activity are always zero. I'm not quite sure how to get around this issue.
When logging:
Log.d("GPSLISTENER ", "lat: "+latitude+" long:"+longitude);
It returns the correct latitude and longitude, it just takes a second or two after the activity starts.
Log.d("GPSSUCCESS", "lat: "+lat+" long:"+lon);
Just returns 0.0 for both. I was under the impression that .requestLocationUpdates would pass the value to lat and lon before the if statement is executed. How can I accomplish this?
You are using public static field for latitude, longitude.
Please change it to non static and using setter, getter with instant object:
lat = mlocListener.getLatitude();
lon = mlocListener.getLongitude();
Google updated its location handling logic. It is now easier to listen location updates with fused location provider. You can implement your location listener in 5 min. Take a look.
Methods for getting the most accurate location
You are listening only gps provider and it is not ready(on waiting for location status) yet and then it does not return any location. Just take a look at fused location provider and write your location listener again.
try this...
mGoogleMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick()
{
try
{
Location myLocation = mGoogleMap.getMyLocation();
onLocationChanged(myLocation);
}
catch (Exception e)
{
Log.getStackTraceString(e);
}
return false;
}
});
user this Handler to get Location
private Handler customHandler = new Handler();
private Runnable updateTimerThread = new Runnable() {
#Override
public void run()
{
try
{
Location myLocation = mGoogleMap.getMyLocation();
secndLocationListener.onLocationChanged(myLocation);
}
catch (Exception e)
{
Log.getStackTraceString(e);
}
}
};
to run this
customHandler.postDelayed(updateTimerThread , 1000);
LocationManager uses the last known location from the cache. The cache is updated when you load google maps. Try this out, go out in the open and check your location. Move to a different location about 200m and check your location again. It will be same as the old one. Now, load google maps, you will notice that you application magically now has the new location.
You need to programmatically kick that cache to the latest location. The only way to do that is
YOUR_APPLICATION_CONTEXT.getLocationManager().requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(final Location location) {
}
});
I am using the following code to find current location of user
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, this);
public void onLocationChanged(Location location) {
Log.e("changed","location");
// TODO Auto-generated method stub
showLocation(location);
}
But the location of user is not finding.If i change provider to Network Provider its working.But with GPS provider only it not working.
change the requestLocationUpdates method so that it updates faster and with less change in coordinates. Change it to:-
requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Try it now. If possible move the phone some meters so that it is detected soon by the GPS satellites. I am presuming that GPS is switched on.
GPS does not provide a 'get my location on demand' functionality. You have to be patient and wait until the device gets a fix from several satellites. This may take several minutes, even with a clear view of the sky. This is why the OS implements this as a callback. onLocationChanged runs when the device has a fix and you just have to wait for it.
Will you please elaborate more? Do you need to find the current location in mapview by Long or Lat? If this is your question then do one thing :
Find Lat and Long by sending manually through DDMS or by generating Lat and Lang on click at mapview :
It can be done by:
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " + "Latitud = " + loc.getLatitude() + "Longitud = " + loc.getLongitude();
Toast.MakeTest(getApplicationContext(),Text,Toast.Length_Long).show()
}
So by this you can get your lat and Long.After getting Lat and Long at mapView's click listener you can write below code:
Projection proj = view1.getProjection();
GeoPoint loc = proj.fromPixels((int)ev.getX(), (int)ev.getY());
//Getting Lat and Log
String longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
String latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);
GeoPoint point = new GeoPoint( (int) (loc.getLatitudeE6()),(int) (loc.getLongitudeE6()));
//Getting location from lat and Long
String address="";
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
}
catch (IOException e) {
e.printStackTrace();
}
Toast t =Toast.makeText(getApplicationContext(), "Longitude: "+ longitude +" Latitude: "+ latitude+" name: "+address, Toast.LENGTH_LONG);
t.show();
You will get output as you click at mapview.
For click event on MapView please write above code in dispatchTouchEvent() as
public boolean dispatchTouchEvent(MotionEvent ev) {
int actionType = ev.getAction();
switch (actionType) {
case MotionEvent.ACTION_UP:
//write above code here
}
}
Try this one.
Edit: Check your code with this given below code.
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " + "Latitud = "
+ loc.getLatitude() + "Longitud = " + loc.getLongitude();
latituteField.setText(String.valueOf(loc.getLatitude()));
longitudeField.setText(String.valueOf(loc.getLongitude()));
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled",Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
First check Your GPS is enabled or disabled.After enabling GPS ,using Location listener to get current location.I am using follwing code to get gps location
String sourceLat, sourceLong;
LocationManager locManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtCurrLat = (TextView) findViewById(R.id.txtCurrLat);
txtCurrLong = (TextView) findViewById(R.id.txtCurrLong);
mapView = (MapView) findViewById(R.id.mapview);
geoPoint = null;
mapView.setSatellite(false);
locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f, locationListener);
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
double fromLat = location.getLatitude();
double fromLong = roundTwoDecimals(location.getLongitude());
Toast.makeText(getApplicationContext(), fromLat +fromLong+"" , Toast.LENGTH_SHORT).show();
sourceLat = Double.toString(fromLat);
sourceLong = Double.toString(fromLong);
txtCurrLat.setText(sourceLat+","+sourceLong);
btnShow.setOnClickListener(this);
}else{
Toast.makeText(getApplicationContext(), "Location is not avilable", Toast.LENGTH_SHORT).show();
}
}
private void updateWithNewLocation(Location location) {
String latLongString = "";
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
sourceLat = Double.toString(lat);
sourceLong = Double.toString(lng);
latLongString = sourceLat + "," + sourceLong;
} else {
latLongString = "No location found";
Toast.makeText(getApplicationContext(), latLongString+"", Toast.LENGTH_SHORT).show();
}
txtCurrLat.setText(latLongString);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
Toast.makeText( getApplicationContext(), "Gps is Disabled.Please enabale gps", Toast.LENGTH_SHORT ).show();
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
Toast.makeText( getApplicationContext(), "Gps is Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
I have implemented sample application for get the current location latitude longitude.If i lunch my application in emulator and i am sending latitude and longitude from Emulator Controls at eclipse then i am getting current location latitude and longitude which from emulator controls.If i lunch the same application in real device then i am not able to get current location latitude and longitude
I have implemented code for get the current location latitude and longitude as follows:
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 11, 11, mlocListener);
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
Log.v("11111","Latitude :"+loc.getLatitude());
Log.v("22222","Longitude :"+ loc.getLongitude());
}
}
From the above code i am not getting current location latitude and longitude in real android device.
How can i get current location latitude and longitude of real device?
please any body help me
GPS_PROVIDER does not work in bound place. So if gps_provider is enabled but you get null location you can replace provider from gps to NETWORK_PROVIDER.
prasad try this code ..by using this i am successfully getting lat long
private Location location = null;
private LocationManager locationManager = null;
locationManager = (LocationManager) context.getSystemService (Context.LOCATION_SERVICE);
Criteria locationCritera = new Criteria();
locationCritera.setAccuracy(Criteria.ACCURACY_FINE);
locationCritera.setAltitudeRequired(false);
locationCritera.setBearingRequired(false);
locationCritera.setCostAllowed(true);
locationCritera.setPowerRequirement(Criteria.NO_REQUIREMENT);
String providerName = locationManager.getBestProvider(locationCritera,
true);
location = locationManager.getLastKnownLocation(providerName);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locationListener);
currentLocation = context.getSharedPreferences(PREFS_NAME, 0);
editor = currentLocation.edit();
}
public String getCurrentLatitude() {
try {
if (!currentLocation.getString("currentLatitude", "")
.equalsIgnoreCase(""))
return currentLocation.getString("currentLatitude", "");
else if (location.getLatitude() != 0.0)
return Double.toString(location.getLatitude());
else
return "0.0";
} catch (Exception e) {
e.printStackTrace();
}
return "0.0";
}
public String getCurrentLongitude() {
try {
if (!currentLocation.getString("currentLongitude", "")
.equalsIgnoreCase(""))
return currentLocation.getString("currentLongitude", "");
else if (location.getLongitude() != 0.0)
return Double.toString(location.getLongitude());
else
return "0.0";
} catch (Exception e) {
e.printStackTrace();
}
return "0.0";
}
are you trying on emulator or device. if you are trying in device then your device should have to be near window or in open place.
override these methods in your MyLocationListener. so that you can track your GPS status. check and see if you can get whats the problem
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Disabled",
Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
On a real device, you will have to be patient and wait for a fix from the satellites. This can take several minutes, even with a clear view of the sky.
For testing outside, you would be better advised to have a simple text box in your app, initialise it to something like "No GPS fix yet", then send a string comprised of the lat/long coordinates to it when the location changes.
Maybe this is more clear. I will change the conditional to something more efficient later if it is possible
double longitude = 0;
double latitude = 0;
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) != null) {
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
} else {
Location location = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
}
There are two types of location providers,
GPS Location Provider
Network Location Provider
package com.shir60bhushan.gpsLocation;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import android.util.Log;
public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}
This Link can help you for more information
http://androidtutorials60.blogspot.in/2013/09/gps-current-location-of-device.html