GoogleMaps API can't get current latitude and longitude - java

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.

Related

How to get my location? [duplicate]

This question already has answers here:
How to calculate distance between two locations using their longitude and latitude value
(14 answers)
Closed 5 years ago.
I am new with maps in android i have this code :
enter codepublic class MapsActivity extends FragmentActivity implements GoogleMap.OnMyLocationButtonClickListener,
GoogleMap.OnMyLocationClickListener,
OnMapReadyCallback {
private GoogleMap mMap;
Button req_button;
String[] lat;
String[] lon;
String[] id;
String[] emails;
double latitude,lonitude;
int result_search,StatusChange_customer;
String params_search ,Status_cheked_customer,params_checked_customer,Status_cheked_customer_rating;
public Handler mHandler;
Location location;
#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);
Intent intent1 = getIntent();
lat = intent1.getStringArrayExtra("latitute");
lon = intent1.getStringArrayExtra("longitude");
id = intent1.getStringArrayExtra("id");
emails = intent1.getStringArrayExtra("emails");
latitude=intent1.getDoubleExtra("MyLat",0);
lonitude=intent1.getDoubleExtra("MyLon",0);
req_button =(Button)findViewById(R.id.R_id);
this.mHandler = new Handler();
this.mHandler.postDelayed(m_Runnable,5000);
}
private final Runnable m_Runnable = new Runnable()
{
public void run()
{
Search_for_Accepted_Job();
Toast.makeText(MapsActivity.this,"in runnable",Toast.LENGTH_SHORT).show();
MapsActivity.this.mHandler.postDelayed(m_Runnable, 10000);
}
};
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng [] sydeny = new LatLng[lat.length];
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// Add a marker in Sydney and move the camera
for (int i=0 ; i< lat.length;i++) {
sydeny[i] = new LatLng(Double.parseDouble(lat[i]), Double.parseDouble(lon[i]));
}
for (int i=0 ; i< sydeny.length;i++) {
mMap.addMarker(new MarkerOptions().position(sydeny[i]).title(emails[i]+ " " + id[i]));
// mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydeny[i], 5));
}
LatLng sydeny1 = new LatLng(latitude,lonitude);
mMap.addMarker(new MarkerOptions().position(sydeny1).title("Your location" ));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydeny1, 5));*/
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
}
public void Request(View view) {
Toast.makeText(this," Request",Toast.LENGTH_SHORT).show();
for (int i=0; i< lat.length;i++)
{
send_request(id[i]);
}
req_button.setEnabled(false);
}
#Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
return false;
}
#Override
public void onMyLocationClick(#NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
lonitude=location.getLatitude();
lonitude=location.getLongitude();
}
So this code take a latitude and longitude from another activity and present them in Map , recently i tried to implement two interfaces
(GoogleMap.OnMyLocationButtonClickListener
GoogleMap.OnMyLocationClickListener)
and i get my location with blue circle in map and change at real time with me and there is a method named
public void onMyLocationClick(#NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
my Question is how to use the latitude and longitude of this method , i mean how to get the latitude and longitude of my location because it is correct i i will need it to calculate the distance between me and other places .
To correctly use location in your app, you need to handle asking user permission to turn on location in settings (in case it is turned off) and then follow the steps in the documentation:
https://developer.android.com/training/location/retrieve-current.html
To answer your question exactly, did you try location.getLatitude() and location.getLongitude()?

LatLng.latitude and LatLng.longitude cant be used because not specific values

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);

Current location shows on emulator but not on phone

I am setting up my map to track my location. Right at the start I want it to detect my Lat and Long and show where I am and update the marker location when I move.
When I test this on GenyMotion emulator and input my own positions, it works and shows updated location accordingly. But when I test it on a mobile device, I do not get any marker and get the "Location null" Toast message.
Since it is the first time on the device, there is probably no last known location. Thus wanting to make sure, I took the device and moved a distance (probably 50 meters or so back n forth) and still nothing updated on the device.
public class TrackMapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
LocationManager locationManager;
Location location;
String provider;
Double lat, lng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track_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);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
try {
//Get last known user location
location = locationManager.getLastKnownLocation(provider);
if(location != null){
Toast.makeText(TrackMapsActivity.this, "Location NOT null", Toast.LENGTH_SHORT).show();
onLocationChanged(location);
}
else {
Toast.makeText(TrackMapsActivity.this, "Location null", Toast.LENGTH_SHORT).show();
}
}
catch (SecurityException e){
e.printStackTrace();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
protected void onResume() {
super.onResume();
try {
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
catch (SecurityException e){
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
try {
locationManager.removeUpdates(this);
}
catch (SecurityException e){
e.printStackTrace();
}
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(TrackMapsActivity.this, "You Moved", Toast.LENGTH_SHORT).show();
lat = location.getLatitude();
lng = location.getLongitude();
LatLng yourLocation = new LatLng(lat, lng);
if(mMap != null) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(yourLocation).title("Your Location"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(yourLocation, 10));
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
do you put the permission for using the gps :)
The main permissions you need are
android.permission.ACCESS_COARSE_LOCATION or
android.permission.ACCESS_FINE_LOCATION.

Can't get coordinates using LocationManager

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

How to plot on maps from arraylist with lon/lat?

This is my Map Class...
public class Mapa extends FragmentActivity implements LocationListener {
public GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mapa);
Getting Google Play availability status
int status =GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else {
Getting reference to the SupportMapFragment
SupportMapFragment fm = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
Getting GoogleMap object from the fragment
map = fm.getMap();
Enabling MyLocation Layer of Google Map
map.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);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
}
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
Getting latitude of the current location
double latitude = location.getLatitude();
Getting longitude of the current location
double longitude = location.getLongitude();
Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
Showing the current location in Google Map
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
Zoom in the Google Map
map.animateCamera(CameraUpdateFactory.zoomTo(15));
Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
And this is my class with the arraylist
public void getPontos(View view) {
String codigo;
codigo = linhaList.get(spinner.getSelectedItemPosition()).getCodigo();
new WebServiceGetPontosLinha().execute(codigo);
}
private class WebServiceGetPontosLinha extends
AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this, "",
getResources().getText(R.string.connecting), true, false);
}
#Override
protected Void doInBackground(String... params) {
WebServiceConsumer webServiceConsumer = new WebServiceConsumer(
MainActivity.this);
pontoList = webServiceConsumer.getPontos(params[0]);
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
pontoArrayAdapter = new ArrayAdapter<PontosLinhas>(
MainActivity.this,
android.R.layout.simple_spinner_dropdown_item, pontoList);
spinner1.setAdapter(pontoArrayAdapter);
}
}
How do I plot the content of spinner on maps like an image?
This involves a lot of details which is not needed for your but hope you get the picture.
I developed an app that among other things shows the location of hydrants on a map and this is how I load the hydrants to the map:
private class LoadHydrantsToMapTask extends
AsyncTask<Hydrant, Integer, List<MarkerOptions>> {
private int loadHydrantsGoal = 0;
public LoadHydrantsToMapTask(int loadHydrantsGoal) {
this.loadHydrantsGoal = loadHydrantsGoal;
}
// Before running code in separate thread
#Override
protected void onPreExecute() {
Device.lockOrientation((Activity)context);
// Create a new progress dialog.
progressDialog = new ProgressDialog(context);
// Set the progress dialog to display a horizontal bar .
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage(context
.getString(R.string.adding_hydrants));
// This dialog can't be canceled by pressing the back key.
progressDialog.setCancelable(false);
// This dialog isn't indeterminate.
progressDialog.setIndeterminate(false);
// The maximum number of progress items is 100.
progressDialog.setMax(loadHydrantsGoal);
// Set the current progress to zero.
progressDialog.setProgress(0);
// Display the progress dialog.
progressDialog.show();
}
// The code to be executed in a background thread.
#Override
protected List<MarkerOptions> doInBackground(Hydrant... hydrants) {
List<MarkerOptions> markers = new ArrayList<MarkerOptions>();
for (Hydrant hydrant : hydrants) {
final String hydrant_type = hydrant.getHydrantType();
final String hydrant_icon_path = hydrant.getIconPath();
double latitude = hydrant.getLatitude();
double longitude = hydrant.getLongitude();
final LatLng position = new LatLng(latitude, longitude);
final String address = hydrant.getAddress();
final String addressNumber = hydrant.getAddressNumber();
final String addressremark = hydrant.getAddressRemark();
final String remark = hydrant.getRemark();
BitmapDescriptor icon = BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED);
if (!hydrant_icon_path.isEmpty()) {
File iconfile = new File(hydrant_icon_path);
if (iconfile.exists()) {
BitmapDescriptor loaded_icon = BitmapDescriptorFactory
.fromPath(hydrant_icon_path);
if (loaded_icon != null) {
icon = loaded_icon;
} else {
Log.e(TAG, "loaded_icon was null");
}
} else {
Log.e(TAG, "iconfile did not exist: "
+ hydrant_icon_path);
}
} else {
Log.e(TAG, "iconpath was empty on hydrant type: "
+ hydrant_type);
}
StringBuffer snippet = new StringBuffer();
if (!address.isEmpty())
snippet.append("\n" + address + " " + addressNumber);
if (addressremark.isEmpty())
snippet.append("\n" + addressremark);
if (!remark.isEmpty())
snippet.append("\n" + remark);
markers.add(new MarkerOptions().position(position)
.title(hydrant_type).snippet(snippet.toString())
.icon(icon));
publishProgress(markers.size());
}
return markers;
}
// Update the progress
#Override
protected void onProgressUpdate(Integer... values) {
// set the current progress of the progress dialog
progressDialog.setProgress(values[0]);
}
// after executing the code in the thread
#Override
protected void onPostExecute(List<MarkerOptions> markers) {
GoogleMap map = GoogleMapsModule.getInstance().getMap();
for (MarkerOptions marker : markers) {
if (marker != null)
map.addMarker(marker);
}
if (markers.size() == mHydrants.size()) {
setAllHydrantAdded(true);
setNearbyHydrantsAdded(true);
} else {
setNearbyHydrantsAdded(true);
}
Device.releaseOrientation((Activity) context);
}
}
When I call the task, I have a list of Hydrant objects. To parse the list to the AsyncTask I convert the list into an Array:
new LoadHydrantsToMapTask(hydrants.size()).execute(hydrants
.toArray(new Hydrant[hydrants.size()]));

Categories