ANDROID locationManager.requestLocationUpdates cannot be resolved? - android

I don't understand why locationManager.requestLocationUpdates cannot be resolved. I searched up the answer and it says you must import LocationClient which is not in use anymore.
Here is how I find my current location method. Please tell me if I am missing anything.
private void setUpMap() {
// Enable MyLocation Layer of Google Map
mMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria,true);
LocationListener locationChangeListener = new LocationListener() {
public void onLocationChanged(Location l) {
if (l != null) {
Log.i("SuperMap", "Location changed : Lat: " + l.getLatitude() + " Lng: " +
l.getLongitude());
}
}
public void onProviderEnabled(String p) {
}
public void onProviderDisabled(String p) {
}
public void onStatusChanged(String p, int status, Bundle extras) {
}
};
locationManager.requestLocationUpdates(provider,0,0,locationChangeListener);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
// set map type
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location
double latitude = myLocation.getLatitude();
// Get longitude of the current location
double longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng 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(14));
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!").snippet("Consider yourself located"));
}
}
Here are my imports
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.GeofencingApi;

Import LocationListener interface from android.location package because currently you are importing from com.google.android.gms.location package but requestLocationUpdates method takes android.location.LocationListener as last parameter.
Change :
import com.google.android.gms.location.LocationListener;
to
import android.location.LocationListener;

Related

Start map with current location

I want the map in this application to start with the current location of the user but it keeps starting with the default location being the location with latitude = 0 and longitude = 0.
It also doesn't work when I walk around with phone in hand..
This is my code:
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements LocationListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private LocationManager locationManager;
private double longitude;
private double latitude;
public Criteria criteria;
public String bestProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
getLocation();
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
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();
}
}
}
protected void getLocation() {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();
//You can still do this if you like, you might get lucky:
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
Log.e("TAG", "GPS is on");
latitude = location.getLatitude();
longitude = location.getLongitude();
}
else{
//This is what you need:
locationManager.requestLocationUpdates(bestProvider, 1000, 0, this);
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My Location"));
}
#Override
public void onLocationChanged(Location location) {
//remove location callback:
locationManager.removeUpdates(this);
//open the map:
latitude = location.getLatitude();
longitude = location.getLongitude();
}
// ... other LocationListener methods that I left empty. I removed to shorten the code
}
}
Could you please tell me where's the problem? I've tried many fixes from StackOF but I couldn't get it to work.

Problems with writing JSON objects into a file

I'm writing a small application that get your location every 10 seconds and puts Latitude and Longitude into a JSON object. Than it should write Lat and Lon into a file in External Storage. I made run the application and I can see the file.json but there's only a string Lon into. Instead it should write a couple of values Lon Lat every time the location changes. What is the problem?
Here is the code:
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Logger;
public class MainActivity extends AppCompatActivity 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;
JSONObject jsonObject;
FileOutputStream outputStream;
String latlon;
String filename;
File sdCardFile;
FileWriter fw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
filename="salvataggi.json";
sdCardFile = new File(getExternalFilesDir(null), filename);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, this);
}
#Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
try {
jsonObject = new JSONObject();
jsonObject.put("Lat", location.getLatitude());
jsonObject.put("Lon", location.getLongitude());
latlon=jsonObject.toString();
writeToFile(latlon, sdCardFile, fw);
}catch (JSONException je) { }
}
public static void writeToFile(String latlon, File sdCardFile, FileWriter fw) {
try{
fw = new FileWriter(sdCardFile, true);
fw.write(latlon);
fw.flush();
fw.close();
}catch(Exception e){
e.printStackTrace();
}
}
Where am I doing wrong?
When you request location updates at a certain interval, you have no guarantee that you will receive updates at exactly that interval. According to the javadoc, all you can be certain of is that the updates will occur no faster than the given time duration. If the GPS isn't getting updated locations, the listener may never be called at all. It can take some time to get a GPS lock in the first place.
If you really need to provide some coordinate every 10 seconds, consider using a Handler to schedule a Runnable every 10 seconds that polls the value of getLastKnownLocation and makes sure the return value is not null. That returned Location may not be accurate, but it's at least something.

how to put a geopoint from user current location in parse.com

So i am new to database programming as well as android programming, i am trying to get a user's location and store the location into the parse.com database. I believe my code is along the right path, can someone assist me with the issue?
import android.content.Context;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseObject;
import com.parse.SaveCallback;
import com.parse.SignUpCallback;
public class MapsActivity extends FragmentActivity implements RoutingListener {
protected GoogleMap mMap;
protected LatLng start;
protected LatLng end;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mMap = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
try {
setUpMapIfNeeded();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
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();
}
}
}
private void setUpMap() {
// Enable MyLocation Layer of Google Map
mMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
// set map type
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
double longitude = location.getLongitude();
double latitude = location.getLatitude();
// Get longitude of the current location
String userId = "O6pGXcJy3C";
//String username = "Nick";
ParseObject globeobject = new ParseObject("global");
globeobject.put("username","Alana");
globeobject.put("userID",userId);
final ParseGeoPoint point = new ParseGeoPoint(latitude, longitude);
globeobject.put("Location", point);
}
}
#Override
public void onRoutingFailure() {
// The Routing request failed
}
#Override
public void onRoutingStart() {
// The Routing Request starts
}
}
I believe you have done the needful.
At the of "final ParseGeoPoint point = new ParseGeoPoint(latitude, longitude);
globeobject.put("Location", point);" lines put
globeobject.saveInBackground();

Error in marker options icon

I want to get the current location of the user by using Google Maps V2. I get this error, the method icon(bitmapdescriptor) is undefined for the type marker.
This is my code based on android + google map api v2 + current location
import android.app.Dialog;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
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.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}
else{ // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Google Map object from the fragment
GoogleMap googleMap = fm.getMap();
// Enabling MyLocation Layer of Google
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting current location
Location location = locationManager.getLastKnownLocation(provider);
LocationListener locationListener = new LocationListener(){
public void onLocationChanged(Location location){
// Redraw the marker when get location update
drawMarker(location);
}
#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
}
};
if(location!=null){
// Place the initial marker
drawMarker(location);
}
locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
}
}
private void drawMarker(Location location){
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
GoogleMap googleMap = fm.getMap();
googleMap.clear();
LatLng currentPosition = new LatLng(location.getLatitude(),location.getLongitude());
googleMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat:" + location.getLatitude() + "Lng" + location.getLongitude()))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title("ME");
}
And if i replace .icon with .setIcon, the whole new MarkerOptions() is in red and I get this error, Cannot invoke title(String) on the primitive type void. What should I do?
You have misplaced a parenthesis when creating your marker, therefore methods icon and title are unrecognized.
Replace your code to:
mMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat:" + location.getLatitude() + "Lng" + location.getLongitude())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title("ME"));
This was pretty obvious as MarkerOptions object doesn't have a setIcon method, but a Marker has one. And adding a MarkerOptions to the map returns a Marker object :-)
Just for clarification, you could set the icon like this:
Marker myMarker = mMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat:" + location.getLatitude() + "Lng" + location.getLongitude())
.title("ME"));
myMarker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));

Android get location from cell tower

Hi I want to get location from cell tower(Sim card) without internet. I had used below mentioned code it's give me only last location when network available.
my requirement is to get location without WiFi or internet. can it's possible?
package com.example.gpscelltower;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class CellTowerActivity1 extends Activity {
private static final String TAG = "Cell";
private static LocationManager locationManager;
private static LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cell_tower);
locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
String providerName=LocationManager.NETWORK_PROVIDER;
Location location=locationManager.getLastKnownLocation(providerName);
updateWithLocation(location);
//Cell-ID and WiFi location updates.
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.d("TAG", "locationListner");
updateWithLocation(location);
String Text = "My current location is: " + "Latitude = "+ location.getLatitude() + "Longitude = " + location.getLongitude();
Toast.makeText(getApplicationContext(), Text, Toast.LENGTH_LONG).show();
Log.d("TAG", "Starting..");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("TAG", "onSatatus");
}
public void onProviderEnabled(String provider) {
Log.d("TAG", "onProviderEnable");
}
public void onProviderDisabled(String provider) {
Log.d("TAG", "onProviderDisble");
}
};
}
private void updateWithLocation(Location location) {
Log.d("TAG", "UpdateWithLocation");
String displayString;
if(location!=null){
Double lat=location.getLatitude();
Double lng=location.getLongitude();
Long calTime=location.getTime();
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(calTime);
String time=formatter.format(calendar.getTime()).toString();
displayString="The Lat: "+lat.toString()+" \nAnd Long: "+lng.toString()+"\nThe time of Calculation: "+time;
}else{
displayString="No details Found";
}
Toast.makeText(CellTowerActivity1.this, ""+displayString, Toast.LENGTH_LONG).show();
}
}
Cell geolocation works through sending Cell towers IDs to server which maps it to coordinates. So, unfortunately it's not posssible to get your coordinates w/o data connection with standard APIs.

Categories

Resources