How to get current location using googleapiClient then put marker - android

I do want to get current location with GoogleApiClient with this code below,
#Override
public void onConnected(#Nullable Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null)
{
currentLat = mLastLocation.getLatitude();
currentLon = mLastLocation.getLongitude();
}else
{
Toast.makeText(getApplicationContext(), "Cannot get lat and lon", Toast.LENGTH_SHORT).show();
}
}
then after that i do want to put marker on current location, my problem is mLastlocation still null
#Override
public void onMapReady(GoogleMap googleMap) {
dGoogleMap = googleMap;
if(mLastLocation != null)
{
MarkerOptions marker = new MarkerOptions()
.position(new LatLng(currentLat, currentLon))
.title("My Current Location");
dGoogleMap.addMarker(marker);
dGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(currentLat, currentLon), 16));
}
}
Or this is my fault missunderstand the flow of async, or just my poor logic needs to be improved.

Put below line in your onMapReady method
dGoogleMap.setMyLocationEnabled(true);

Related

How to replace FusedLocationAPI deprecated method in this code?

I am trying to implement an app that uses Google Map API, I'm using this deprecated method and it's causing my app to not perform properly. deprecated method is: FusedLocationAPI, any ideas how to replace it in this context?
code:
public void onConnected(#Nullable Bundle bundle) {
locationRequest = LocationRequest.create();
locationRequest.setInterval(100);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
lastlocation = location;
if (currentLocationMarker != null) {
currentLocationMarker.remove();
}
Log.d("lat = ", "" + latitude);
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Location");
markerOptions.snippet("My Present Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
currentLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(7));
if (client != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
}
}

get current location functions return null

The below code is an extract from my Android application to get current location
I have been following http://blog.teamtreehouse.com/beginners-guide-location-android and http://droidmentor.com/get-the-current-location-in-android/
most of the documentation is outdated even the developer.google and developers.android stuff.
I want to know why both functions return null and what can I do about it
thank you.
#Override
public void onConnected(Bundle bundle) {
try
{
Log.d(TAG, "connection successful");
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation == null) {
Log.d(TAG, "get last location = null");
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); //then nothing happens
}
else {
Log.d(TAG, "last location successful");
handleNewLocation(mLastLocation);
}; }
#Override
public void onLocationChanged(Location location){
handleNewLocation(location);
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
Address address = getAddress(location);
starttext.setText("Current Location: \n" + address.toString());
}
The FusedLocationProviderApi is depreciated https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi
So use FusedLocationProviderClient instead. Usage: https://developer.android.com/training/location/retrieve-current.html#play-services

my location point appears out of the street google maps eclipse

I developed an application for Android in Eclipse with Google maps. The problem is that the blue dot indicating my current location appears always parallel to the road where I am driving, on roads outside cities. But if you are within the city the point already on top of the road.
I'm using this to get my location on the start of the app:
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location myLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
then I add the blue dot to the map:
googleMap.setMyLocationEnabled(true);
and then I start listening for location changes:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, time, 1, this);
My location change function:
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Lat1 = location.getLatitude();
Long1 = location.getLongitude();
if (Lat1 != Lat || Long1 != Long) {
Lat = location.getLatitude();
Long = location.getLongitude();
if (startNav == true) {
googleMap.animateCamera(CameraUpdateFactory
.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 17));
b = new LatLng(Lat, Long);
if (a != null) {
String urlTopass = makeURL(b.latitude, b.longitude, a.latitude, a.longitude);
new connectAsyncTask(urlTopass).execute();
}
}
}
}
}
My question is why does the blue dot appear parallel to the street instead of on top of it?
Use the FusedLocationProviderAPI. It is recommended over using the older open source Location APIs, especially since you're already using a Google Map so you are already using Google Play Services.
Simply set up a Location Listener, and update your current location Marker in each onLocationChanged() callback. If you only want one location update, just un-register for callbacks after the first callback returns.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null || !mGoogleApiClient.isConnected()){
buildGoogleApiClient();
mGoogleApiClient.connect();
}
if (map == null) {
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap retMap) {
map = retMap;
setUpMap();
}
public void setUpMap(){
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setMyLocationEnabled(true);
}
#Override
protected void onPause(){
super.onPause();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
protected synchronized void buildGoogleApiClient() {
Toast.makeText(this, "buildGoogleApiClient", Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
Toast.makeText(this,"onConnected", Toast.LENGTH_SHORT).show();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setSmallestDisplacement(0.1F);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
//remove previous current location Marker
if (marker != null){
marker.remove();
}
double dLatitude = mLastLocation.getLatitude();
double dLongitude = mLastLocation.getLongitude();
marker = map.addMarker(new MarkerOptions().position(new LatLng(dLatitude, dLongitude))
.title("My Location").icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));
}
}

Android: how get from (setMyLocationEnabled) -> longitude and latitude?

how I can get latitude and longitude from setMyLocationEnabled? while my code is this.
I need to use it to zoomin to location,
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0,0)).title("Marker"));
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLng());
mMap.animateCamera(CameraUpdateFactory.zoomBy(13));
}
For getting individual latitude and longitude, the following works for me.
mMap.setMyLocationEnabled(true);
double lat = mMap.getMyLocation().getLatitude();
double longt = mMap.getMyLocation().getLongitude();
Google map location API has the listeners you can get your current location by using this.
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
if(mMap != null){
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
}
};
And then set the listener for the map.
mMap.setOnMyLocationChangeListener(myLocationChangeListener);

marker in my location?

Please help me, how can I set a marker in current location?
Below my code onCreate, addMarker and createMapView.
onCreate
public class MapActivity extends Activity {
GoogleMap googleMap;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_activity);
createMapView();
addMarker();
}
addMarker
private void addMarker() {
if (null != googleMap) {
googleMap.addMarker(new MarkerOptions()
.title("Marker")
.position(new LatLng(0, 0))
.draggable(true));
}
}
createMapView
private void createMapView() {
try {
if (null == googleMap) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.mapView)).getMap();
if (null == googleMap) {
Toast.makeText(getApplicationContext(), "Error creating map", Toast.LENGTH_LONG).show();
}
}
} catch (NullPointerException e) {
Log.e("mapApp", e.toString());
}
}
You are setting your marker at (0, 0)
.position(new LatLng(0, 0))
You can get the latest position in onLocationChanged.
Get the latitude and longitude:
new LatLng(location.getLatitude(), location.getLongitude())
Use the LatLng object to set your marker.
Get the latitude and longitude location from FusedLocationApi as GoogleApiClient.FusedLocationApi.getLastLocation() and then call addMarker using these lat/longs.
Hope this helps.
First of all you need to get current latlng of your position
and create latlng object based on it , and when you get latlng successfully
use this method
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
fromPosition = new LatLng(latti, longi);
googleMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.orangedoticon)).title("helo0o0"));
You must get your lat and lng of your current location and put this code.
#Override
public void onMapReady(GoogleMap map) {
map.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
}
https://developers.google.com/maps/documentation/android-api/marker

Categories

Resources