我想通过OnLocationChanged的方法获取位置更改,我以前使用过OnMyLocationChanged,但我发现该方法已被废止,但是使用新的方法,当分配mGoogleApiClient变量时,它会标记为错误
namespace FuncionesAndroid.Droid
{
[Activity(Label = "MainMapa")]
public class MainMapa : Activity, IOnMapReadyCallback, IOnMyLocationClickListener, IOnMyLocationButtonClickListener, Android.Gms.Location.ILocationListener, GoogleApiClient.IConnectionCallbacks, GoogleApiClient.IOnConnectionFailedListener
{
private string _tag = "MainMapa";
GoogleMap mapa = null;
DataBase db = new DataBase();
private LocationRequest locationRequest;
static GoogleApiClient mGoogleApiClient;
public static int MILISEGUNDOS_POR_SECUNDOS = 1000;
public static int MINUTO = 60 * MILISEGUNDOS_POR_SECUNDOS;
//private IFusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi;
public async void OnMapReady(GoogleMap googleMap)
{
mapa = googleMap;
googleMap.MyLocationEnabled = true;
googleMap.SetOnMyLocationButtonClickListener(this);
googleMap.SetOnMyLocationClickListener(this);
googleMap.SetMinZoomPreference(6.0F);
//Opcional
googleMap.SetLatLngBoundsForCameraTarget(new LatLngBounds(new LatLng(14.399838, -119.346947),new LatLng(30.706694, -83.355215)));
googleMap.UiSettings.ZoomControlsEnabled = true;
googleMap.UiSettings.CompassEnabled = true;
locationRequest = new LocationRequest();
locationRequest.SetInterval(MINUTO);
locationRequest.SetFastestInterval(15 * MILISEGUNDOS_POR_SECUNDOS);
locationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
try
{
mGoogleApiClient = new GoogleApiClient.Builder(this)
.AddConnectionCallbacks(this)
.AddOnConnectionFailedListener(this)
.AddApi(LocationServices.API)
.Build();
}
catch (Exception e)
{
Log.Debug(_tag, e.Message);
}
googleMap.MoveCamera(CameraUpdateFactory.ZoomIn());
CargarMarcadores();
CentrarMyUbicacion();
}
private void GuardarRutas(ArrayList rutas, int idInicio, int idFin)
{
foreach (ArrayList path in rutas)
{
foreach (Dictionary<String, Double> punto in path)
{
Model.Polyline polyline = new Model.Polyline()
{
id_inicio = idInicio,
id_fin = idFin,
lat = punto["lat"],
lon = punto["lon"]
};
db.InsertarDatoPolyline(polyline, this);
}
}
}
public void CargarMarcadores()
{
BitmapDrawable bitmapClienteDraw = (BitmapDrawable)GetDrawable(Resource.Mipmap.marker_map_us);
Bitmap bitmapCliente = bitmapClienteDraw.Bitmap;
Bitmap smallMarkerCliente = Bitmap.CreateScaledBitmap(bitmapCliente, 60, 90, false);
List<ClientesGps> clientesGps;
clientesGps = db.selectTablaClientesGps(this);
Location miUbicacion = ObtenerUbicacionActual();
foreach (ClientesGps cliente in clientesGps)
{
MarkerOptions clienteMarcador = new MarkerOptions()
.SetPosition(new LatLng(cliente.lat, cliente.lon))
.SetIcon(BitmapDescriptorFactory.FromBitmap(smallMarkerCliente))
.SetTitle(cliente.nombre);
mapa.AddMarker(clienteMarcador);
}
}
public void CentrarMyUbicacion()
{
LocationManager locationManager = (LocationManager)
GetSystemService(Context.LocationService);
Criteria criteria = new Criteria();
criteria.Accuracy = Accuracy.Fine;
Location Ubicación = locationManager.GetLastKnownLocation(locationManager.GetBestProvider(criteria, false));
if (Ubicación != null)
{
LatLng myUbicación = new LatLng(Ubicación.Latitude, Ubicación.Longitude);
mapa.AnimateCamera(CameraUpdateFactory.NewLatLngZoom(myUbicación,15.4F));
}
}
public Location ObtenerUbicacionActual()
{
LocationManager locationManager = (LocationManager)
GetSystemService(Context.LocationService);
Criteria criteria = new Criteria();
criteria.Accuracy = Accuracy.Fine;
Location Ubicación = locationManager.GetLastKnownLocation(locationManager.GetBestProvider(criteria, false));
return Ubicación;
}
public void DibujarRutas(ArrayList rutas, GoogleMap googleMap)
{
PolylineOptions polylineOptions = null;
foreach(ArrayList path in rutas)
{
polylineOptions = new PolylineOptions();
foreach(Dictionary<String, Double> punto in path)
{
double lat, lon;
lat = punto["lat"];
lon = punto["lon"];
polylineOptions.Add(new LatLng(lat, lon));
}
polylineOptions.InvokeWidth(15);
polylineOptions.InvokeColor(Color.Blue);
polylineOptions.Geodesic(true);
}
if(polylineOptions!=null)
{
googleMap.AddPolyline(polylineOptions);
}
else
{
Toast.MakeText(this, "Direcciones no encontradas", ToastLength.Short).Show();
}
}
private async Task<ArrayList> GetUrlAsync(LatLng origin,LatLng dest, String directionMode)
{
String str_origin = "origin=" + origin.Latitude + "," + origin.Longitude;
String str_dest = "destination=" + dest.Latitude + "," + dest.Longitude;
String mode = "mode=" + directionMode;
String parameters = str_origin + "&" + str_dest + "&" + mode;
String output = "json";
JObject json = await Servicios.Servicio.ObtenerRutaGoogleMaps(output, parameters, GetString(Resource.String.GoogleKey));
ArrayList routes = new ArrayList();
JArray jRoutes = null;
JArray jLegs = null;
JArray jSteps = null;
try
{
jRoutes = (JArray)json["routes"];
for (int i = 0; i < jRoutes.Count; i++)
{
jLegs = (JArray)jRoutes[i]["legs"];
ArrayList path = new ArrayList();
for (int j = 0; j < jLegs.Count; j++)
{
jSteps = (JArray)jLegs[j]["steps"];
for (int k = 0; k < jSteps.Count; k++)
{
String polyline = "";
polyline = (String)jSteps[k]["polyline"]["points"];
ArrayList list = decodePolyline(polyline);
for(int l = 0; l < list.Count; l++)
{
Dictionary<String, Double> hm = new Dictionary<string, Double>();
hm.Add("lat", ((LatLng)list[l]).Latitude);
hm.Add("lon", ((LatLng)list[l]).Longitude);
path.Add(hm);
}
}
routes.Add(path);
}
}
return routes;
}
catch (JsonReaderException e)
{
routes = null;
return routes;
}
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.MainMapa);
MapFragment mapFragment = (MapFragment)FragmentManager.FindFragmentById(Resource.Id.map);
mapFragment.GetMapAsync(this);
}
protected override void OnResume()
{
base.OnResume();
if(mGoogleApiClient.IsConnected)
{
RequestLocationUpdates();
}
}
protected override void OnStart()
{
base.OnStart();
mGoogleApiClient.Connect();
}
protected override void OnStop()
{
base.OnStop();
mGoogleApiClient.Disconnect();
}
private void RequestLocationUpdates()
{
LocationServices.FusedLocationApi.RequestLocationUpdates(mGoogleApiClient, locationRequest, this);
}
protected override void OnPause()
{
base.OnPause();
LocationServices.FusedLocationApi.RemoveLocationUpdates(mGoogleApiClient, this);
}
public void OnMyLocationClick(Location location)
{
Toast.MakeText(this, "My Ubicación actual", ToastLength.Short).Show();
}
public bool OnMyLocationButtonClick()
{
Toast.MakeText(this, "Centrando en ubicación actual", ToastLength.Short).Show();
return false;
}
public async void OnLocationChanged(Location location)
{
Toast.MakeText(this, location.ToString(),ToastLength.Short).Show();
}
public void OnConnectionFailed(ConnectionResult result)
{
//throw new NotImplementedException();
}
public void OnConnected(Bundle connectionHint)
{
RequestLocationUpdates();
}
public void OnConnectionSuspended(int cause)
{
//throw new NotImplementedException();
}
}
}
同样,我看到了一些不用的代码,它们不使用Google AppClient,但是不解释其用法或没有很好地记录,如果它们有更好的代码,我将不胜感激< / p>
答案 0 :(得分:0)
该解决方案非常简单且愚蠢,我在另一个论坛上看到,当谈到GoogleApiClient在Xamarin中第一个失败时是正常的,正确的做法是清理并重新编译该解决方案,非常感谢您想阅读的东西太多了!