Get current location when button is clicked - java

I have a google maps app and now I've added a button. I want to get a message (Toast) with my coordinates when I click the button. Which is the simplest way to do this? Do I also have to implement onLocationChanged class?

You can use different ways to implement it. I tend to think that the best for your task is to show toast after pressing my location button.
public class MapActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Show my location button
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
//Do something with your location. You can use mMap.getMyLocation();
//anywhere in this class to get user location
Toast.makeText(MapActivity.this, String.format("%f : %f",
mMap.getMyLocation().getLatitude(), mMap.getMyLocation().getLongitude()),
Toast.LENGTH_SHORT).show();
return false;
}
});
}
}
Also you can show toast with user location every time it changes. To do it set OnMyLocationChangeListener
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(android.location.Location location) {
//...
}
});

Do I also have to implement onLocationChanged class?
If you don't want to receive location updates, the answer is no.
Which is the simplest way to do this?
The simplest way is to obtain the last known location as described here.

The Example Google maps project on github has an example of how to do this.
Additionally, Android Studio has a Google Maps Activity template you can choose when you create a project. This project has getLastKnownLocation() implemented. More information can be found here.

Related

Can disable the GoogleMap to move to a marker when clicked?

The following is my current GoogleMap Setup Code.
I now want the Map to stop panning to a clicked Marker (which I added in another segment). I believe the right term would be, that I want the autopan to be on (?)
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildClient();
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(false);
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.getUiSettings().setScrollGesturesEnabled(false);
} else {
ErrorManager.displayError(TBCError.PermissionDenied, this);
}
}
Thanks in advance!
panning is formally referred to as control gestures, it would make sense you'll either have to overwrite a listener or disable a control with a boolean, so take a peek at this link android documentation reference for control gestures.
zoom control UiSettings.setZoomGesturesEnabled(boolean)
or scroll (pan) control UiSettings.setScrollGesturesEnabled(boolean).
Google Markers have a default behavior depending on the boolean returned by OnMarkerClick(...),
"
Return false to indicate that we have not consumed the event and that we wish for the default behavior to occur (which is for the camera to move such that the marker is centered and for the marker's info window to open, if it has one). return false;"
android documentation reference for google api marker

Google Maps Pin in my Android application

I need to display user inserted pins on the map that i will have in my application.
This pin needs to be visible to all the users using the app.
I have no clue how to implement this.
Can i get some help please?
Pins in Google Maps are called Markers and they are pretty simple to create.
Following what is documented from the Google Maps API here, you just use the addMarker() method to create a marker and can customize the options of where it should be placed and the title to show when it is clicked on
#Override
public void onMapReady(GoogleMap map) {
map.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
}

I'm not having setUpMapIfNeeded library in my MapsActivity.java file

I posted the code snippet below as I'm unable to find the command setUpMapIfNeeded();. When I type the necessary command, I get red lines everywhere. Can anyone help me out with this code? Also, I'm not getting any marker in my emulator.
I'm open to suggestions, please help me out. The min sdk version that I'm using is 17, and the android studio version is 2.1. I'm using the Googlemaps activity. I still don't understand why I'm not getting the setUpMapIfNeeded command and also the rest of the inbuilt code snippet.
Code screenshot
#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);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
Also after trying the missing code I'm unable to get any marker.
Whereas, wherever I have search online I'm getting this tutorial.
If you are aware of any other code, do let me know.
When you use MapsActivty, there is no need for any extra code. All the neccessary code is generated by Android Studio itself. If you look at the tutorial, the code inside the setUpMapIfNeeded() is same as the code you have in your onCreate(). When you add the Google MapsActivty, all you need to show the map is the Google Maps API key. Paste the APi key in your "google_maps_api.xml"(inside values folder) and you are done. Run the application and you will get the map in your Activity.
Steps for acquiring the Google Maps API key is given in the google_maps_api.xml in comments.
Also if are adding your own markers, then use the following code
public void setMarkerOnMap(String name, LatLng l) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(l);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(name);
// Placing a marker on the touched position
mMap.addMarker(markerOptions);
}
Call this function like this :
LatLng loc=new LatLng(latitude,longitude);
String str_placeName="Place Name";
setMarkerOnMap(str_placeName,loc);
You need to call setUpMapIfNeeded() in onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
}
Check this tutorial and SO question on how to add markers.

Clicking on marker to edit marker info in android

I am making an app that uses google maps and markers, and would like to enable users to long click on map to add a marker, and get a popup that would allow them to name the marker, write a short summary about it, etc. I would also like to enable the users to click on the existing marker and to get a popup with the info they entered previously and that they could edit at any time. At first I tried doing something like this:
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng arg0) {
startActivity(new Intent(MapsActivity.this, SetMarkerInfoActivity.class));
}
});
I would open new activity when i long click on the map. I added marker code to the SetMarkerInfoActivity:
marker = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker))
.position(
new LatLng(arg0.latitude,
arg0.longitude))
.visible(true));
But this seemed like bad solution. Does anyone have some better idea?

Wait onLocationChanged(Location location)

I need to get current location, and after that - do next code. How can i wait while this method has finished? onLocationChanged is called automatically that why i have problem. Do someone has any ideas how to do itmore correct?
I make it very stupid, in OnLocationChanged() i call onResume(), but it is so bad idea.
#Override
public void onLocationChanged(Location location) {
final Location loc = location;
Log.d("myLogs", "OnChange2");
Log.d("myLogs", "2" + loc.getLatitude() + "," + loc.getLongitude());
myLat = loc.getLatitude();
myLong = location.getLongitude();
onResume();
}
You might want to use AsyncTask for that. See Android find GPS location once, show loading dialog for the answers. Basically in onPreExecute you can start dialog( it starts before the doInBackground is called). It means you are waiting till the time you can location and showing the dialog. Then in doInBackground you can get the location. After that finishes onPostExecute is called. You can stop is from inside onPostExecute. You can check if the location is not null and then call some other function from inside onPostExecute also if you want.
This might be one way. You can learn a basic example from AsyncTask Android example . You can also start by reading the documentation here and read How to Get GPS Location Using AsyncTask? .
Some other similar helpful questions:
Wait for current location - GPS - Android Dev
getting location instantly in android
Hope this helps.
I realize the OP has accepted the above answer but I have a feeling the OP wanted a more simple answer.
I am assuming the OP has an android application with an Activity. I declared mine like this:
public class HelloAndroidActivity extends Activity implements LocationListener {
The OP was confused as to how the lifecycle methods worked and when work should be done. My Resume and Pause methods would look like this:
#Override
protected void onPause() {
((LocationManager)getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
super.onPause();
}
#Override
protected void onResume() {
((LocationManager)getSystemService(Context.LOCATION_SERVICE)).requestLocationUpdates(LocationManager.GPS_PROVIDER, 5 * 1000, 1, this);
super.onResume();
}
Notice that my onResume asks that I be notified when there are location updates and the onPause method asks that I no longer be notified. You should be careful to not ask for updates at a time interval smaller then you really need or you will drain your battery.
Since the activity implements LocationListener my onLocationChanged method looks like this:
#Override
public void onLocationChanged(Location location) {
// Update the location fields
((EditText)findViewById(R.id.latField)).setText(Double.toString(location.getLatitude()));
((EditText)findViewById(R.id.longField)).setText(Double.toString(location.getLongitude()));
}
This simply takes the new location and updates some text EditText fields that I have in my activity. The only other thing I needed to do was to add the GPS permission to my manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
So if I were asking how to start out using the location manager and the location service this would be how I would begin. I'm not trying to take anything away from the accepted answer, I just think there was a fundamental misunderstanding about what to do in onResume and in the onLocationMethodChanged methods.

Categories