I'm developing an app that uses the Google Maps V2 API and I'm having trouble do get my coordinates and to put it into the LatLng object... Here's my code:
public class TelaMapa extends android.support.v4.app.FragmentActivity
implements OnMapClickListener, OnCameraChangeListener{
// Google Map
protected GoogleMap googleMap;
private SupportMapFragment mapFragment;
protected AndroidLocationSource locationSource;
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_mapa);
}
#Override
protected void onResume(){
super.onResume();
configureMap();
}
/**
* function to load map. If map is not created it will create it for you
* */
private void configureMap() {
if (googleMap == null) {
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
googleMap = mapFragment.getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
LocationManager LM = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String bestProvider = LM.getBestProvider(new Criteria(),true);
Location localAtu;
/*Location myLocation = LM.getLastKnownLocation(bestProvider);
double lat= myLocation.getLatitude();
double lng = myLocation.getLongitude();
LatLng latLng = new LatLng(lat, lng);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 20));*/
if(bestProvider != null){
localAtu = LM.getLastKnownLocation(bestProvider);
} else {
localAtu = LM.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
LatLng latLng;
if(localAtu != null){
latLng = new LatLng(localAtu.getLatitude(), localAtu.getLongitude());
final CameraPosition position = new CameraPosition.Builder()
.target(latLng)
.bearing(0)
.tilt(0)
.zoom(17)
.build();
CameraUpdate update = CameraUpdateFactory.newCameraPosition(position);
googleMap.moveCamera(update);
adicionarMarcador(googleMap, latLng);
locationSource = new AndroidLocationSource();
googleMap.setLocationSource(locationSource);
locationSource.setLocation(latLng);
} else {
Toast.makeText(getApplicationContext(),
"GPS desligado ou indisponível!", Toast.LENGTH_LONG)
.show();
}
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Desculpe! Não foi possível criar o mapa!", Toast.LENGTH_SHORT)
.show();
}
}
}
That's it, I installed it in my Motorola Atrix and it always show me the toast in the else
block... Thanks for reading!
Answered by Sanket Kachhela!
Just use this tutorial and it will work fine!
androidhive.info/2012/07/android-gps-location-manager-tutorial
Related
It is drawing a polyline based on where the user was and now is but for some reason it creates another line which points from the new LatLng to the Origin(Where the user started) LatLng
I am trying to figure out why but I am struggling to find the problem in my code
As you can see it draws a line as the user moves but on each new latlng it draws this really straight line to the latlng
Please Note: Yes I know some of the code I am using in LocationRequest is deprecated I will update it in the final version
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private PolylineOptions polylineOptions;
private Polyline polyline;
private List<LatLng> points;
private LocationCallback locationCallback;
private FusedLocationProviderClient mFusedLocationClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
mMap.setMyLocationEnabled(true);
mFusedLocationClient.requestLocationUpdates(getLocationRequest(), locationCallback, Looper.myLooper());
}
}
});
points = new ArrayList<>();
polylineOptions = new PolylineOptions();
polylineOptions.color(Color.BLUE);
polylineOptions.width(5);
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult != null) {
Location location = locationResult.getLastLocation();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
points.add(latLng);
polylineOptions.addAll(points);
if (polyline != null) {
polyline.remove();
}
polyline = mMap.addPolyline(polylineOptions);
}
}
};
}
private LocationRequest getLocationRequest() {
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(10);
locationRequest.setFastestInterval(3000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
return locationRequest;
}
}
In Theory:
The app should draw a simple polyline based on where the user was and where they are now(simple right?)
Reality:
It is drawing a polyline based on where the user was and now is but for some reason it creates another line which points from the new LatLng to the Origin(Where the user started) LatLng
Tried:
Tried to find anything on the google docs even tried ChatGPT(not going to lie) but I can't find a solution.
I was trying to make a map activity app which when run, displays user's GPS' location on a map using a marker. However, on running, it just displays the marker in the default location (Sydney) please help. Below is my code.. I have tried a number of ways but all of them still lead me to Sydney. What Im trying to do is for the app to take me directly to my location once run.
Below is my code;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_real_time_location);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PackageManager.PERMISSION_GRANTED);
}
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
try {
latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("My Current Position"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
catch (SecurityException e){
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_UPDATE_TIME, MIN_UPDATES_DISTANCE, locationListener);
}
catch (SecurityException e){
e.printStackTrace();
}
}
Use LocationCallback instead to get your latest location:
LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
//The last location in the list is the newest
Location location = locationList.get(locationList.size() - 1);
Log.i(TAG, "Location " + location.getLatitude() + " " + location.getLongitude());
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Create instance for current user lat and lng
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
// Add user position marker
currentUserPositionMarker(latLng);
//move map camera
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, CURRENT_MAP_ZOOM));
}
}
};
/**
* Add Marker for user current position
*
* #param latLng current lat and lng of user
*/
private void currentUserPositionMarker(LatLng latLng) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(CURRENT_POSITION);
mCurrLocationMarker = gMap.addMarker(markerOptions);
//move map camera
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, CURRENT_MAP_ZOOM));
}
#Override
public void onPause() {
super.onPause();
if (mFusedLocationProviderClient != null) {
mFusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
}
}
#SuppressLint("MissingPermission")
#Override
public void onMapReady(GoogleMap googleMap) {
gMap = googleMap;
gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
gMap.getUiSettings().setMapToolbarEnabled(false);
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(SET_INTERVAL_FOR_ACTIVE_LOCATION_UPDATES); // 3 seconds interval
mLocationRequest.setFastestInterval(SET_INTERVAL_FOR_ACTIVE_LOCATION_UPDATES);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (isFineLocationPermissionGranted())
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
You need to get the last known location of the device, use this link to get the last known location, and then display the marker where you want.
got an error at line "Location.distanceBetween(LatLng.latitude, LatLng.longitude, circle.getCenter().latitude,circle.getCenter().longitude,distance);" LatLng.latitude and LatLng.longitude cant be used because not specific values.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{//DirectionFinderListener {
private GoogleMap mMap;
//private Button btnFindPath;
//private EditText etOrigin;
//private EditText etDestination;
private List<Marker> originMarkers = new ArrayList<>();
private List<Marker> destinationMarkers = new ArrayList<>();
// private List<Marker> = new ArrayList<>();
Circle shape;
Marker marker;
//private List<Polyline> polylinePaths = new ArrayList<>();
private ProgressDialog progressDialog;
long minDistance = 15;
float[] distance = new float[2];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//btnFindPath = (Button) findViewById(R.id.btnFindPath);
//etOrigin = (EditText) findViewById(R.id.etOrigin);
//etDestination = (EditText) findViewById(R.id.etDestination);
/*btnFindPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendRequest();
}
});*/
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng hcmus = new LatLng(3.719639, 103.123972); //3.719639, 103.123972
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(hcmus, 18));
originMarkers.add(mMap.addMarker(new MarkerOptions()
.title("IBM CoE")
.position(hcmus)));
Circle circle = mMap.addCircle(new CircleOptions()
.center(new LatLng(3.719639, 103.123972))
.radius(10000)
.strokeColor(Color.RED)
.fillColor(Color.BLUE));
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
Location.distanceBetween(LatLng.latitude, LatLng.longitude, circle.getCenter().latitude,circle.getCenter().longitude,distance);
if ( distance[0] <= circle.getRadius())
{
Toast.makeText(this, "You are in radius location", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "You are not in radius location", Toast.LENGTH_LONG).show();
}
/*if (destinationMarkers == ) { //equation
Intent main = new Intent(MapsActivity.this, MainActivity.class);
startActivity(main);
}
else { Toast.makeText(this, "You are not in radius location", Toast.LENGTH_LONG).show();
}*/
}
How to get current Location latitude and longitude
See the parameter of doc of distanceBetween method. It results distance in meter between two locations and it takes parameters like this,
startLatitude double: the starting latitude
startLongitude double: the starting longitude
endLatitude double: the ending latitude
endLongitude double: the ending longitude
results float: an array of floats to hold the results
As its clearly stated, the first two parameters hold the value of first location object's Latitude and Longitude. In your case, you're referring the default Location object's Latitude and Longitude properties which doesn't represent any location value.
I can see you're already getting current location
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
So, this line should be like this,
Location.distanceBetween(latitude, longitude, circle.getCenter().latitude,circle.getCenter().longitude, distance);
So I wrote a class that will find the users location and find the distance between that and another point but I have a random number generator so when I call I use method I use in my activity (restarting the activity) the random number changes which I don't want to happen. If anyone would show me how to refresh the users location on the click of the button without restarting the whole activity it would be a great help
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
//These variable are initalized here as they need to be used in more than one methid
private double currentLatitude; //lat of user
private double currentLongitude; //long of user
Random rand = new Random();
int n = rand.nextInt(5) + 1;
int score = 0;
public static final String TAG = MapsActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
//contains lat and lon of another place
private void setUpMap() {
if (n == 1) {
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeVillageApartmets, longitudeVillageApartments)).title("1"); //create marker
mMap.addMarker(marker); // adding marker
} else if (n == 2) {
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeSU, longitudeSU)).title("2"); //create marker
mMap.addMarker(marker); // adding marker
} else if (n == 3) {
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeArtsBuilding, longitudeArtsBuilding)).title("3"); //create marker
mMap.addMarker(marker); // adding marker
} else if (n == 4) {
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeJH, longitudeJH)).title("4"); //create marker
mMap.addMarker(marker); // adding marker
} else if (n == 5) {
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeForebell, longitudeForebell)).title("5"); //create marker
mMap.addMarker(marker); // adding marker
}
}
//contains your lat and lon
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
//mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location"));
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("You are here");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom((latLng), 11.0F));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
//Refresh button. Will reset the location of your flag
//If the user clicks the button, the activity is finished and restarted
Button button2=(Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick (View w){
Intent intent = getIntent();
finish();
startActivity(intent);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
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();
}
}
}
#Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
Note if there's a problem with the code I delete a lot of it so it's only brackets and stuff. I just posted all this so you have an idea what's happening. I only want to refresh your location, not the entire activity
Intent intent = getIntent();
finish();
startActivity(intent);
Can you try this one ? I did not test it.
MarkerOptions markerOptions;
Marker marker;
private void setUpMap() {
if(marker!= null)
marker.remove();
markerOptions = null;
if (n == 1) {
markerOptions = new MarkerOptions().position(new LatLng(latitudeVillageApartmets, longitudeVillageApartments)).title("1"); //create marker
} else if (n == 2) {
markerOptions = new MarkerOptions().position(new LatLng(latitudeSU, longitudeSU)).title("2"); //create marker
} else if (n == 3) {
markerOptions = new MarkerOptions().position(new LatLng(latitudeArtsBuilding, longitudeArtsBuilding)).title("3"); //create marker
} else if (n == 4) {
markerOptions = new MarkerOptions().position(new LatLng(latitudeJH, longitudeJH)).title("4"); //create marker
} else if (n == 5) {
markerOptions = new MarkerOptions().position(new LatLng(latitudeForebell, longitudeForebell)).title("5"); //create marker
}
if(markerOptions!=null)
marker = mMap.addMarker(markerOptions); // adding marker
}
And on your onclicklistener
button2.setOnClickListener(new View.OnClickListener() {
public void onClick (View w){
n = rand.nextInt(5) + 1;
setUpMap();
}
});
Or you can use marker.setPosition(LatLng); if your marker is not null
I'm trying to get the coordinates but without success. The result is 0 . But when I write:
googleMap.setMyLocationEnabled(true);
I can see the blue dot. I'm trying to get these values with this code:
lat = googleMap.getMyLocation().getLatitude();
lng = googleMap.getMyLocation().getLongitude();
After that, lat and lng are 0.
My whole code:
public class GPS_maps extends Activity {
// Google Map
private GoogleMap googleMap;
static Location currentLocation;
static double lat , lng;
TextView coordinates;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
coordinates = (TextView) findViewById(R.id.txt_coordinates);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// googleMap.setMyLocationEnabled(true);
lat = googleMap.getMyLocation().getLatitude();
lng = googleMap.getMyLocation().getLongitude();
coordinates.setText(String.valueOf(lat) +" , " +String.valueOf(lng));
LatLng coordinate = new LatLng(lat, lng);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 5);
googleMap.animateCamera(yourLocation);
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}}
}
I don't get any errors. Where is my mistake?
Try the following:
Remove static modifier from the declaration of lat, lan.
Make sure you are sending in the correct syntax to setCoordiante.
To make sure the lat and lan are right, print them out right after you get them.