i have this code:
if (item.getItemId() == R.id.tempMap) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = null;
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)||locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
if (location != null) {
Log.e("PROVIDER SCELTO", provider);
onLocationChanged(location);
Log.e("LATITUDE", String.valueOf(latitude));
Log.e("LONGITUDE", String.valueOf(longitude));
and:
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
latitude = location.getLatitude();
longitude = location.getLongitude();
}
but the last gps point that it return is the last point after i use the "google maps navigator". So, if i not use gm navigator, the latitude and longitude is not updated.
WHY???
Thank you
location fix requires time wait till a good fix is recived this checks the time of the fix and sets location only if the fix is within a time period if you dont check the time of the fix it will provide the last fix recived irespective of when
public void onLocationChanged(Location location) {
Date dd=new Date(location.getTime());
Date ddd=new Date(System.currentTimeMillis()-(1000*60*15));
Log.e("", String.valueOf(location.getTime()+":"+System.currentTimeMillis()+":"+dd+":"+ddd));
if (dd.compareTo(ddd)==1?true:false) {
got=true;
latitude=String.valueOf(location.getLatitude());
longitude=String.valueOf(location.getLongitude());}
}
Related
Im facing some problem with my application, specifically with route plot/draw on my google maps. Ive made test route around my house and found out, that GPS providers are not as accurate as similar applications like runtastic or endomondo.
Sometimes Location listener makes incomprehensible changes on my map and the polyline then draws any lines on the map near my location even with perfect GPS signal.
Some other time, it just doesnot work. It does not listen to location change.
Can anybody explain me (like Im five) how does other fitness application get their current position and the plot route onto the google map? Thanks!
//Map Fragment
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.fragment1)).getMap();
map.setMyLocationEnabled(true);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
//Permission gain
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSION_ACCESS_COURSE_LOCATION);
return;
}
isLocationEnabled(getApplicationContext());
Location myLocation = locationManager.getLastKnownLocation(provider);
if (myLocation != null) {
latitude = myLocation.getLatitude();
longitude = myLocation.getLongitude();
float zoom = (float) 17.0;
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), zoom));
Log.e("TAG", "GPS is on");
Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
} else {
locationManager.requestLocationUpdates(provider, 5000, 0, this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10, this);
}
public void onLocationChanged(Location mylocation) {
if (lastLocationloc == null) {
lastLocationloc = mylocation;
}
LatLng lastLatLng = locationToLatLng(lastLocationloc);
LatLng thisLatLng = locationToLatLng(mylocation);
map.addPolyline(new PolylineOptions().add(lastLatLng).add(thisLatLng).width(6).color(Color.RED));
lastLocationloc = mylocation;
Toast.makeText(MainActivity.this, "!!!!Location CHANGE!!!!", Toast.LENGTH_SHORT).show();
}
public static LatLng locationToLatLng(Location loc) {
if (loc != null)
return new LatLng(loc.getLatitude(), loc.getLongitude());
return null;
}
For example, I want to plot it like this:
But my application works its own way..
First of all, you need to take into account the accuracy of the received location. You can get the accuracy using the Location.getAccuracy() method (documentation). The accuracy is measured in meters, so the lower the better:
if (location.getAccuracy() < MINIMUM_ACCURACY) {
// Add the new location to your polyline
}
You can set your MINIMUM_ACCURACY to be 10 meter for example.
On the other hand, you may want to add a new location to your polyline only if your new location is farther than a given distance to your last added location. As an example:
private static final float MINIMUM_ACCURACY = 10;
private static final float MINIMUM_DISTANCE_BETWEEN_POINTS = 20;
private Location lastLocationloc;
// ...
public void onLocationChanged(Location mylocation) {
if (mylocation.getAccuracy() < MINIMUM_ACCURACY) {
if (lastLocationloc == null || lastLocationloc.distanceTo(mylocation) > MINIMUM_DISTANCE_BETWEEN_POINTS) {
// Add the new location to your polyline
lastLocationloc = mylocation;
}
}
}
I have implemented the Google Maps API v2 in my Android app. I add a marker and zoom to level 14 when I open the activity containing the map fragment.
Here is how I add/update the marker:
private void updateMarker() {
if(marker != null){
marker.remove();
}
LatLng latlng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
marker = mMap.addMarker(new MarkerOptions().position(latlng).title(username));
marker.setIcon((BitmapDescriptorFactory.fromResource(R.drawable.marker)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(zoom), 2000, null);
}
It works correctly in debug via Android Studio, using a Nexus 5 with the latest Android installed. The problem is when I run a release build. The marker is added in the correct place, the zoom animation works correctly, zooming to the correct level. But it doesn't move to the marker I added.
Use this
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, zoom));
Or
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng, zoom), 2000, null);
Don't call both method right after each other.
you should pass the result value of CameraUpdateFactory.newLatLngZoom(latlng, zoom) to animateCamera which returns a CameraUpdate that moves the center of the screen to a latitude and longitude specified by a LatLng object, and moves to the given zoom level. You can read more about it here
Implement GoogleApiClient.ConnectionCallbacks and override onConnected method as follows:
#Override
public void onConnected(Bundle bundle) {
Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mGMLastKnownLocation = LocationServices.FusedLocationApi.getLastLocation(mGMGoogleApiClient);
try {
// Get LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled)
{
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
//You can still do this if you like, you might get lucky
mGMLastKnownLocation = locationManager.getLastKnownLocation(provider);
if (mGMLastKnownLocation != null) {
//place marker at current position
mMap.clear();
// Get latitude of the current location
double latitude = mGMLastKnownLocation.getLatitude();
// Get longitude of the current location
double longitude = mGMLastKnownLocation.getLongitude();
// Create a LatLng object for the current location
latLng = new LatLng(latitude, longitude);
// Show the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(7));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(new LatLng(latitude, longitude)).title("You are here!").snippet("Consider yourself located").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
mCurrLocation = mMap.addMarker(markerOptions);
} else {
mGMLocationRequest = new LocationRequest();
mGMLocationRequest.setInterval(5000); //5 seconds
mGMLocationRequest.setFastestInterval(3000); //3 seconds
mGMLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGMGoogleApiClient, mGMLocationRequest, this);
}
} else {
//prompt user to enable location
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
}
} catch (Exception e) {
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
}
Also, implement LocationListener and override the onLocationChanged method as follows:
#Override
public void onLocationChanged(Location location) {
//remove previous current location marker and add new one at current position
if (mCurrLocation != null) {
mCurrLocation.remove();
}
double latitude = location.getLatitude();
double longitude = location.getLongitude();
latLng = new LatLng(latitude, longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(new LatLng(latitude, longitude)).title("Position").snippet("I am here").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
mCurrLocation = mMap.addMarker(markerOptions);
Toast.makeText(this, "Location Changed", Toast.LENGTH_SHORT).show();
//If you only need one location, unregister the listener
LocationServices.FusedLocationApi.removeLocationUpdates(mGMGoogleApiClient, this);
}
I hope it helps!!
I need to display users current locations using gps. At startup it displays some random location in sea and when i'll click to gps icon it displays my current location (white circle with optic icon).
How can I do to display that on startup? I'm new at android/java so feel free to correct me anything.
my code is:
public class MainMapsActivity extends FragmentActivity implements android.location.LocationListener {
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_maps);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = fm.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
}
Create a data member of Location class.
public static Location mLocation;
use OnMyLocationChangeListener on Map
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
mLocation = location;
displayCurrentLocation();
}
});
public void displayCurrentLocation(){
CameraPosition cameraPosition = new CameraPosition.Builder().
target(new LatLng(mLocation.getLatitude(), mLocation.getLongitude())).
tilt(60).
zoom(15).
bearing(0).
build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
hope it will works.
You can achieve this in two ways
Run a service (background operation) and get current latitude and longitude at the app starting itself , before coming to the targeted screen
Expose methods in service which you can access from Activity
Show users current location from the service method input
Or else implement a listener which will every time update the users current location
You can refer the following Example 1 and Example 2
I'm trying to get a user's location and I have this method
public Location getCurrentLocation() {
LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locManager.getBestProvider(criteria, true);
Location location = locManager.getLastKnownLocation(provider);
return location;
}
I have another method that will center a circle object based on the location variable's latitude and longitude in this method
private void loadMapResources() {
userLocation = getCurrentLocation();
//DRAW CIRCLE HERE
if(userRadius != 0){
Circle radiusCircle = googleMap.addCircle(new CircleOptions()
.center(new LatLng(userLocation.getLatitude(), userLocation.getLongitude()))
.radius(userRadius)
.strokeWidth(4)
.strokeColor(Color.parseColor("#FF6699"))
.fillColor(Color.parseColor("#66F3F3F3"))
);
//SHOW USER ICON AT CURRENT LOCATION
BitmapDescriptor userIcon = BitmapDescriptorFactory.fromResource(R.drawable.ic_user);
googleMap.addMarker(new MarkerOptions()
.title("YOU ARE HERE")
.icon(userIcon)
.position(new LatLng(userLocation.getLatitude(), userLocation.getLongitude()))
);
}
}
Now this code has worked before on devices with and without GPS. Could anyone tell me why userLocation is throwing a NullPointerException?
Please keep in mind, that getLastKnownLocation can sometimes return null (for example, if provider is currently disabled or there is no last known location), so you should always check the result of this method:
Location location = locManager.getLastKnownLocation(provider);
if (location == null){
//handle this case
//return location with some default coordinates, for example
}
return location;
I am getting the longitude and latitude of my device, but it takes at 30 seconds to a minute to do so. Any suggestions to cut the time down?
public class MainActivity extends Activity
{
public String zipcode;
public double latG;
public double lonG;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.getLastKnownLocation(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener()
{
public void onLocationChanged(Location location)
{
if (location != null)
{
latG = location.getLatitude();
lonG = location.getLongitude();
Toast.makeText(MainActivity.this,
latG + " " + lonG,
Toast.LENGTH_LONG).show();
}
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try
{
addresses = geocoder.getFromLocation(latG, lonG, 1);
}
catch (IOException e)
{
Context context = this;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle("Error");
alertDialogBuilder.setMessage("Error in getting address information.");
alertDialogBuilder.setCancelable(true);
}
for (Address address : addresses)
{
if(address.getPostalCode() != null)
{
zipcode = address.getPostalCode();
Toast.makeText(MainActivity.this, zipcode, Toast.LENGTH_LONG).show();
break;
}
}
}
}
You are using GPS_PROVIDER for fetching the GPS data. GPS_PROVIDER fetches details directly from the satellite so it takes time for the first time you load this. Moreover GPS_PROVIDER takes more than 30 seconds if your are not below the open sky. GPS_PROVIDER may return NULL when you are inside the office or in basement.
There is an alternative way for this is to use NETWORK_PROVIDER. This provider will give you GPS details based on your current Network state. This will not be much accurate like GPS_PROVIDER but it works faster.
hi you are using GPS PROVIDER which can take some time as it depends on several constraints like yours building position, physical position, weather as gps data is available from the satellite so use a network provider which may faster in yours case please have a look on the given code snippet at
http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/
Best option is to use Google Play Services and its LocationClient.
http://developer.android.com/google/play-services/location.html
This gives you a provider that automatically picks the best available information from all the provider types and can return the location immediately in some cases using getLastLocation()
try to run it in device rather than running it in the emulator.
try this
try {
gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {}
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
It will give the response what ever the service is available.Even you can place your priority
Use this code to fetch faster,
String provider;
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
if (provider != null && !provider.equals("")) {
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
if (location != null)
{
onLocationChanged(location);
//your remaining code
}