Google Maps API Android会设置上次位置错误

时间:2016-01-26 17:24:09

标签: android google-maps google-maps-android-api-2 google-maps-api-2

所以我试图按照教程查看最后一个位置,如此处所示 http://developer.android.com/training/location/retrieve-current.html

我没有将标记添加到片段中,这表明标记正在正确更新。我在我的主项目上试过这个并且它不起作用。所以我试着按照教程中的一个全新项目的信,看看我是否可以解决问题。

我想知道这是否是我使用的模拟器的问题(肯定使用的是谷歌API版本6.0),因为我无法正确运行示例项目

下面是我使用过的文件和生成的错误日志 MapTesting.java

package dominic.maptesting;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
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.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
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;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

 private GoogleMap mMap;
 private GoogleApiClient mGoogleApiClient;
 private Location mLastLocation;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_maps);
  // Obtain the SupportMapFragment and get notified when the map is ready to be used.
  SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
   .findFragmentById(R.id.map);
  mapFragment.getMapAsync(this);

  if (mGoogleApiClient == null) {
   mGoogleApiClient = new GoogleApiClient.Builder(this)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .addApi(LocationServices.API)
    .build();

  }

 }

 @Override
 public void onConnected(Bundle connectionHint) {
  if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
   // TODO: Consider calling
   //    ActivityCompat#requestPermissions
   // here to request the missing permissions, and then overriding
   //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
   //                                          int[] grantResults)
   // to handle the case where the user grants the permission. See the documentation
   // for ActivityCompat#requestPermissions for more details.
   return;
  }
  mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
   mGoogleApiClient);
  if (mLastLocation != null) {
   LatLng test = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
   mMap.addMarker(new MarkerOptions().position(test).title("Marker Test"));
   mMap.moveCamera(CameraUpdateFactory.newLatLng(test));

  } else {}

 }

 @Override
 public void onConnectionSuspended(int i) {

 }

 protected void onStart() {
  mGoogleApiClient.connect();
  super.onStart();
 }

 protected void onStop() {
  mGoogleApiClient.disconnect();
  super.onStop();
 }


 @Override
 public void onMapReady(GoogleMap googleMap) {
  mMap = googleMap;

 }

 @Override
 public void onConnectionFailed(ConnectionResult connectionResult) {

 }
}

Activity_Map.xml

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="dominic.maptesting.MapsActivity" />

AppManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="dominic.maptesting">

<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality. 
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_GPS"/>


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/. 
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

01-26 17:21:51.228 3427-3427/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-26 17:21:51.228 3427-3427/? E/android.os.Debug: failed to load memtrack module: -2
01-26 17:21:51.255 1299-1339/? E/InputDispatcher: channel 'b6f8f72 dominic.maptesting/dominic.maptesting.MapsActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
01-26 17:21:51.991 959-959/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
01-26 17:21:53.175 3440-3440/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-26 17:21:53.175 3440-3440/? E/android.os.Debug: failed to load memtrack module: -2
01-26 17:21:53.244 3436-3436/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-26 17:21:53.244 3436-3436/? E/android.os.Debug: failed to load memtrack module: -2
01-26 17:21:53.725 1598-1872/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4093960
01-26 17:21:54.666 948-2693/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property

非常感谢任何建议或帮助。我非常坚持这个,并且是Android的新手

1 个答案:

答案 0 :(得分:0)

如果您仔细查看以下代码块导致问题。

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
   // TODO: Consider calling
   //    ActivityCompat#requestPermissions
   // here to request the missing permissions, and then overriding
   //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
   //                                          int[] grantResults)
   // to handle the case where the user grants the permission. See the documentation
   // for ActivityCompat#requestPermissions for more details.
   return;
  }

在Android 6.0上,此块将返回true,并且函数将在不执行更多代码的情况下退出。原因是您的目标是android 6.0版本而您没有处理运行时权限。请仔细阅读本文以了解Android Runtime权限。

http://developer.android.com/training/permissions/requesting.html https://github.com/googlesamples/android-RuntimePermissions

在使用运行时权限后,您可能无法在地图上看到标记,因为LocationServices.FusedLocationApi.getLastLocation可能只返回null,因此您也必须处理该逻辑。