gpt4 book ai didi

android - 谷歌地图 API 位置更新

转载 作者:行者123 更新时间:2023-11-29 20:26:52 25 4
gpt4 key购买 nike

我在我的 android 应用程序中使用 map ,但我想使用位置更新并将其显示在 map 上,我正在关注谷歌开发人员关于使用 LocationRequest() 进行位置更新的文档,但不知道如何使用这进入 map 。这是我的 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) {

}
}

这是我的观点

<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" />

最佳答案

看起来您正在将 FusedLocationProviderApi 与旧的开源 Location API 混合使用。如果您使用的是 FusedLocationProviderApi,请坚持使用。

您遗漏了两个关键部分,对 mGoogleApiClient.connect() 的调用,以及对 requestLocationUpdates() 的调用。

这是您的代码的一般结构:

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

}

}

关于android - 谷歌地图 API 位置更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32426163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com