你好我正在尝试做一个在地图中显示的应用程序(api v2)mi当前位置并实现它
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.SyncStateContract.Constants;
import android.util.Log;
import android.view.Menu;
public class Desayunos extends android.support.v4.app.FragmentActivity implements LocationListener, LocationSource, SensorEventListener {
private GoogleMap mMap;
private OnLocationChangedListener mListener;
private LocationManager locationManager;
private boolean haveLocation = false;
private SensorManager mSensorManager;
private float[] mGravity;
private float[] mGeomagnetic;
private long lastTimeCompassUpdated = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Instanciamos locationManager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean network_enabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
boolean gps_enabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.i("Provider", "estado: "+network_enabled);
Log.i("Provider", "estado: "+gps_enabled);
// Establecemos la precisión
Criteria locationCriteria = new Criteria();
locationCriteria.setAccuracy(Criteria.ACCURACY_FINE);
// Y establecemos que se escuche al mejor proveedor de localización ( redes móviles o GPS o WiFi )
locationManager.requestLocationUpdates(locationManager.getBestProvider(locationCriteria, true), 1L, 2F, (LocationListener) this);
initializeMap();
}
private void initializeMap()
{
// Confirmamos que no se ha inicializado el mapa todavía
if (mMap == null)
{
// obtenemos el mapa de la vista
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapaDesa)).getMap();
// Registramos o establecemos ésta clase, MapActivity, como LocationSource del mapa para utilizar nuestro locationManager y el Listener ;)
mMap.setLocationSource(this);
// Inicializamos el mapa...
if (mMap != null)
{
setUpMap();
}
}
}
private void setUpMap()
{
// Nos localiza...
mMap.setMyLocationEnabled(true);
// Pinta una marca en La Meca
//addLaMecaMarkOnMap();
}
private void addLaMecaMarkOnMap()
{
/*mMap.addMarker(new MarkerOptions()
.position(new LatLng(Constants.laMecaLatitude, Constants.laMecaLongitude))
.title("La Meca")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.icono)));*/
}
private void initialiceSensors()
{
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
// Vamos a usar el acelerómetro y el sensor magnético
Sensor gsensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Sensor msensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mSensorManager.registerListener(this, gsensor, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, msensor, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onPause()
{
if(locationManager != null)
{
locationManager.removeUpdates((LocationListener) this);
}
super.onPause();
}
@Override
public void onResume()
{
super.onResume();
initializeMap();
if(locationManager != null)
{
mMap.setMyLocationEnabled(true);
}
}
public void activate(OnLocationChangedListener listener)
{
mListener = listener;
}
public void deactivate()
{
mListener = null;
}
public void onLocationChanged(Location location)
{
if (!haveLocation)
{
initialiceSensors();
haveLocation = true;
}
mMap.clear();
if( mListener != null )
{
addLaMecaMarkOnMap();
mListener.onLocationChanged( location );
CameraPosition newCameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // centra el mapa en nuestra posición
.zoom(17) // establece el zoom
.bearing(0)
.tilt(0)
.build();
//Move the camera to the user's location once it's available!
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(newCameraPosition));
}
}
public void onProviderDisabled(String provider)
{
// cuando se deshabilita un probeedor de localización... prefiero no hacer nada
// Toast.makeText(this, "provider disabled", Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider)
{
// cuando se habilita un probeedor de localización... prefiero no hacer nada
// Toast.makeText(this, "provider enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
// Cuando cambia el estado de la localización... prefiero no hacer nada
// Toast.makeText(this, "status changed", Toast.LENGTH_SHORT).show();
}
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
// cuando cambia la precisión...
}
public void onSensorChanged(SensorEvent event)
{
// quiero dejar un margen de 3 segundos al principio
// para la animación hasta el punto donde se encuentra el usuario...
if (lastTimeCompassUpdated == 0)
{
lastTimeCompassUpdated = System.currentTimeMillis()+3000;
return;
}
else if (System.currentTimeMillis()>lastTimeCompassUpdated )
{
if (mMap!=null)
{
int matrix_size = 16;
float[] R = new float[matrix_size];
float[] outR = new float[matrix_size];
if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)
return;
switch (event.sensor.getType())
{
case Sensor.TYPE_MAGNETIC_FIELD:
mGeomagnetic = event.values.clone();
break;
case Sensor.TYPE_ACCELEROMETER:
mGravity = event.values.clone();
break;
}
if (mGeomagnetic != null && mGravity != null)
{
if (SensorManager.getRotationMatrix(R, null, mGravity, mGeomagnetic))
{
SensorManager.getOrientation(R, outR);
}
CameraPosition oldPosition = mMap.getCameraPosition();
// Quiero que sólo se actualice si hay una variación de mas de un grado
if (Math.abs(Math.abs(oldPosition.bearing) - Math.abs(Math.toDegrees(outR[0])))>1)
{
CameraPosition newCameraPosition = new CameraPosition.Builder()
.target(oldPosition.target) // Sets the center of the map to Mountain View
.zoom(oldPosition.zoom) // Sets the zoom
.bearing((float) Math.toDegrees(outR[0]))
.tilt(oldPosition.tilt)
.build(); // Creates a CameraPosition from the builder
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(newCameraPosition));
}
}
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
它没有显示错误,但应用程序显示地图,而没有标记当前位置
我也放了xml文件:
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Restaurantes" >
<fragment
android:id="@+id/mapaDesa"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
</RelativeLayout>
有什么想法吗?
谢谢你!!