Android Studio无法加载地图

时间:2015-03-08 06:16:59

标签: java android google-maps google-maps-api-3

我在创建应用时遇到了一些问题。它说:无法加载地图。联系Google服务器时出错这可能是一个身份验证问题(但可能是由于网络错误)。我已经就这个问题咨询了其他帖子,但它还没有解决我的问题。我已经备份了我的项目,然后擦除了我的硬盘并将项目放回到Android Studio Projects文件夹中。我重置了密钥并在Google Developers API网站中创建了一个新项目。我的代码如下。我在这个项目中有很多活动。如果我需要展示所有这些,请告诉我。这是地图活动。

JAVA

package com.example.ani.mapactivity;

import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity {

private GoogleMap mMap; // Might be null if Google Play services APK is not available.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    setUpMapIfNeeded();
    mMap.setMyLocationEnabled(true);
}

@Override
protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
    final LatLng position = new LatLng(37.3180226,-121.9096162);
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 15));
    MarkerOptions school = new MarkerOptions();
    school.position(position);
    mMap.addMarker(school);

    final LatLng positionShop = new LatLng(37.31614,-121.910097);
    MarkerOptions shop = new MarkerOptions();
    shop.position(positionShop);
    mMap.addMarker(shop);

    final LatLng positionRestaurant = new LatLng(37.3188015,-121.9140952);
    final MarkerOptions restaurant = new MarkerOptions();
    restaurant.position(positionRestaurant);
    mMap.addMarker(restaurant);
    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            Log.d("Message", "Lat = " + marker.getPosition().latitude);
            Log.d("Message", "Longitude = " + marker.getPosition().longitude);
            if(marker.getPosition().latitude == positionRestaurant.latitude && marker.getPosition().longitude == positionRestaurant.longitude){
                Intent lotA = new Intent(MapsActivity.this, LotA.class);
                startActivity(lotA);

            }
            else if(marker.getPosition().latitude == position.latitude && marker.getPosition().longitude == position.longitude) {
                Intent lotC = new Intent(MapsActivity.this, LotC.class);
                startActivity(lotC);
            }
            else if(marker.getPosition().latitude == positionShop.latitude && marker.getPosition().longitude == positionShop.longitude) {
                Intent lotB = new Intent(MapsActivity.this, LotB.class);
                startActivity(lotB);
            }
            return false;

        }
    });
}

/**
 * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
 * installed) and the map has not already been instantiated.. This will ensure that we only ever
 * call {@link #setUpMap()} once when {@link #mMap} is not null.
 * <p/>
 * If it isn't installed {@link SupportMapFragment} (and
 * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
 * install/update the Google Play services APK on their device.
 * <p/>
 * A user can return to this FragmentActivity after following the prompt and correctly
 * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
 * have been completely destroyed during this process (it is likely that it would only be
 * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
 * method in {@link #onResume()} to guarantee that it will be called.
 */
private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}

/**
 * This is where we can add markers or lines, add listeners or move the camera. In this case, we
 * just add a marker near Africa.
 * <p/>
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 */
private void setUpMap() {

}
}

XML

<resources>
<string name="google_maps_key_instructions" templateMergeStrategy="replace"><!--

TODO: Before you run your application, you need a Google Maps API key.

To get one, follow this link, follow the directions and press "Create" at the end:

https://console.developers.google.com/flows/enableapi?    apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=5C:4E:3D:B7:F9:47:39:B4:C9:FA:98:27:43:DD:48:18:E5:9F:7E:A5%3Bcom.example.ani.mapactivity

You can also add your credentials to an existing key, using this line:
5C:4E:3D:B7:F9:47:39:B4:C9:FA:98:27:43:DD:48:18:E5:9F:7E:A5;com.example.ani.mapactivity

Once you have your key (it starts with "AIza"), replace the "google_maps_key"
string in this file.
--></string>

<string name="google_maps_key" templateMergeStrategy="preserve">AIzaSyAXa14eBg8mrEGo1_DCmultIcnNl-RUOQo</string>

logcat的

03-08 01:02:13.797    2605-2620/com.example.ani.mapactivity I/Google Maps Android API﹕ Failed to contact Google servers. Another attempt will be made when connectivity is established.

03-08 01:02:14.197    2605-2632/com.example.ani.mapactivity D/dalvikvm﹕ GC_FOR_ALLOC freed 1360K, 17% free 10637K/12732K, paused 19ms, total 19ms

03-08 01:02:30.367    2605-2635/com.example.ani.mapactivity E/Google Maps Android API﹕ Failed to load map. Error contacting Google servers. This is probably an authentication issue (but could be due to network errors).

找不到设备

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.anish.mapactivity" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission    android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<permission android:name="com.example.anish.permission.MAPS_RECEIVE"
    android:protectionLevel="signature"/>
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" >
</uses-feature>

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

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <meta-data
        android:name="com.google.android.maps.v2.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>
    <activity
        android:name=".LotA"
        android:label="@string/title_activity_lot" >
    </activity>
    <activity
        android:name=".LotB"
        android:label="@string/title_activity_lot_b" >
    </activity>
    <activity
        android:name=".LotC"
        android:label="@string/title_activity_lot_c" >
    </activity>
</application>

</manifest>

请不要留下粗鲁的答案或记下我的答案。我在模拟器和真实手机上试过这个。如果需要进一步解释或更多代码(其他活动),请在评论中告诉我。

谢谢,

阿尼

修改

我试过了2015年的说法。它现在抛出这个错误:

03-08 03:02:43.230    1828-1828/com.example.ani.mapactivity D/OpenGLRenderer﹕ Enabling debug mode 0
03-08 03:02:43.230    1828-1905/com.example.ani.mapactivity D/﹕ HostConnection::get() New Host Connection established 0xb7fe3100, tid 1905
03-08 03:02:43.610    1828-1905/com.example.ani.mapactivity D/dalvikvm﹕ GC_FOR_ALLOC freed 1224K, 16% free 10642K/12632K, paused 12ms, total 12ms
03-08 03:02:58.090    1828-1906/com.example.ani.mapactivity E/Google Maps Android API﹕ Failed to load map. Error contacting Google servers. This is probably an authentication issue (but could be due to network errors).
03-08 03:03:12.890    1828-1905/com.example.ani.mapactivity A/libc﹕ Fatal signal 11 (SIGSEGV) at 0x00000007 (code=1), thread 1905 (Thread-82)

2 个答案:

答案 0 :(得分:1)

我认为你的代码没有问题。

确保manifest.xml文件中包含以下所有标记。

<permission android:name="com.example.mymaps.permission.MAPS_RECEIVE" 
android:protectionLevel="signature"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

将com.example.mymaps替换为您的包名。

并检查应用程序标记中是否包含以下元数据。

<meta-data
 android:name="com.google.android.maps.v2.API_KEY"
 android:value="AIzaSyAXa14eBg8mrEGo1_DCmultIcnNl" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

使用您自己的API密钥替换API_KEY元数据标记中的android:值。

希望这会有所帮助。问候。

答案 1 :(得分:1)

在build.gradle文件中

dependencies {
    compile 'com.google.android.gms:play-services:6.5.87'
}

步骤: *确保该设备具有Google Play服务APK *安装最新的Google Play服务

enter image description here

  • https://code.google.com/apis/console/
  • 创建项目
  • 启用“Google Maps Android API v2” enter image description here
  • 在API控制台中注册项目中的SHA1(现在,你需要写SHA1;你的.app.package.name )并获取API

并在androidmanifest.xml文件中添加应用程序标记中的元标记

<meta-data
 android:name="com.google.android.maps.v2.API_KEY"
 android:value="Your Api Key goes here" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

在地图上显示地图和位置所需的权限。

<!--Permissions-->

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />