Reputation: 124
I'm using a map in my android app, but I want to use location updates and display it on a map, I'm following the documentation on google developers about location updates with LocationRequest() but cant figure how to use this into the map. here is my activity.java
import android.content.Context;
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 com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
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.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
public class MapaActivity extends FragmentActivity implements OnMapReadyCallback,ConnectionCallbacks,OnConnectionFailedListener, LocationListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
// Request code to use when launching the resolution activity
private static final int REQUEST_RESOLVE_ERROR = 1001;
// Unique tag for the error dialog fragment
private static final String DIALOG_ERROR = "dialog_error";
// Bool to track whether the app is already resolving an error
private boolean mResolvingError = false;
// etiqueta para logs
private final String TAG="Mapas";
//coordenadas-------------------
private String lat;
private String lon;
//variables para localizacion
Location mLastLocation;
Location mCurrentLocation;
LocationRequest mLocationRequest;
String mLastUpdateTime;
//// posicion anterior///////////////
LocationManager locationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mapa);
// Create a GoogleApiClient instance
// Kick off the process of building a GoogleApiClient and requesting the LocationServices
// API.
buildGoogleApiClient();
//nuevo codigo
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
protected synchronized void buildGoogleApiClient() {
Log.v(TAG, "Lanzando GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
//location request
// actualiza cada 40 segundos min 20 segundos
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(40000);
mLocationRequest.setFastestInterval(20000);
//prioridad alta precision
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Log.v(TAG,"se ingresa al locationRequest");
}
@Override
protected void onResume() {
super.onResume();
// setUpMapIfNeeded();
}
@Override
protected void onPause(){
super.onPause();
Log.v(TAG, "evento onPause");
}
@Override
protected void onStop(){
super.onStop();
Log.v(TAG, "evento onStop");
}
@Override
protected void onDestroy(){
super.onDestroy();
Log.v(TAG, "evento onDestroy");
};
@Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia, and move the camera.
// habilitar controles de zoom
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//habilitar brujula
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.setMyLocationEnabled(true);
// para pasar a funcion
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object needed to retrieve the provider
Criteria criteria = new Criteria();
// Get the name of the best available provider
String provider = locationManager.getBestProvider(criteria, true);
// We can use the provider immediately to get the last known location
Location location = locationManager.getLastKnownLocation(provider);
googleMap.clear();
// convert the location object to a LatLng object that can be used by the map API
LatLng currentPosition = new LatLng(location.getLatitude(), location.getLongitude());
Log.v(TAG, "Latitud :" + location.getLatitude());
googleMap.addMarker(new MarkerOptions().position(currentPosition).title("Yo"));
// zoom to the current location
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition, 13));
googleMap.setMyLocationEnabled(true);
Log.v(TAG, currentPosition.toString());
//pasar la posicion para grabar en el servidor
}
@Override
public void onConnected(Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
and here is my view
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map"
tools:context=".MapaActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
Upvotes: 1
Views: 897
Reputation: 43342
It looks like you're mixing the FusedLocationProviderApi with the old open source Location API. If you're using the FusedLocationProviderApi, just stick with that.
You're missing two key pieces, the call to mGoogleApiClient.connect()
, and the call to requestLocationUpdates()
.
Here's the general structure of what your code should look like:
public class MainActivity extends FragmentActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap map;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private Marker marker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
buildGoogleApiClient();
mGoogleApiClient.connect();
if (map == null) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.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) {
Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();
}
@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));
}
}
Upvotes: 2